Merge branch 'branch-1' into branch-v2
This commit is contained in:
466
src/shared/services/auth/authServices.ts
Normal file
466
src/shared/services/auth/authServices.ts
Normal file
@@ -0,0 +1,466 @@
|
||||
import AuthModel from "../../V1Models/Auth/userAuthModel.ts";
|
||||
import UsersDataModel from "../../V1Models/Auth/user.ts";
|
||||
import nodemailer from "nodemailer";
|
||||
import tokenType from "../../V1Models/Auth/tokenModel.ts";
|
||||
import Jwt from "jsonwebtoken";
|
||||
|
||||
import { hashValidator, hashGenerate } from "../../utils/Hasing.ts";
|
||||
import redis from "../../redis/redis.ts";
|
||||
import { tokenGenerator, tokenRefreshGenerator } from "../../utils/token.ts";
|
||||
interface Iserviceuser {
|
||||
userName: string;
|
||||
Email: string;
|
||||
Password: string;
|
||||
profilePicture: string;
|
||||
}
|
||||
interface IloginUser {
|
||||
Email: string;
|
||||
Password: string;
|
||||
fingerprint: string;
|
||||
}
|
||||
interface IresetToken {
|
||||
resetToken: string;
|
||||
newPassword: string;
|
||||
confirmPassword: string;
|
||||
}
|
||||
interface IUser {
|
||||
Email: string;
|
||||
userName: string;
|
||||
_id: string;
|
||||
}
|
||||
const jwt_secret = process.env.JWT_SECRET as string;
|
||||
export function extractOrg(Email: string) {
|
||||
return Email.split("@")[1].split(".")[0];
|
||||
}
|
||||
async function findExistingUserEmail(Email: string) {
|
||||
const organization = extractOrg(Email);
|
||||
const existingUser = await AuthModel(organization).findOne({
|
||||
Email: Email,
|
||||
isArchive: false,
|
||||
});
|
||||
return existingUser;
|
||||
}
|
||||
|
||||
export const AuthSignup = async (
|
||||
data: Iserviceuser
|
||||
): Promise<{
|
||||
status: string;
|
||||
}> => {
|
||||
const { userName, Email, Password, profilePicture } = data;
|
||||
try {
|
||||
let role;
|
||||
const caseChange = Email.toLowerCase();
|
||||
const organization = extractOrg(caseChange);
|
||||
const Existing_User = await findExistingUserEmail(caseChange);
|
||||
if (Existing_User) {
|
||||
return { status: "User already exists" };
|
||||
} else {
|
||||
const hashPassword = await hashGenerate(Password);
|
||||
const userCount = await AuthModel(organization).countDocuments({});
|
||||
role = userCount === 0 ? "Admin" : "User";
|
||||
const isShare = "true";
|
||||
const newuser = await AuthModel(organization).create({
|
||||
userName: userName,
|
||||
Email: caseChange,
|
||||
Password: hashPassword,
|
||||
});
|
||||
const UserDatas = await UsersDataModel(organization).create({
|
||||
userId: newuser._id,
|
||||
role: role,
|
||||
isShare: isShare,
|
||||
profilePicture: profilePicture,
|
||||
});
|
||||
return { status: "Success" };
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
return {
|
||||
status: error.message,
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
status: "An unexpected error occurred",
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const AuthLogin = async (
|
||||
data: IloginUser
|
||||
): Promise<{ status: string; data?: Object }> => {
|
||||
try {
|
||||
const { Email, Password, fingerprint } = data;
|
||||
const caseChange = Email.toLowerCase();
|
||||
const organization = extractOrg(caseChange);
|
||||
const Existing_User = await findExistingUserEmail(caseChange);
|
||||
if (!Existing_User) return { status: "User Not Found!!! Kindly signup..." };
|
||||
else {
|
||||
const existingMail = await getUserFromCacheOrDB(caseChange);
|
||||
const checkPassword = await hashValidator(
|
||||
Password,
|
||||
existingMail.Password
|
||||
);
|
||||
if (!checkPassword)
|
||||
return {
|
||||
status: "Email & Password is invalid...Check the credentials",
|
||||
};
|
||||
|
||||
const browserID = existingMail.visitorBrowserID;
|
||||
if (browserID && browserID !== fingerprint) {
|
||||
await Promise.all([
|
||||
redis.del(`token:${caseChange}`),
|
||||
redis.del(`user:${caseChange}`),
|
||||
]);
|
||||
await AuthModel(organization).updateOne(
|
||||
{ Email: caseChange },
|
||||
{ visitorBrowserID: "" }
|
||||
);
|
||||
await tokenType(organization).updateOne(
|
||||
{ userId: Existing_User._id },
|
||||
{ refreshToken: "" }
|
||||
);
|
||||
return {
|
||||
status: "Already LoggedIn on another browser....Please logout!!!",
|
||||
};
|
||||
}
|
||||
const UserData = await UsersDataModel(organization).findOne({
|
||||
userId: existingMail._id,
|
||||
isArchive: false,
|
||||
});
|
||||
if (!UserData)
|
||||
return {
|
||||
status: "User_Datas not found",
|
||||
};
|
||||
const redisTokenRaw = await redis.get(`token:${caseChange}`);
|
||||
if (redisTokenRaw) {
|
||||
const cachedTokens = JSON.parse(redisTokenRaw);
|
||||
try {
|
||||
Jwt.verify(cachedTokens.token, jwt_secret);
|
||||
return {
|
||||
status: "Success",
|
||||
data: {
|
||||
message: "login successfull",
|
||||
email: existingMail.Email,
|
||||
name: existingMail.userName,
|
||||
userId: existingMail._id,
|
||||
isShare: UserData.isShare,
|
||||
token: cachedTokens.token,
|
||||
refreshToken: cachedTokens.refreshToken,
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
console.log("Access token expired. Generating new...");
|
||||
}
|
||||
}
|
||||
const tokenValidation = tokenGenerator(
|
||||
existingMail.Email,
|
||||
UserData.role,
|
||||
existingMail._id,
|
||||
organization
|
||||
);
|
||||
const refreshTokenvalidation = tokenRefreshGenerator(
|
||||
existingMail.Email,
|
||||
UserData.role,
|
||||
existingMail._id,
|
||||
organization
|
||||
);
|
||||
|
||||
await handleTokenCache(
|
||||
existingMail._id.toString(),
|
||||
existingMail.Email,
|
||||
tokenValidation,
|
||||
refreshTokenvalidation
|
||||
);
|
||||
|
||||
const updatedUser = await AuthModel(organization)
|
||||
.findByIdAndUpdate(
|
||||
existingMail._id,
|
||||
{ visitorBrowserID: fingerprint },
|
||||
{ new: true }
|
||||
)
|
||||
.select("-__v -Profilepicture");
|
||||
if (!updatedUser)
|
||||
return {
|
||||
status: "User update failed.",
|
||||
};
|
||||
await redis.setex(
|
||||
`user:${existingMail.Email}`,
|
||||
3600,
|
||||
JSON.stringify(updatedUser)
|
||||
);
|
||||
const finalResult = {
|
||||
message: "login successfull",
|
||||
email: existingMail.Email,
|
||||
name: existingMail.userName,
|
||||
userId: existingMail._id,
|
||||
isShare: UserData.isShare,
|
||||
// updatedUser: updatedUser as IUser,
|
||||
token: tokenValidation,
|
||||
refreshToken: refreshTokenvalidation,
|
||||
};
|
||||
return {
|
||||
status: "Success",
|
||||
data: finalResult,
|
||||
};
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
return {
|
||||
status: error.message,
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
status: "An unexpected error occurred",
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
export const AuthLogout = async ({
|
||||
Email,
|
||||
}: Iserviceuser): Promise<{ status: string }> => {
|
||||
try {
|
||||
const caseChange = Email.toLowerCase();
|
||||
const organization = extractOrg(caseChange);
|
||||
const Existing_User = await findExistingUserEmail(caseChange);
|
||||
if (!Existing_User) return { status: "User not found" };
|
||||
|
||||
const tokenData = await tokenType(organization).findOne({
|
||||
userId: Existing_User._id,
|
||||
isArchive: false,
|
||||
});
|
||||
|
||||
if (!tokenData) return { status: "Token not found" };
|
||||
await Promise.all([
|
||||
redis.del(`token:${caseChange}`),
|
||||
redis.del(`user:${caseChange}`),
|
||||
]);
|
||||
tokenData.refreshToken = "";
|
||||
await tokenData.save();
|
||||
Existing_User.visitorBrowserID = "";
|
||||
await Existing_User.save();
|
||||
return { status: "Success" };
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
return {
|
||||
status: error.message,
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
status: "An unexpected error occurred",
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
export const forgetPassword = async ({
|
||||
Email,
|
||||
}: Iserviceuser): Promise<{ status: string }> => {
|
||||
try {
|
||||
const caseChange = Email.toLowerCase();
|
||||
const organization = extractOrg(caseChange);
|
||||
const Existing_User = await findExistingUserEmail(caseChange);
|
||||
if (Existing_User) {
|
||||
if (Existing_User.lastPasswordReset) {
|
||||
const lastPasswordReset = Existing_User.lastPasswordReset;
|
||||
const now = Date.now();
|
||||
const timeDiff = now - lastPasswordReset;
|
||||
const diffInHours = Math.floor(timeDiff / (1000 * 60 * 60));
|
||||
if (diffInHours < 24)
|
||||
return {
|
||||
status: "You can only reset your password once every 24 hours.",
|
||||
};
|
||||
}
|
||||
const transport = nodemailer.createTransport({
|
||||
service: "gmail",
|
||||
secure: true,
|
||||
auth: {
|
||||
user: process.env.EMAIL_USER,
|
||||
pass: process.env.EMAIL_PASS,
|
||||
},
|
||||
});
|
||||
const resetToken = tokenGenerator(
|
||||
Email,
|
||||
Existing_User.Role as string,
|
||||
Existing_User._id as string,
|
||||
organization
|
||||
);
|
||||
const userTokenData = await tokenType(organization).findOne({
|
||||
Email: Email,
|
||||
isArchive: false,
|
||||
});
|
||||
if (!userTokenData) {
|
||||
await tokenType(organization).create({
|
||||
Email: Existing_User.Email,
|
||||
userId: Existing_User._id,
|
||||
resetToken: resetToken,
|
||||
resetTokenExpiry: Date.now(),
|
||||
});
|
||||
} else {
|
||||
userTokenData.resetToken = resetToken;
|
||||
userTokenData.resetTokenExpiry = new Date();
|
||||
await userTokenData.save();
|
||||
}
|
||||
const Receiver = {
|
||||
from: process.env.EMAIL_USER,
|
||||
to: Email,
|
||||
subject: "Password Reset Request",
|
||||
text: `Click the below link to generate the new password \n ${
|
||||
process.env.CLIENT_URL
|
||||
}/reset-password/${tokenGenerator(
|
||||
Email,
|
||||
Existing_User.Role as string,
|
||||
Existing_User._id as string,
|
||||
organization
|
||||
)}`,
|
||||
};
|
||||
await transport.sendMail(Receiver);
|
||||
|
||||
return { status: "Success" };
|
||||
} else {
|
||||
return { status: "Email not found" };
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
return {
|
||||
status: error.message,
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
status: "An unexpected error occurred",
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
export const resetPassword = async ({
|
||||
resetToken,
|
||||
newPassword,
|
||||
confirmPassword,
|
||||
}: IresetToken): Promise<{ status: string }> => {
|
||||
try {
|
||||
const decoded = Jwt.verify(resetToken, "Milestone");
|
||||
if (typeof decoded === "string" || !("email" in decoded))
|
||||
return { status: "Invalid token payload." };
|
||||
|
||||
const Email = decoded.email;
|
||||
const organization = extractOrg(Email);
|
||||
if (newPassword !== confirmPassword) return { status: "Password mismatch" };
|
||||
|
||||
const userData = await AuthModel(organization).findOne({
|
||||
Email: Email,
|
||||
isArchive: false,
|
||||
});
|
||||
const userTokenData = await tokenType(organization).findOne({
|
||||
Email: Email,
|
||||
isArchive: false,
|
||||
});
|
||||
if (!userData || !userTokenData) return { status: "User not found" };
|
||||
else {
|
||||
const tokenexpiry = userTokenData.resetTokenExpiry as Date;
|
||||
const now = Date.now();
|
||||
const tokenAge = tokenexpiry ? now - tokenexpiry.getTime() : 0;
|
||||
const TOKEN_EXPIRATION_TIME = 15 * 60 * 1000;
|
||||
|
||||
if (!tokenexpiry || tokenAge > TOKEN_EXPIRATION_TIME)
|
||||
return { status: "Token is invalid or expired." };
|
||||
const hashPassword = await hashGenerate(newPassword);
|
||||
const lastPasswordReset = Date.now();
|
||||
await AuthModel(organization).findByIdAndUpdate(
|
||||
userData._id,
|
||||
{ Password: hashPassword, lastPasswordReset: lastPasswordReset },
|
||||
{ new: true }
|
||||
);
|
||||
userTokenData.resetToken = "";
|
||||
userTokenData.resetTokenExpiry = undefined;
|
||||
await userTokenData.save();
|
||||
await ResetFromCacheOrDB(Email);
|
||||
return { status: "Success" };
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
return {
|
||||
status: error.message,
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
status: "An unexpected error occurred",
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
async function getUserFromCacheOrDB(Email: string) {
|
||||
const redisUserKey = `user:${Email}`;
|
||||
try {
|
||||
const cachedUser = await redis.get(redisUserKey);
|
||||
if (cachedUser) return JSON.parse(cachedUser);
|
||||
|
||||
const Existing_User = await findExistingUserEmail(Email);
|
||||
|
||||
if (Existing_User) {
|
||||
await redis.setex(redisUserKey, 3600, JSON.stringify(Existing_User));
|
||||
}
|
||||
return Existing_User;
|
||||
} catch (error) {
|
||||
return error;
|
||||
}
|
||||
}
|
||||
|
||||
async function ResetFromCacheOrDB(Email: string) {
|
||||
const redisUserKey = `user:${Email}`;
|
||||
try {
|
||||
const organization = extractOrg(Email);
|
||||
const cachedUser = await redis.get(redisUserKey);
|
||||
if (cachedUser) {
|
||||
const user = await AuthModel(organization)
|
||||
.findOne({
|
||||
Email: Email,
|
||||
isArchive: false,
|
||||
})
|
||||
.lean()
|
||||
.select("-__v -Profilepicture");
|
||||
|
||||
if (user) {
|
||||
await redis.setex(redisUserKey, 3600, JSON.stringify(user));
|
||||
}
|
||||
return user;
|
||||
}
|
||||
} catch (error) {
|
||||
return error;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleTokenCache(
|
||||
userId: string,
|
||||
Email: string,
|
||||
token: string,
|
||||
refreshToken: string
|
||||
) {
|
||||
const redisTokenKey = `token:${Email}`;
|
||||
try {
|
||||
const organization = extractOrg(Email);
|
||||
const tokenPayload = {
|
||||
token,
|
||||
refreshToken,
|
||||
userId,
|
||||
Email,
|
||||
};
|
||||
await redis.setex(redisTokenKey, 3600, JSON.stringify(tokenPayload));
|
||||
|
||||
let tokenDoc = await tokenType(organization).findOne({
|
||||
userId,
|
||||
isArchive: false,
|
||||
});
|
||||
if (!tokenDoc) {
|
||||
tokenDoc = await tokenType(organization).create({ userId, refreshToken });
|
||||
} else {
|
||||
await tokenType(organization).findByIdAndUpdate(
|
||||
tokenDoc._id,
|
||||
{ refreshToken },
|
||||
{ new: true }
|
||||
);
|
||||
}
|
||||
|
||||
return tokenPayload;
|
||||
} catch (error) {
|
||||
return error;
|
||||
}
|
||||
}
|
||||
155
src/shared/services/builder/cameraService.ts
Normal file
155
src/shared/services/builder/cameraService.ts
Normal file
@@ -0,0 +1,155 @@
|
||||
import UsersDataModel from "../../V1Models/Auth/user.ts";
|
||||
import cameraModel from "../../V1Models/Builder/cameraModel.ts";
|
||||
import { existingProjectById } from "../helpers/v1projecthelperFns.ts";
|
||||
interface IcameraData {
|
||||
userId: string;
|
||||
role: string;
|
||||
position: Object;
|
||||
target: Object;
|
||||
rotation: Object;
|
||||
organization: string;
|
||||
projectId: string;
|
||||
versionId: string;
|
||||
}
|
||||
interface IgetCameras {
|
||||
organization: string;
|
||||
userId?: string;
|
||||
role: string;
|
||||
}
|
||||
export const SetCamera = async (
|
||||
data: IcameraData
|
||||
): Promise<{ status: string; data?: Object }> => {
|
||||
try {
|
||||
const {
|
||||
userId,
|
||||
role,
|
||||
position,
|
||||
target,
|
||||
rotation,
|
||||
organization,
|
||||
projectId,
|
||||
versionId,
|
||||
} = data;
|
||||
const LivingProject = await existingProjectById(
|
||||
projectId,
|
||||
organization,
|
||||
userId
|
||||
);
|
||||
if (!LivingProject) return { status: "Project not found" };
|
||||
const existingCamera = await cameraModel(organization).findOne({
|
||||
userId: userId,
|
||||
});
|
||||
if (existingCamera) {
|
||||
const updateCamera = await cameraModel(organization).findOneAndUpdate(
|
||||
{
|
||||
userId: userId,
|
||||
projectId: projectId,
|
||||
versionId: versionId,
|
||||
isArchive: false,
|
||||
},
|
||||
{ position: position, target: target, rotation: rotation },
|
||||
{ new: true }
|
||||
);
|
||||
return {
|
||||
status: "Update Success",
|
||||
data: updateCamera,
|
||||
};
|
||||
} else {
|
||||
const newCamera = await cameraModel(organization).create({
|
||||
userId,
|
||||
projectId,
|
||||
versionId,
|
||||
position,
|
||||
target,
|
||||
rotation,
|
||||
});
|
||||
|
||||
return {
|
||||
status: "Success",
|
||||
data: newCamera,
|
||||
};
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
return {
|
||||
status: error.message,
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
status: "An unexpected error occurred",
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
export const GetCamers = async (
|
||||
data: IgetCameras
|
||||
): Promise<{ status: string; data?: Object }> => {
|
||||
const { userId, organization, role } = data;
|
||||
try {
|
||||
const findCamera = await cameraModel(organization).findOne({
|
||||
userId: userId,
|
||||
});
|
||||
if (!findCamera) {
|
||||
return { status: "Camera not found" };
|
||||
} else {
|
||||
return { status: "Success", data: findCamera };
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
return {
|
||||
status: error.message,
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
status: "An unexpected error occurred",
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
export const onlineActiveDatas = async (
|
||||
data: IgetCameras
|
||||
): Promise<{ status: string; data?: Object }> => {
|
||||
const { organization } = data;
|
||||
try {
|
||||
const findactiveUsers = await UsersDataModel(organization).find({
|
||||
activeStatus: "online",
|
||||
});
|
||||
|
||||
const cameraDataPromises = findactiveUsers.map(async (activeUser: any) => {
|
||||
const cameraData = await cameraModel(organization)
|
||||
.findOne({ userId: activeUser._id })
|
||||
.select("position target rotation -_id");
|
||||
|
||||
if (cameraData) {
|
||||
return {
|
||||
position: cameraData.position,
|
||||
target: cameraData.target,
|
||||
rotation: cameraData.rotation,
|
||||
userData: {
|
||||
_id: activeUser._id,
|
||||
userName: activeUser.userName,
|
||||
email: activeUser.email,
|
||||
activeStatus: activeUser.activeStatus,
|
||||
},
|
||||
};
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
const cameraDatas = (await Promise.all(cameraDataPromises)).filter(
|
||||
(singledata: any) => singledata !== null
|
||||
);
|
||||
|
||||
return { status: "Success", data: cameraDatas };
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
return {
|
||||
status: error.message,
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
status: "An unexpected error occurred",
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -76,3 +76,15 @@ export const generateUntitledProjectName = async (
|
||||
|
||||
return newNumber === 0 ? "Untitled" : `Untitled ${newNumber}`;
|
||||
};
|
||||
export const existingProjectById = async (
|
||||
projectId: string,
|
||||
organization: string,
|
||||
userId: string
|
||||
) => {
|
||||
const projectData = await projectModel(organization).findOne({
|
||||
_id: projectId,
|
||||
createdBy: userId,
|
||||
isArchive: false,
|
||||
});
|
||||
return projectData;
|
||||
};
|
||||
|
||||
90
src/shared/services/helpers/v1projecthelperFns.ts
Normal file
90
src/shared/services/helpers/v1projecthelperFns.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
import projectModel from "../../V1Models/Project/project-model.ts";
|
||||
import { Types } from "mongoose";
|
||||
import versionModel from "../../V1Models/Version/versionModel.ts";
|
||||
import AuthModel from "../../V1Models/Auth/userAuthModel.ts";
|
||||
export const existingProject = async (
|
||||
projectUuid: string,
|
||||
organization: string,
|
||||
userId: string
|
||||
) => {
|
||||
const projectData = await projectModel(organization).findOne({
|
||||
projectUuid: projectUuid,
|
||||
createdBy: userId,
|
||||
isArchive: false,
|
||||
});
|
||||
return projectData;
|
||||
};
|
||||
|
||||
export const existingUser = async (userId: string, organization: string) => {
|
||||
if (!Types.ObjectId.isValid(userId)) {
|
||||
console.log("Invalid ObjectId format");
|
||||
return null;
|
||||
}
|
||||
const userData = await AuthModel(organization).findOne({
|
||||
_id: userId,
|
||||
});
|
||||
return userData;
|
||||
};
|
||||
|
||||
export const archiveProject = async (
|
||||
projectId: string,
|
||||
organization: string
|
||||
) => {
|
||||
return await projectModel(organization).findByIdAndUpdate(
|
||||
projectId,
|
||||
{ isArchive: true },
|
||||
{ new: true }
|
||||
);
|
||||
};
|
||||
export const previousVersion = async (
|
||||
projectId: string,
|
||||
organization: string
|
||||
) => {
|
||||
const result = await versionModel(organization).findOne({
|
||||
projectId: projectId,
|
||||
isArchive: false,
|
||||
});
|
||||
// .sort({ version: -1 });
|
||||
return result;
|
||||
};
|
||||
export const generateUntitledProjectName = async (
|
||||
organization: string,
|
||||
userId: string
|
||||
): Promise<string> => {
|
||||
const projects = await projectModel(organization)
|
||||
.find({
|
||||
createdBy: userId,
|
||||
isArchive: false,
|
||||
projectName: { $regex: /^Untitled(?: \s?\d+)?$/, $options: "i" },
|
||||
})
|
||||
.select("projectName");
|
||||
|
||||
const usedNumbers = new Set<number>();
|
||||
|
||||
for (const proj of projects) {
|
||||
const match = proj.projectName.match(/^Untitled(?:\s?(\d+))?$/);
|
||||
if (match) {
|
||||
const num = match[1] ? parseInt(match[1], 10) : 0;
|
||||
usedNumbers.add(num);
|
||||
}
|
||||
}
|
||||
|
||||
let newNumber = 0;
|
||||
while (usedNumbers.has(newNumber)) {
|
||||
newNumber++;
|
||||
}
|
||||
|
||||
return newNumber === 0 ? "Untitled" : `Untitled ${newNumber}`;
|
||||
};
|
||||
export const existingProjectById = async (
|
||||
projectId: string,
|
||||
organization: string,
|
||||
userId: string
|
||||
) => {
|
||||
const projectData = await projectModel(organization).findOne({
|
||||
_id: projectId,
|
||||
createdBy: userId,
|
||||
isArchive: false,
|
||||
});
|
||||
return projectData;
|
||||
};
|
||||
@@ -57,26 +57,29 @@ export const searchProject = async (data: searchProjectInterface) => {
|
||||
if (!userExisting) return { status: "User not found" };
|
||||
const findprojectName = await projectModel(organization).find({
|
||||
projectName: { $regex: `${searchName}`, $options: "i" }, // 'i' makes it case-insensitive
|
||||
isArchive: false,
|
||||
})
|
||||
if (!findprojectName||findprojectName.length===0) return { status: "Project not found" }
|
||||
isArchive: false,
|
||||
});
|
||||
if (!findprojectName || findprojectName.length === 0)
|
||||
return { status: "Project not found" };
|
||||
return { status: "Success", data: findprojectName };
|
||||
} catch (error: unknown) {
|
||||
return { status: error };
|
||||
}
|
||||
}
|
||||
};
|
||||
export const searchTrashProject = async (data: searchProjectInterface) => {
|
||||
try {
|
||||
const { userId, organization, searchName } = data;
|
||||
const userExisting = await existingUser(userId, organization);
|
||||
if (!userExisting) return { status: "User not found" };
|
||||
const findprojectName = await projectModel(organization).find({
|
||||
projectName: { $regex: `${searchName}`, $options: "i" },
|
||||
isArchive: true,isDeleted:false
|
||||
})
|
||||
if (!findprojectName||findprojectName.length===0) return { status: "Project not found" }
|
||||
projectName: { $regex: `${searchName}`, $options: "i" },
|
||||
isArchive: true,
|
||||
isDeleted: false,
|
||||
});
|
||||
if (!findprojectName || findprojectName.length === 0)
|
||||
return { status: "Project not found" };
|
||||
return { status: "Success", data: findprojectName };
|
||||
} catch (error: unknown) {
|
||||
return { status: error };
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -43,7 +43,7 @@ export const createProject = async (data: CreateProjectInput) => {
|
||||
return {
|
||||
status: "user_not_found",
|
||||
};
|
||||
}
|
||||
}
|
||||
const projectExisting = await existingProject(
|
||||
projectUuid,
|
||||
organization,
|
||||
@@ -125,7 +125,7 @@ export const DeleteProject = async (data: ProjectInterface) => {
|
||||
{ isArchive: true, DeletedAt: new Date() },
|
||||
{ new: true }
|
||||
);
|
||||
if (updateProject) return { status: "Success",project: updateProject };
|
||||
if (updateProject) return { status: "Success", project: updateProject };
|
||||
} catch (error: unknown) {
|
||||
return { status: error };
|
||||
}
|
||||
|
||||
208
src/shared/services/v1Project/v1projectservice.ts
Normal file
208
src/shared/services/v1Project/v1projectservice.ts
Normal file
@@ -0,0 +1,208 @@
|
||||
import projectModel from "../../V1Models/Project/project-model.ts";
|
||||
import versionModel from "../../V1Models/Version/versionModel.ts";
|
||||
import {
|
||||
existingProject,
|
||||
existingUser,
|
||||
archiveProject,
|
||||
previousVersion,
|
||||
generateUntitledProjectName,
|
||||
} from "../helpers/v1projecthelperFns.ts";
|
||||
import UsersDataModel from "../../V1Models/Auth/user.ts";
|
||||
interface CreateProjectInput {
|
||||
projectName: string;
|
||||
projectUuid: string;
|
||||
userId: string; // user ID
|
||||
thumbnail?: string;
|
||||
sharedUsers?: string[];
|
||||
organization: string;
|
||||
}
|
||||
interface updateProjectInput {
|
||||
projectName: string;
|
||||
projectId: string;
|
||||
userId: string; // user ID
|
||||
thumbnail?: string;
|
||||
sharedUsers?: string[];
|
||||
organization: string;
|
||||
role: string;
|
||||
}
|
||||
interface GetProjectsInterface {
|
||||
userId: string;
|
||||
organization: string;
|
||||
role: string;
|
||||
}
|
||||
interface ProjectInterface {
|
||||
projectId: string;
|
||||
userId: string;
|
||||
organization: string;
|
||||
role: string;
|
||||
}
|
||||
interface RoleFilter {
|
||||
isArchive: boolean;
|
||||
createdBy?: string;
|
||||
}
|
||||
export const createProject = async (data: CreateProjectInput) => {
|
||||
try {
|
||||
const { thumbnail, sharedUsers, projectUuid, userId, organization } = data;
|
||||
const userExisting = await existingUser(userId, organization);
|
||||
if (!userExisting) {
|
||||
return {
|
||||
status: "user_not_found",
|
||||
};
|
||||
}
|
||||
const projectExisting = await existingProject(
|
||||
projectUuid,
|
||||
organization,
|
||||
userId
|
||||
);
|
||||
|
||||
if (projectExisting) {
|
||||
return {
|
||||
status: "project_exists",
|
||||
project: projectExisting,
|
||||
};
|
||||
}
|
||||
const newProjectName = await generateUntitledProjectName(
|
||||
organization,
|
||||
userId
|
||||
);
|
||||
const project = await projectModel(organization).create({
|
||||
projectName: newProjectName,
|
||||
projectUuid: projectUuid,
|
||||
createdBy: userId,
|
||||
thumbnail: thumbnail,
|
||||
sharedUsers: sharedUsers || [],
|
||||
isArchive: false,
|
||||
});
|
||||
const versionData = await previousVersion(project._id, organization);
|
||||
if (!versionData || versionData.length === 0) {
|
||||
const newVersion = await versionModel(organization).create({
|
||||
projectId: project._id,
|
||||
createdBy: userId,
|
||||
version: 0.0,
|
||||
});
|
||||
await projectModel(organization).findByIdAndUpdate(
|
||||
{ _id: project._id, isArchive: false },
|
||||
{ total_versions: `v-${newVersion.version.toFixed(2)}` }
|
||||
);
|
||||
}
|
||||
return {
|
||||
status: "Success",
|
||||
project: project,
|
||||
};
|
||||
} catch (error) {
|
||||
console.log("error: ", error);
|
||||
return {
|
||||
status: error,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
export const GetAllProjects = async (data: GetProjectsInterface) => {
|
||||
try {
|
||||
const { userId, organization, role } = data;
|
||||
await existingUser(userId, organization);
|
||||
if (!existingUser) return { status: "User not found" };
|
||||
let filter = { isArchive: false } as RoleFilter;
|
||||
if (role === "User") {
|
||||
filter.createdBy = userId;
|
||||
}
|
||||
const projectDatas = await projectModel(organization)
|
||||
.find(filter)
|
||||
.select("_id projectName createdBy thumbnail createdAt projectUuid");
|
||||
if (projectDatas) return { status: "Success", Datas: projectDatas };
|
||||
} catch (error: unknown) {
|
||||
return { status: error };
|
||||
}
|
||||
};
|
||||
|
||||
export const DeleteProject = async (data: ProjectInterface) => {
|
||||
try {
|
||||
const { projectId, organization, userId, role } = data;
|
||||
const ExistingUser = await existingUser(userId, organization);
|
||||
if (!ExistingUser) return { status: "User not found" };
|
||||
let filter = { _id: projectId, isArchive: false } as RoleFilter;
|
||||
if (role === "User") {
|
||||
filter.createdBy = userId;
|
||||
}
|
||||
const existingProject = await projectModel(organization).findOne(filter);
|
||||
if (!existingProject) return { status: "Project not found" };
|
||||
const updateProject = await projectModel(organization).findOneAndUpdate(
|
||||
filter,
|
||||
{ isArchive: true, DeletedAt: new Date() },
|
||||
{ new: true }
|
||||
);
|
||||
if (updateProject) return { status: "Success", project: updateProject };
|
||||
} catch (error: unknown) {
|
||||
return { status: error };
|
||||
}
|
||||
};
|
||||
export const updateProject = async (data: updateProjectInput) => {
|
||||
try {
|
||||
const { projectId, organization, userId, projectName, thumbnail, role } =
|
||||
data;
|
||||
const ExistingUser = await existingUser(userId, organization);
|
||||
if (!ExistingUser) return { status: "User not found" };
|
||||
let filter = { _id: projectId, isArchive: false } as RoleFilter;
|
||||
if (role === "User") {
|
||||
filter.createdBy = userId;
|
||||
}
|
||||
const existingProject = await projectModel(organization).findOne(filter);
|
||||
if (!existingProject) return { status: "Project not found" };
|
||||
if (projectName !== undefined) projectName;
|
||||
if (thumbnail !== undefined) thumbnail;
|
||||
const updateProject = await projectModel(organization)
|
||||
.findOneAndUpdate(
|
||||
filter,
|
||||
{ projectName: projectName, thumbnail: thumbnail },
|
||||
{ new: true }
|
||||
)
|
||||
.select("_id projectName createdBy thumbnail createdAt");
|
||||
if (updateProject) return { status: "Success", data: updateProject };
|
||||
} catch (error: unknown) {
|
||||
return { status: error };
|
||||
}
|
||||
};
|
||||
const maxLength: number = 6;
|
||||
export const viewProject = async (data: ProjectInterface) => {
|
||||
try {
|
||||
const { projectId, organization, userId, role } = data;
|
||||
const userExisting = await existingUser(userId, organization);
|
||||
if (!userExisting) return { status: "User not found" };
|
||||
const RecentUserDoc = await UsersDataModel(organization).findOne({
|
||||
userId: userId,
|
||||
isArchive: false,
|
||||
});
|
||||
let filter = { _id: projectId, isArchive: false } as RoleFilter;
|
||||
if (role === "User") {
|
||||
filter.createdBy = userId;
|
||||
}
|
||||
const existingProject = await projectModel(organization).findOne(filter);
|
||||
if (!existingProject) return { status: "Project not found" };
|
||||
const newArr = RecentUserDoc?.recentlyViewed || [];
|
||||
if (RecentUserDoc?.recentlyViewed.length === 0) {
|
||||
newArr.push(projectId);
|
||||
await RecentUserDoc.save();
|
||||
} else {
|
||||
const index = newArr.indexOf(projectId);
|
||||
if (index !== -1) {
|
||||
newArr.splice(index, 1);
|
||||
}
|
||||
newArr.unshift(projectId);
|
||||
|
||||
if (newArr.length > maxLength) {
|
||||
newArr.pop();
|
||||
}
|
||||
}
|
||||
await UsersDataModel(organization).updateOne(
|
||||
{ _id: userId },
|
||||
{ recentlyViewed: newArr },
|
||||
{ new: true }
|
||||
);
|
||||
const projectData = await projectModel(organization)
|
||||
.findOneAndUpdate(filter, { isViewed: Date.now() }, { new: true })
|
||||
.select("_id projectName createdBy thumbnail createdAt");
|
||||
return { status: "Success", data: projectData };
|
||||
} catch (error: unknown) {
|
||||
return { status: error };
|
||||
}
|
||||
};
|
||||
92
src/shared/services/v1home/v1homeservice.ts
Normal file
92
src/shared/services/v1home/v1homeservice.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
import projectModel from "../../V1Models/Project/project-model.ts";
|
||||
import userModel from "../../model/user-Model.ts";
|
||||
import UsersDataModel from "../../V1Models/Auth/user.ts";
|
||||
import { existingUser } from "../helpers/ProjecthelperFn.ts";
|
||||
|
||||
interface IRecentData {
|
||||
organization: string;
|
||||
userId: string;
|
||||
role: string;
|
||||
}
|
||||
interface IProject {
|
||||
_id: string;
|
||||
projectName: string;
|
||||
createdBy: string;
|
||||
thumbnail?: string;
|
||||
createdAt: Date;
|
||||
isViewed?: number;
|
||||
}
|
||||
interface searchProjectInterface {
|
||||
searchName: string;
|
||||
userId: string;
|
||||
organization: string;
|
||||
}
|
||||
interface RoleFilter {
|
||||
isArchive: boolean;
|
||||
createdBy?: string;
|
||||
}
|
||||
export const RecentlyAdded = async (data: IRecentData) => {
|
||||
try {
|
||||
const { userId, organization, role } = data;
|
||||
const userExisting = await existingUser(userId, organization);
|
||||
if (!userExisting) return { status: "User not found" };
|
||||
const userRecentData = await UsersDataModel(organization)
|
||||
.findOne({ userId: userId, isArchive: false })
|
||||
.populate({
|
||||
path: "recentlyViewed",
|
||||
model: projectModel(organization),
|
||||
select: "_id",
|
||||
});
|
||||
let filter = { isArchive: false } as RoleFilter;
|
||||
if (role === "User") {
|
||||
filter.createdBy = userId;
|
||||
}
|
||||
const populatedProjects = userRecentData.recentlyViewed as IProject[];
|
||||
const RecentDatas = await Promise.all(
|
||||
populatedProjects.map(async (project) => {
|
||||
const projectExisting = await projectModel(organization)
|
||||
.findOne(filter)
|
||||
.select("_id projectName createdBy thumbnail createdAt isViewed");
|
||||
return projectExisting;
|
||||
})
|
||||
);
|
||||
|
||||
const filteredProjects = RecentDatas.filter(Boolean);
|
||||
return { status: "Success", data: filteredProjects };
|
||||
} catch (error) {
|
||||
return { status: error };
|
||||
}
|
||||
};
|
||||
export const searchProject = async (data: searchProjectInterface) => {
|
||||
try {
|
||||
const { userId, organization, searchName } = data;
|
||||
const userExisting = await existingUser(userId, organization);
|
||||
if (!userExisting) return { status: "User not found" };
|
||||
const findprojectName = await projectModel(organization).find({
|
||||
projectName: { $regex: `${searchName}`, $options: "i" }, // 'i' makes it case-insensitive
|
||||
isArchive: false,
|
||||
});
|
||||
if (!findprojectName || findprojectName.length === 0)
|
||||
return { status: "Project not found" };
|
||||
return { status: "Success", data: findprojectName };
|
||||
} catch (error: unknown) {
|
||||
return { status: error };
|
||||
}
|
||||
};
|
||||
export const searchTrashProject = async (data: searchProjectInterface) => {
|
||||
try {
|
||||
const { userId, organization, searchName } = data;
|
||||
const userExisting = await existingUser(userId, organization);
|
||||
if (!userExisting) return { status: "User not found" };
|
||||
const findprojectName = await projectModel(organization).find({
|
||||
projectName: { $regex: `${searchName}`, $options: "i" },
|
||||
isArchive: true,
|
||||
isDeleted: false,
|
||||
});
|
||||
if (!findprojectName || findprojectName.length === 0)
|
||||
return { status: "Project not found" };
|
||||
return { status: "Success", data: findprojectName };
|
||||
} catch (error: unknown) {
|
||||
return { status: error };
|
||||
}
|
||||
};
|
||||
75
src/shared/services/v1trash/v1trashservice.ts
Normal file
75
src/shared/services/v1trash/v1trashservice.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import projectModel from "../../V1Models/Project/project-model.ts";
|
||||
interface IOrg {
|
||||
organization: string;
|
||||
role: string;
|
||||
userId: string;
|
||||
}
|
||||
interface IRestore {
|
||||
projectId: string;
|
||||
organization: string;
|
||||
role: string;
|
||||
userId: string;
|
||||
}
|
||||
interface RoleFilter {
|
||||
isArchive: boolean;
|
||||
createdBy?: string;
|
||||
}
|
||||
export const TrashDatas = async (data: IOrg) => {
|
||||
try {
|
||||
const { organization, role, userId } = data;
|
||||
let filter = { isArchive: true, isDeleted: false } as RoleFilter;
|
||||
if (role === "User") {
|
||||
filter.createdBy = userId;
|
||||
}
|
||||
const TrashLists = await projectModel(organization).find(filter);
|
||||
if (!TrashLists) return { staus: "Trash is Empty" };
|
||||
const TrashDocs: any[] = [];
|
||||
for (const Trash of TrashLists) {
|
||||
const now = new Date();
|
||||
const deletedPlus15 = new Date(
|
||||
Trash.DeletedAt.getTime() + 15 * 24 * 60 * 60 * 1000
|
||||
);
|
||||
if (now > deletedPlus15) {
|
||||
console.log("now > deletedPlus15: ", now > deletedPlus15);
|
||||
await projectModel(organization).updateOne(
|
||||
{ _id: Trash._id },
|
||||
{ $set: { isDeleted: true } }
|
||||
);
|
||||
} else {
|
||||
TrashDocs.push(Trash);
|
||||
}
|
||||
}
|
||||
const ListDatas = TrashDocs.map((data) => {
|
||||
return {
|
||||
projectName: data.projectName,
|
||||
thumbnail: data.thumbnail,
|
||||
createdBy: data.createdBy,
|
||||
_id: data._id,
|
||||
};
|
||||
});
|
||||
|
||||
return { status: "Success", ListDatas };
|
||||
} catch (error) {
|
||||
return { status: error };
|
||||
}
|
||||
};
|
||||
export const RestoreTrashData = async (data: IRestore) => {
|
||||
try {
|
||||
const { projectId, organization, role, userId } = data;
|
||||
let filter = { isArchive: true, _id: projectId } as RoleFilter;
|
||||
if (role === "User") {
|
||||
filter.createdBy = userId;
|
||||
}
|
||||
const findProject = await projectModel(organization).findOne(filter);
|
||||
if (!findProject) return { status: "Project not found" };
|
||||
const restoreData = await projectModel(organization).findOneAndUpdate(
|
||||
filter,
|
||||
{ isArchive: false, DeletedAt: null },
|
||||
{ new: true }
|
||||
);
|
||||
if (!restoreData) return { status: "Project Restore unsuccessfull" };
|
||||
return { status: "Project Restored successfully" };
|
||||
} catch (error) {
|
||||
return { status: error };
|
||||
}
|
||||
};
|
||||
127
src/shared/services/version/versionService.ts
Normal file
127
src/shared/services/version/versionService.ts
Normal file
@@ -0,0 +1,127 @@
|
||||
import projectModel from "../../model/project/project-model.ts";
|
||||
import assetModel from "../../V1Models/Builder/assetModel.ts";
|
||||
import versionModel from "../../model/version/versionModel.ts";
|
||||
|
||||
class VersionService {
|
||||
async getCurrentVersion(db: string, projectId: string) {
|
||||
const project = await projectModel(db).findById(projectId);
|
||||
if (!project) throw new Error("Project not found");
|
||||
|
||||
return {
|
||||
versionNumber: parseFloat(project.Present_version || "0.0"),
|
||||
versionString: project.Present_version || "0.0",
|
||||
};
|
||||
}
|
||||
|
||||
async createNewVersion(
|
||||
db: string,
|
||||
projectId: string,
|
||||
userId: string,
|
||||
description?: string
|
||||
) {
|
||||
const project = await projectModel(db).findById(projectId);
|
||||
if (!project) throw new Error("Project not found");
|
||||
|
||||
const { versionNumber } = await this.getCurrentVersion(db, projectId);
|
||||
const newVersion = parseFloat((versionNumber + 0.1).toFixed(1));
|
||||
const versionName = `Version ${newVersion.toFixed(1)}`;
|
||||
|
||||
const version = await versionModel(db).create({
|
||||
versionName,
|
||||
version: newVersion,
|
||||
projectId: project._id,
|
||||
createdBy: userId,
|
||||
description,
|
||||
});
|
||||
|
||||
await projectModel(db).findByIdAndUpdate(projectId, {
|
||||
Present_version: newVersion.toFixed(1),
|
||||
total_versions: newVersion.toFixed(1),
|
||||
});
|
||||
|
||||
return version;
|
||||
}
|
||||
|
||||
async saveCurrentStateAsVersion(
|
||||
db: string,
|
||||
projectId: string,
|
||||
userId: string,
|
||||
description?: string
|
||||
) {
|
||||
// Create new version
|
||||
const newVersion = await this.createNewVersion(
|
||||
db,
|
||||
projectId,
|
||||
userId,
|
||||
description
|
||||
);
|
||||
|
||||
// Get all assets from previous version
|
||||
const previousVersion = parseFloat((newVersion.version - 0.1).toFixed(1));
|
||||
const previousVersionDoc = await versionModel(db).findOne({
|
||||
projectId,
|
||||
version: previousVersion,
|
||||
});
|
||||
console.log("previousVersionDoc: ", previousVersionDoc);
|
||||
|
||||
let previousAssets = [];
|
||||
if (previousVersionDoc) {
|
||||
previousAssets = await assetModel(db).find({
|
||||
projectId,
|
||||
versionId: previousVersionDoc._id,
|
||||
isArchive: false,
|
||||
});
|
||||
}
|
||||
|
||||
// Copy assets to new version
|
||||
const newAssets = await Promise.all(
|
||||
previousAssets.map(async (asset) => {
|
||||
console.log("previousAssets: ", previousAssets);
|
||||
const newAsset = { ...asset.toObject(), versionId: newVersion._id };
|
||||
delete newAsset._id;
|
||||
return await assetModel(db).create(newAsset);
|
||||
})
|
||||
);
|
||||
|
||||
return {
|
||||
version: newVersion,
|
||||
assets: newAssets,
|
||||
};
|
||||
}
|
||||
|
||||
async getVersionHistory(db: string, projectId: string) {
|
||||
const versions = await versionModel(db)
|
||||
.find({ projectId, isArchive: false })
|
||||
.sort({ version: 1 })
|
||||
.populate("createdBy", "name email");
|
||||
|
||||
const versionHistory = await Promise.all(
|
||||
versions.map(async (version) => {
|
||||
const assets = await assetModel(db).find({
|
||||
projectId,
|
||||
versionId: version._id,
|
||||
isArchive: false,
|
||||
});
|
||||
|
||||
const assetCounts = assets.reduce((acc, asset) => {
|
||||
acc[asset.type] = (acc[asset.type] || 0) + 1;
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
return {
|
||||
version: version.version.toFixed(1),
|
||||
versionName: version.versionName,
|
||||
createdAt: version.createdAt,
|
||||
createdBy: version.createdBy,
|
||||
description: version.description,
|
||||
assets: assetCounts,
|
||||
totalAssets: assets.length,
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
return versionHistory;
|
||||
}
|
||||
}
|
||||
|
||||
export default new VersionService();
|
||||
115
src/shared/services/wall/wallItemservice.ts
Normal file
115
src/shared/services/wall/wallItemservice.ts
Normal file
@@ -0,0 +1,115 @@
|
||||
import { Request, Response } from "express";
|
||||
import wallItemModel from "../../../shared/model/builder/assets/wallitems-Model.ts";
|
||||
interface IWallSetupData {
|
||||
modelUuid: string;
|
||||
modelName: string;
|
||||
type: string;
|
||||
csgposition: [];
|
||||
csgscale: [];
|
||||
position: [];
|
||||
quaternion: [];
|
||||
scale: [];
|
||||
organization: string;
|
||||
}
|
||||
interface IWallItemResult {
|
||||
data: {};
|
||||
state: string;
|
||||
}
|
||||
export class WallItems {
|
||||
static async setWallItems(data: IWallSetupData): Promise<IWallItemResult> {
|
||||
try {
|
||||
const {
|
||||
modelUuid,
|
||||
modelName,
|
||||
position,
|
||||
type,
|
||||
csgposition,
|
||||
csgscale,
|
||||
quaternion,
|
||||
scale,
|
||||
organization,
|
||||
} = data;
|
||||
const findvalue = await wallItemModel(organization).findOne({
|
||||
modelUuid: modelUuid,
|
||||
});
|
||||
|
||||
if (findvalue) {
|
||||
const updatevalue = await wallItemModel(organization).findOneAndUpdate(
|
||||
{ modelUuid: modelUuid },
|
||||
{
|
||||
modelName,
|
||||
position,
|
||||
type,
|
||||
csgposition,
|
||||
csgscale,
|
||||
quaternion,
|
||||
scale,
|
||||
},
|
||||
{ new: true } // Return the updated document
|
||||
);
|
||||
return {
|
||||
state: "Updated successfully",
|
||||
data: updatevalue,
|
||||
};
|
||||
// res.status(201).json(updatevalue);
|
||||
} else {
|
||||
const newValue = await wallItemModel(organization).create({
|
||||
modelUuid,
|
||||
modelName,
|
||||
position,
|
||||
type,
|
||||
csgposition,
|
||||
csgscale,
|
||||
quaternion,
|
||||
scale,
|
||||
});
|
||||
return {
|
||||
state: "wall Item created successfully",
|
||||
data: newValue,
|
||||
};
|
||||
// res.status(201).json(newValue);
|
||||
}
|
||||
|
||||
// Send response with the created document
|
||||
} catch (error:unknown) {
|
||||
const err = error as Error;
|
||||
console.error("Error creating wallitems:", error);
|
||||
return { state: "Failed to create wallitems", data: { message: err.message } };
|
||||
// return { state: "Failed to create wallitems", data: error } };
|
||||
// res.status(500).json({ message: "Failed to create wallitems" });
|
||||
}
|
||||
}
|
||||
static async getWallItems(req: Request, res: Response) {
|
||||
try {
|
||||
const { organization } = req.params;
|
||||
|
||||
const findValue = await wallItemModel(organization).find();
|
||||
if (!findValue) {
|
||||
res.status(200).json("wallitems not found");
|
||||
} else {
|
||||
res.status(201).json(findValue);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error get wallitems:", error);
|
||||
res.status(500).json({ error: "Failed to get wallitems" });
|
||||
}
|
||||
}
|
||||
static async deleteWallItems(req: Request, res: Response) {
|
||||
try {
|
||||
const { modelUuid, modelName, organization } = req.body;
|
||||
|
||||
const findValue = await wallItemModel(organization).findOneAndDelete({
|
||||
modelUuid: modelUuid,
|
||||
modelName: modelName,
|
||||
});
|
||||
if (!findValue) {
|
||||
res.status(200).json("user not found");
|
||||
} else {
|
||||
res.status(201).json(findValue);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error get wallitems:", error);
|
||||
res.status(500).json({ error: "Failed to get wallitems" });
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user