api collaboration

This commit is contained in:
2025-10-22 10:28:18 +05:30
parent 2826199587
commit b58433d77f
33 changed files with 5391 additions and 526 deletions

2
.env
View File

@@ -1,4 +1,4 @@
MONGO_URI=mongodb://192.168.0.110/
MONGO_URI=mongodb://192.168.0.212/
MONGO_USER=mydata
MONGO_PASSWORD=mongodb@hexr2002
MONGO_AUTH_DB=admin

1619
fdf Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -6,6 +6,7 @@ import collectionNodeRoutes from "./routes/collectionRoutes";
import edgeRoutes from "./routes/edgeRoutes";
import authRoutes from "./routes/authRoutes";
import homeRoutes from "./routes/homeRoutes";
import dummyRoutes from "./routes/dummyRoutes";
dotenv.config();
const app = express();
@@ -20,5 +21,6 @@ app.use("/api/v1", projectRoutes);
app.use("/api/v1", collectionNodeRoutes);
app.use("/api/v1", edgeRoutes);
app.use("/api/v1", homeRoutes);
app.use("/api/v1", dummyRoutes);
export default app;

View File

@@ -10,8 +10,8 @@ export const signupController = async (
res: Response
): Promise<void> => {
try {
const { userName, email, password, confirmPassword } = req.body;
if (!userName || !email || !password || !confirmPassword) {
const { userName, email, password } = req.body;
if (!userName || !email || !password) {
res.status(400).json({
message: "All fields are required",
});
@@ -21,9 +21,9 @@ export const signupController = async (
userName,
email,
password,
confirmPassword,
};
const result = await signupService(data);
console.log("result: ", result);
switch (result.status) {
case "User Already exists":

View File

@@ -3,12 +3,15 @@ import {
addAttributes,
DelAttributes,
delCollection,
DuplicateAttributes,
DuplicateCollection,
GetcollectionLists,
GetcollectionNode,
GetNodesInProject,
Nodecreation,
SetCollectionName,
updatecollection,
UpdateAttributes,
GetcollectionGraphicData,
} from "../../shared/services/collectionService";
import { AuthenticatedRequest } from "../../shared/utils/token";
export const NodeCreationController = async (
@@ -17,8 +20,14 @@ export const NodeCreationController = async (
): Promise<void> => {
try {
const { organization, userId } = req.user || {};
const { projectId, position } = req.body;
if (!organization || !projectId || !position || !userId) {
const { projectId, position, collectionName, type } = req.body;
if (
!organization ||
!projectId ||
!position ||
!userId ||
!collectionName
) {
res.status(400).json({
message: "All fields are required",
});
@@ -28,13 +37,19 @@ export const NodeCreationController = async (
organization,
projectId,
position,
type,
collectionName,
userId,
};
const result = await Nodecreation(data);
console.log("result: ", result);
switch (result.status) {
case "User not found":
res.status(404).json({ message: "User not found" });
break;
case "project not found":
res.status(200).json({
res.status(404).json({
message: "project not found",
});
break;
@@ -43,12 +58,20 @@ export const NodeCreationController = async (
message: "Collection node creation unsuccessfull",
});
break;
case "CollectionName already exists":
res.status(200).json({
message: "CollectionName already exists",
});
break;
case "Success":
res.status(200).json({
message: "Node created successfully",
collectionNodeId: result.data,
});
break;
case "Validation Error":
res.status(400).json({ message: result.data || "Validation Error" });
break;
default:
res.status(500).json({
message: "Internal server error",
@@ -62,13 +85,27 @@ export const NodeCreationController = async (
}
};
export const SetCollectionNameController = async (
export const updateCollectionController = async (
req: AuthenticatedRequest,
res: Response
): Promise<void> => {
try {
const { organization, userId } = req.user || {};
const { projectId, collectionNodeId, collectionName, position } = req.body;
const {
projectId,
collectionNodeId,
collectionName,
position,
backgroundColor,
borderColor,
fontColor,
lineColor,
lineThickness,
fontName,
lineType,
borderThickness,
cornerRadius,
} = req.body;
if (
!organization ||
!projectId ||
@@ -85,15 +122,27 @@ export const SetCollectionNameController = async (
organization,
projectId,
userId,
backgroundColor,
borderColor,
fontColor,
lineColor,
lineThickness,
fontName,
lineType,
borderThickness,
cornerRadius,
collectionNodeId,
collectionName,
position,
};
const result = await SetCollectionName(data);
const result = await updatecollection(data);
switch (result.status) {
case "User not found":
res.status(404).json({ message: "User not found" });
break;
case "project not found":
res.status(200).json({
res.status(404).json({
message: "project not found",
});
break;
@@ -141,8 +190,62 @@ export const CollectionDatas = async (
};
const result = await GetcollectionNode(data);
switch (result.status) {
case "User not found":
res.status(404).json({ message: "User not found" });
break;
case "project not found":
res.status(404).json({
message: "project not found",
});
break;
case "No collection Nodes present":
res.status(200).json({
message: "No collection Nodes present",
Collections: result.data,
});
break;
case "Success":
res.status(200).json(result.data);
break;
default:
res.status(500).json({
message: "Internal server error",
});
break;
}
} catch (error) {
res.status(500).json({
message: "Unknown error",
});
}
};
export const graphicDatas = async (
req: AuthenticatedRequest,
res: Response
): Promise<void> => {
try {
const { organization, userId } = req.user || {};
const { projectId, collectionNodeId } = req.params;
if (!organization || !projectId || !collectionNodeId || !userId) {
res.status(400).json({
message: "All fields are required",
});
return;
}
const data = {
organization,
projectId,
userId,
collectionNodeId,
};
const result = await GetcollectionGraphicData(data);
switch (result.status) {
case "User not found":
res.status(404).json({ message: "User not found" });
break;
case "project not found":
res.status(404).json({
message: "project not found",
});
break;
@@ -189,8 +292,11 @@ export const DeleteCollectionsController = async (
};
const result = await delCollection(data);
switch (result.status) {
case "User not found":
res.status(404).json({ message: "User not found" });
break;
case "project not found":
res.status(200).json({
res.status(404).json({
message: "project not found",
});
break;
@@ -240,8 +346,11 @@ export const DuplicateNodeCollectionController = async (
};
const result = await DuplicateCollection(data);
switch (result.status) {
case "User not found":
res.status(404).json({ message: "User not found" });
break;
case "project not found":
res.status(200).json({
res.status(404).json({
message: "project not found",
});
break;
@@ -285,9 +394,14 @@ export const NodesCollectionsBasedOnproject = async (
userId,
};
const result = await GetNodesInProject(data);
console.log("resultdssa: ", result);
switch (result.status) {
case "User not found":
res.status(404).json({ message: "User not found" });
break;
case "project not found":
res.status(200).json({
res.status(404).json({
message: "project not found",
});
break;
@@ -319,8 +433,8 @@ export const AddAttributesController = async (
): Promise<void> => {
try {
const { organization, userId } = req.user || {};
const { collectionNodeId } = req.params;
const { projectId, attributes } = req.body;
// const { collectionNodeId } = req.params;
const { projectId, attributes, collectionNodeId } = req.body;
if (
!organization ||
!projectId ||
@@ -341,12 +455,21 @@ export const AddAttributesController = async (
attributes,
};
const result = await addAttributes(data);
console.log("result: ", result);
switch (result.status) {
case "User not found":
res.status(404).json({ message: "User not found" });
break;
case "project not found":
res.status(200).json({
res.status(404).json({
message: "project not found",
});
break;
case "Subcollection already added for the object data":
res.status(200).json({
message: "Subcollection already added for the object data",
});
break;
case "Collection not found":
res.status(200).json({
message: "Collection not found",
@@ -377,8 +500,16 @@ export const updateAttributesCollections = async (
try {
const { organization, userId } = req.user || {};
const { collectionNodeId, attributeId } = req.params;
const { projectId, required, defaultValue, unique, index, key, type } =
req.body;
const {
projectId,
required,
primary,
defaultValue,
unique,
index,
key,
type,
} = req.body;
if (
!organization ||
!userId ||
@@ -394,6 +525,7 @@ export const updateAttributesCollections = async (
const data = {
organization,
projectId,
primary,
userId,
collectionNodeId,
attributeId,
@@ -405,9 +537,14 @@ export const updateAttributesCollections = async (
type,
};
const result = await UpdateAttributes(data);
console.log("result: ", result);
switch (result.status) {
case "User not found":
res.status(404).json({ message: "User not found" });
break;
case "project not found":
res.status(200).json({
res.status(404).json({
message: "project not found",
});
break;
@@ -461,8 +598,11 @@ export const delAttributesCollections = async (
};
const result = await DelAttributes(data);
switch (result.status) {
case "User not found":
res.status(404).json({ message: "User not found" });
break;
case "project not found":
res.status(200).json({
res.status(404).json({
message: "project not found",
});
break;
@@ -487,3 +627,120 @@ export const delAttributesCollections = async (
});
}
};
export const duplicateAttributesCollections = async (
req: AuthenticatedRequest,
res: Response
): Promise<void> => {
try {
const { organization, userId } = req.user || {};
const { projectId, attrKey, collectionNodeId } = req.body;
if (
!organization ||
!projectId ||
!collectionNodeId ||
!attrKey ||
!userId
) {
res.status(400).json({
message: "All fields are required",
});
return;
}
const data = {
organization,
userId,
projectId,
collectionNodeId,
attrKey,
};
const result = await DuplicateAttributes(data);
console.log("result: ", result);
switch (result.status) {
case "User not found":
res.status(404).json({ message: "User not found" });
break;
case "project not found":
res.status(404).json({
message: "project not found",
});
break;
case "CollectionId not found for duplication":
res.status(200).json({
message: "CollectionId not found for duplication",
});
break;
case "Attribute doesnot match":
res.status(200).json({
message: "Attribute doesnot match",
});
break;
case "Success":
res.status(200).json({
message: "Attributes duplicated successfully",
data: result.data,
});
break;
default:
res.status(500).json({
message: "Internal server error",
});
break;
}
} catch (error) {
res.status(500).json({
message: "Unknown error",
});
}
};
export const collectionListsController = async (
req: AuthenticatedRequest,
res: Response
): Promise<void> => {
try {
const { organization, userId } = req.user || {};
const { projectId } = req.params;
if (!organization || !projectId || !userId) {
res.status(400).json({
message: "All fields are required",
});
return;
}
const data = {
organization,
projectId,
userId,
};
const result = await GetcollectionLists(data);
switch (result.status) {
case "User not found":
res.status(404).json({ message: "User not found" });
break;
case "project not found":
res.status(404).json({
message: "project not found",
});
break;
case "Collection not found":
res.status(200).json({
message: "Collection not found",
Collections: result.data,
});
break;
case "Success":
res.status(200).json({ Collections: result.data });
break;
default:
res.status(500).json({
message: "Internal server error",
});
break;
}
} catch (error) {
res.status(500).json({
message: "Unknown error",
});
}
};

View File

@@ -0,0 +1,558 @@
import { Request, Response } from "express";
import { AuthenticatedRequest } from "../../shared/utils/token";
import {
addAttributesdummy,
collectionKeyRenamedummy,
GetcollectionNodedummy,
Nodecreationdummy,
SetCollectionNamedummy,
} from "../../shared/services/dummyService";
export const NodeCreationControllerdummy = async (
req: AuthenticatedRequest,
res: Response
): Promise<void> => {
try {
// const { organization, userId } = req.user || {};
const { projectId, position, organization, userId, collectionName } =
req.body;
console.log("req.body: ", req.body);
if (!organization || !projectId || !position || !userId) {
res.status(400).json({
message: "All fields are required",
});
return;
}
const data = {
organization,
projectId,
position,
userId,
collectionName,
};
const result = await Nodecreationdummy(data);
console.log("result: ", result);
switch (result.status) {
case "project not found":
res.status(200).json({
message: "project not found",
});
break;
case "Collection node creation unsuccessfull":
res.status(200).json({
message: "Collection node creation unsuccessfull",
});
break;
case "Success":
res.status(200).json({
message: "Node created successfully",
collectionNodeId: result.data,
});
break;
default:
res.status(500).json({
message: "Internal server error",
});
break;
}
} catch (error) {
res.status(500).json({
message: "Unknown error",
});
}
};
export const SetCollectionNameControllerdummy = async (
req: AuthenticatedRequest,
res: Response
): Promise<void> => {
try {
// const { organization, userId } = req.user || {};
const {
projectId,
collectionNodeId,
collectionName,
position,
organization,
userId,
} = req.body;
if (
!organization ||
!projectId ||
!userId ||
!collectionName ||
!collectionNodeId
) {
res.status(400).json({
message: "All fields are required",
});
return;
}
const data = {
organization,
projectId,
userId,
collectionNodeId,
collectionName,
position,
};
const result = await SetCollectionNamedummy(data);
console.log("result: ", result);
switch (result.status) {
case "project not found":
res.status(200).json({
message: "project not found",
});
break;
case "Collection not found":
res.status(200).json({
message: "Collection not found",
});
break;
case "Success":
res.status(200).json({
message: "collection name updated",
});
break;
default:
res.status(500).json({
message: "Internal server error",
});
break;
}
} catch (error) {
res.status(500).json({
message: "Unknown error",
});
}
};
export const CollectionDatasdummy = async (
req: AuthenticatedRequest,
res: Response
): Promise<void> => {
try {
const { organization, userId } = req.query as {
userId: string;
organization: string;
};
const { projectId, collectionNodeId } = req.params;
if (!organization || !projectId || !collectionNodeId || !userId) {
res.status(400).json({
message: "All fields are required",
});
return;
}
const data = {
organization,
projectId,
userId,
collectionNodeId,
};
const result = await GetcollectionNodedummy(data);
switch (result.status) {
case "project not found":
res.status(200).json({
message: "project not found",
});
break;
case "No collection Nodes present":
res.status(200).json({
message: "No collection Nodes present",
Collections: result.data,
});
break;
case "Success":
res.status(200).json(result.data);
break;
default:
res.status(500).json({
message: "Internal server error",
});
break;
}
} catch (error) {
res.status(500).json({
message: "Unknown error",
});
}
};
export const CollectionkeyRenamesdummy = async (
req: AuthenticatedRequest,
res: Response
): Promise<void> => {
try {
// const { organization, userId } = req.user || {};
const {
projectId,
collectionNodeId,
organization,
userId,
newKeyName,
oldKeyName,
} = req.body;
if (!organization || !projectId || !collectionNodeId || !userId) {
res.status(400).json({
message: "All fields are required",
});
return;
}
const data = {
organization,
projectId,
userId,
collectionNodeId,
newKeyName,
oldKeyName,
};
const result = await collectionKeyRenamedummy(data);
switch (result.status) {
case "project not found":
res.status(200).json({
message: "project not found",
});
break;
case "No collection Nodes present":
res.status(200).json({
message: "No collection Nodes present",
Collections: result.data,
});
break;
case "Success":
res.status(200).json(result.data);
break;
default:
res.status(500).json({
message: "Internal server error",
});
break;
}
} catch (error) {
res.status(500).json({
message: "Unknown error",
});
}
};
// export const DeleteCollectionsController = async (
// req: AuthenticatedRequest,
// res: Response
// ): Promise<void> => {
// try {
// const { organization, userId } = req.user || {};
// const { projectId, collectionNodeId } = req.params;
// if (!organization || !projectId || !collectionNodeId || !userId) {
// res.status(400).json({
// message: "All fields are required",
// });
// return;
// }
// const data = {
// organization,
// projectId,
// userId,
// collectionNodeId,
// };
// const result = await delCollection(data);
// switch (result.status) {
// case "project not found":
// res.status(200).json({
// message: "project not found",
// });
// break;
// case "Collection not found":
// res.status(200).json({
// message: "Collection not found",
// });
// break;
// case "Success":
// res.status(200).json({ message: "Collection deleted successfully" });
// break;
// default:
// res.status(500).json({
// message: "Internal server error",
// });
// break;
// }
// } catch (error) {
// res.status(500).json({
// message: "Unknown error",
// });
// }
// };
// export const DuplicateNodeCollectionController = async (
// req: AuthenticatedRequest,
// res: Response
// ): Promise<void> => {
// try {
// const { organization, userId } = req.user || {};
// const { collectionNodeId } = req.params;
// const { projectId, collectionName, position, attributes } = req.body;
// if (!organization || !projectId || !collectionNodeId || !userId) {
// res.status(400).json({
// message: "All fields are required",
// });
// return;
// }
// const data = {
// organization,
// projectId,
// userId,
// collectionName,
// position,
// attributes,
// collectionNodeId,
// };
// const result = await DuplicateCollection(data);
// switch (result.status) {
// case "project not found":
// res.status(200).json({
// message: "project not found",
// });
// break;
// case "Duplication unsuccessfull":
// res.status(200).json({
// message: "Duplication unsuccessfull",
// });
// break;
// case "Success":
// res.status(200).json({ message: "Duplicated successfully" });
// break;
// default:
// res.status(500).json({
// message: "Internal server error",
// });
// break;
// }
// } catch (error) {
// res.status(500).json({
// message: "Unknown error",
// });
// }
// };
// export const NodesCollectionsBasedOnproject = async (
// req: AuthenticatedRequest,
// res: Response
// ): Promise<void> => {
// try {
// const { organization, userId } = req.user || {};
// const { projectId } = req.params;
// if (!organization || !projectId || !userId) {
// res.status(400).json({
// message: "All fields are required",
// });
// return;
// }
// const data = {
// organization,
// projectId,
// userId,
// };
// const result = await GetNodesInProject(data);
// switch (result.status) {
// case "project not found":
// res.status(200).json({
// message: "project not found",
// });
// break;
// case "No collection Nodes present":
// res.status(200).json({
// message: "No collection Nodes present",
// Collections: result.data,
// });
// break;
// case "Success":
// res.status(200).json({ Collections: result.data });
// break;
// default:
// res.status(500).json({
// message: "Internal server error",
// });
// break;
// }
// } catch (error) {
// res.status(500).json({
// message: "Unknown error",
// });
// }
// };
export const AddAttributesControllerdummy = async (
req: AuthenticatedRequest,
res: Response
): Promise<void> => {
try {
// const { organization, userId } = req.user || {};
const { collectionNodeId } = req.params;
const { projectId, attributes, organization, userId } = req.body;
if (
!organization ||
!projectId ||
!attributes ||
!userId ||
!collectionNodeId
) {
res.status(400).json({
message: "All fields are required",
});
return;
}
const data = {
organization,
projectId,
userId,
collectionNodeId,
attributes,
};
const result = await addAttributesdummy(data);
console.log("result: ", result);
switch (result.status) {
case "project not found":
res.status(200).json({
message: "project not found",
});
break;
case "Collection not found":
res.status(200).json({
message: "Collection not found",
});
break;
case "Success":
res.status(200).json({
message: "collection Attributes Added",
});
break;
default:
res.status(500).json({
message: "Internal server error",
});
break;
}
} catch (error) {
res.status(500).json({
message: "Unknown error",
});
}
};
// export const updateAttributesCollections = async (
// req: AuthenticatedRequest,
// res: Response
// ): Promise<void> => {
// try {
// const { organization, userId } = req.user || {};
// const { collectionNodeId, attributeId } = req.params;
// const { projectId, required, defaultValue, unique, index, key, type } =
// req.body;
// if (
// !organization ||
// !userId ||
// !projectId ||
// !collectionNodeId ||
// !attributeId
// ) {
// res.status(400).json({
// message: "All fields are required",
// });
// return;
// }
// const data = {
// organization,
// projectId,
// userId,
// collectionNodeId,
// attributeId,
// required,
// defaultValue,
// unique,
// index,
// key,
// type,
// };
// const result = await UpdateAttributes(data);
// switch (result.status) {
// case "project not found":
// res.status(200).json({
// message: "project not found",
// });
// break;
// case "Collection not found":
// res.status(200).json({
// message: "Collection not found",
// });
// break;
// case "Success":
// res.status(200).json({ message: "Field updated successfully" });
// break;
// default:
// res.status(500).json({
// message: "Internal server error",
// });
// break;
// }
// } catch (error) {
// res.status(500).json({
// message: "Unknown error",
// });
// }
// };
// export const delAttributesCollections = async (
// req: AuthenticatedRequest,
// res: Response
// ): Promise<void> => {
// try {
// const { organization, userId } = req.user || {};
// const { collectionNodeId } = req.params;
// const { projectId, AttributeId } = req.body;
// if (
// !organization ||
// !projectId ||
// !collectionNodeId ||
// !AttributeId ||
// !userId
// ) {
// res.status(400).json({
// message: "All fields are required",
// });
// return;
// }
// const data = {
// organization,
// userId,
// projectId,
// collectionNodeId,
// AttributeId,
// };
// const result = await DelAttributes(data);
// switch (result.status) {
// case "project not found":
// res.status(200).json({
// message: "project not found",
// });
// break;
// case "Collection not found":
// res.status(200).json({
// message: "Collection not found",
// Collections: result.data,
// });
// break;
// case "Success":
// res.status(200).json({ message: "Field deleted successfully" });
// break;
// default:
// res.status(500).json({
// message: "Internal server error",
// });
// break;
// }
// } catch (error) {
// res.status(500).json({
// message: "Unknown error",
// });
// }
// };

View File

@@ -1,12 +1,18 @@
import { Request, Response } from "express";
import { Alledges, deleteEdge, edgecreation } from "../../shared/services/edgeService";
import {
Alledges,
deleteEdge,
edgecreation,
} from "../../shared/services/edgeService";
import { AuthenticatedRequest } from "../../shared/utils/token";
export const edgeCreationController = async (
req: Request,
req: AuthenticatedRequest,
res: Response
): Promise<void> => {
try {
const { organization, projectId, from,to,cardinality } = req.body;
if (!organization || !projectId || !from || !to) {
const { organization, userId } = req.user || {};
const { projectId, from, to, cardinality } = req.body;
if (!organization || !projectId || !from || !to || !userId) {
res.status(400).json({
message: "All fields are required",
});
@@ -15,36 +21,40 @@ export const edgeCreationController = async (
const data = {
organization,
projectId,
from,
to,
cardinality
from,
to,
cardinality,
userId,
};
const result = await edgecreation(data);
switch (result.status) {
case "User not found":
res.status(404).json({ message: "User not found" });
break;
case "project not found":
res.status(200).json({
res.status(404).json({
message: "project not found",
});
break;
case "From collection not found":
res.status(200).json({
message: "From collection not found",
case "From collection not found":
res.status(404).json({
message: "From collection not found",
});
break;
case "To collection not found":
res.status(200).json({
message: "To collection not found",
case "To collection not found":
res.status(404).json({
message: "To collection not found",
});
break;
case "Field already exists":
case "Field already exists":
res.status(200).json({
message: "Field already exists",
message: "Field already exists",
});
break;
case "Success":
res.status(200).json({
message:"Edge created successfully",
message: "Edge created successfully",
collectionNodeId: result.data,
});
break;
@@ -61,12 +71,13 @@ cardinality
}
};
export const allEdgesController = async (
req: Request,
req: AuthenticatedRequest,
res: Response
): Promise<void> => {
try {
const { organization, projectId, } = req.body;
if (!organization || !projectId ) {
const { organization, userId } = req.user || {};
const { projectId } = req.params;
if (!organization || !projectId || !userId) {
res.status(400).json({
message: "All fields are required",
});
@@ -75,23 +86,27 @@ export const allEdgesController = async (
const data = {
organization,
projectId,
userId,
};
const result = await Alledges(data);
switch (result.status) {
case "User not found":
res.status(404).json({ message: "User not found" });
break;
case "project not found":
res.status(200).json({
res.status(404).json({
message: "project not found",
});
break;
case "edge not found":
case "edge not found":
res.status(200).json({
message: "edge not found",
message: "edge not found",
});
break;
case "Success":
res.status(200).json({
message:"fetch all Edge datas successfully",
message: "fetch all Edge datas successfully",
collectionNodeId: result.data,
});
break;
@@ -108,12 +123,13 @@ export const allEdgesController = async (
}
};
export const deleteEdgesController = async (
req: Request,
req: AuthenticatedRequest,
res: Response
): Promise<void> => {
try {
const { organization, projectId, edgeId} = req.body;
if (!organization || !projectId ||!edgeId) {
const { organization, userId } = req.user || {};
const { projectId, edgeId } = req.params;
if (!organization || !projectId || !edgeId || !userId) {
res.status(400).json({
message: "All fields are required",
});
@@ -122,24 +138,28 @@ export const deleteEdgesController = async (
const data = {
organization,
projectId,
edgeId
edgeId,
userId,
};
const result = await deleteEdge(data);
switch (result.status) {
case "User not found":
res.status(404).json({ message: "User not found" });
break;
case "project not found":
res.status(200).json({
res.status(404).json({
message: "project not found",
});
break;
case "edge not found":
case "edge not found":
res.status(200).json({
message: "edge not found",
message: "edge not found",
});
break;
case "Success":
res.status(200).json({
message:"Edge deleted successfully",
message: "Edge deleted successfully",
collectionNodeId: result.data,
});
break;
@@ -154,4 +174,4 @@ export const deleteEdgesController = async (
message: "Unknown error",
});
}
};
};

View File

@@ -1,6 +1,9 @@
import { Request, Response } from "express";
import { AuthenticatedRequest } from "../../shared/utils/token";
import { recentlyViewedServices } from "../../shared/services/homePageService";
import {
homeuserProfileServices,
recentlyViewedServices,
} from "../../shared/services/homePageService";
export const homePageRecentlyViewedController = async (
req: AuthenticatedRequest,
@@ -22,7 +25,49 @@ export const homePageRecentlyViewedController = async (
switch (result.status) {
case "User not found":
res.status(403).json({
res.status(404).json({
message: "User not found",
});
break;
case "Success":
res.status(200).json({
datas: result.data,
});
break;
default:
res.status(500).json({
message: "Internal server error",
});
break;
}
} catch (error) {
res.status(500).json({
message: "Unknown error",
});
}
};
export const homePageUserDataController = async (
req: AuthenticatedRequest,
res: Response
): Promise<void> => {
try {
const { organization, userId } = req.user || {};
if (!organization || !userId) {
res.status(400).json({
message: "All fields are required",
});
return;
}
const data = {
organization,
userId,
};
const result = await homeuserProfileServices(data);
switch (result.status) {
case "User not found":
res.status(404).json({
message: "User not found",
});
break;

View File

@@ -4,31 +4,31 @@ import {
GetNodesInProject,
projectCreationService,
projectDatas,
projectModification,
ViewProjectService,
} from "../../shared/services/projectService";
import { AuthenticatedRequest } from "../../shared/utils/token";
export const projectCreationController = async (
req: Request,
req: AuthenticatedRequest,
res: Response
): Promise<void> => {
try {
const { organization, userId } = req.user || {};
const {
organization,
useableLanguage,
language,
projectName,
userId,
apiType,
apiProtocol,
application,
architecture,
description,
} = req.body;
if (
!organization ||
!useableLanguage ||
!language ||
!projectName ||
!userId ||
!apiType ||
!apiProtocol ||
!architecture ||
!application
) {
@@ -40,14 +40,15 @@ export const projectCreationController = async (
const data = {
organization,
projectName,
useableLanguage,
language,
description,
application,
userId,
apiType,
apiProtocol,
architecture,
};
const result = await projectCreationService(data);
console.log("result:projectcreate ", result);
switch (result.status) {
case "Project Already Exists":
@@ -95,24 +96,28 @@ export const getProjects = async (
): Promise<void> => {
try {
const { organization, userId } = req.user || {};
const { skip, limit } = req.params;
if (!organization || !userId) {
res.status(400).json({
message: "All fields are required",
});
return;
}
const result = await projectDatas({ organization, userId });
console.log("result: ", result);
const skipdata = parseInt(skip);
const limitdata = parseInt(limit);
const result = await projectDatas({
organization,
userId,
skipdata,
limitdata,
});
switch (result.status) {
case "No project found":
res.status(200).json({});
res.status(404).json({});
break;
case "Success":
res.status(200).json({
// message: "Projec",
projectDatas: result.data,
});
res.status(200).json({ data: result.data });
break;
default:
res.status(500).json({
@@ -128,12 +133,13 @@ export const getProjects = async (
};
export const NodesCollectionsBasedOnproject = async (
req: Request,
req: AuthenticatedRequest,
res: Response
): Promise<void> => {
try {
const { projectId, organization } = req.params;
if (!organization || !projectId) {
const { organization, userId } = req.user || {};
const { projectId } = req.params;
if (!organization || !projectId || !userId) {
res.status(400).json({
message: "All fields are required",
});
@@ -142,14 +148,20 @@ export const NodesCollectionsBasedOnproject = async (
const data = {
organization,
projectId,
userId,
};
const result = await GetNodesInProject(data);
switch (result.status) {
case "project not found":
res.status(200).json({
res.status(404).json({
message: "project not found",
});
break;
case "User not found":
res.status(404).json({
message: "User not found",
});
break;
case "No collection Nodes present":
res.status(200).json({
message: "No collection Nodes present",
@@ -237,10 +249,10 @@ export const deleteProjectController = async (
switch (result.status) {
case "User not found":
res.status(200).json({ message: "User not found" });
res.status(404).json({ message: "User not found" });
break;
case "Project not found":
res.status(200).json({ message: "Project not found" });
res.status(404).json({ message: "Project not found" });
break;
case "No access granted to delete this project":
res
@@ -267,3 +279,67 @@ export const deleteProjectController = async (
});
}
};
export const updateProjectController = async (
req: AuthenticatedRequest,
res: Response
): Promise<void> => {
try {
const { organization, userId } = req.user || {};
const {
projectId,
projectName,
application,
description,
language,
architecture,
} = req.body;
if (!organization || !userId || !projectId) {
res.status(400).json({
message: "All fields are required",
});
return;
}
const result = await projectModification({
projectId,
organization,
userId,
projectName,
application,
description,
language,
architecture,
});
switch (result.status) {
case "User not found":
res.status(404).json({ message: "User not found" });
break;
case "Project not found":
res.status(404).json({ message: "Project not found" });
break;
case "No access granted to delete this project":
res
.status(200)
.json({ message: "No access granted to update this project" });
break;
case "Project update unsuccessfull":
res.status(200).json({ message: "Project update unsuccessfull" });
break;
case "Success":
res.status(200).json({
message: "Project updated successfully",
});
break;
default:
res.status(500).json({
message: "Internal server error",
});
break;
}
} catch (error) {
res.status(500).json({
message: "Unknown error",
});
}
};

View File

@@ -2,13 +2,16 @@ import express from "express";
import {
AddAttributesController,
CollectionDatas,
collectionListsController,
delAttributesCollections,
DeleteCollectionsController,
duplicateAttributesCollections,
DuplicateNodeCollectionController,
NodeCreationController,
NodesCollectionsBasedOnproject,
SetCollectionNameController,
updateCollectionController,
updateAttributesCollections,
graphicDatas,
} from "../controller/collectionNodeController";
import { tokenValidator } from "../../shared/utils/token";
import authorizedRoles from "../../shared/middleware/rbacMiddleware";
@@ -16,7 +19,7 @@ import authorizedRoles from "../../shared/middleware/rbacMiddleware";
const collectionNodeRoutes = express.Router();
//Node creation
collectionNodeRoutes.post(
"/nodes",
"/node/save",
tokenValidator,
authorizedRoles("Admin", "Editor", "Viewer"),
NodeCreationController
@@ -26,7 +29,7 @@ collectionNodeRoutes.patch(
"/nodes/collectionName",
tokenValidator,
authorizedRoles("Admin", "Editor", "Viewer"),
SetCollectionNameController
updateCollectionController
);
//duplicate collection
collectionNodeRoutes.post(
@@ -35,6 +38,7 @@ collectionNodeRoutes.post(
authorizedRoles("Admin", "Editor", "Viewer"),
DuplicateNodeCollectionController
);
//particular collection data
collectionNodeRoutes.get(
"/nodes/:projectId/:collectionNodeId",
@@ -50,20 +54,22 @@ collectionNodeRoutes.patch(
DeleteCollectionsController
);
//Add fields
//Add fields to the collection node
collectionNodeRoutes.patch(
"/nodes/:collectionNodeId/attributes",
"/node/attributes",
tokenValidator,
authorizedRoles("Admin", "Editor", "Viewer"),
AddAttributesController
);
//Collections and fiels based on the project
collectionNodeRoutes.get(
"/nodes//:projectId",
"/nodes/:projectId",
tokenValidator,
authorizedRoles("Admin", "Editor", "Viewer"),
NodesCollectionsBasedOnproject
);
//update fields
collectionNodeRoutes.patch(
"/nodes/:collectionNodeId/attributes/:attributeId",
@@ -71,6 +77,7 @@ collectionNodeRoutes.patch(
authorizedRoles("Admin", "Editor", "Viewer"),
updateAttributesCollections
);
//delete fields
collectionNodeRoutes.patch(
"/nodes/:collectionNodeId/attributes/softDelete",
@@ -78,4 +85,28 @@ collectionNodeRoutes.patch(
authorizedRoles("Admin", "Editor", "Viewer"),
delAttributesCollections
);
collectionNodeRoutes.patch(
"/duplicate/attribute",
// tokenValidator,
// authorizedRoles("Admin", "Editor", "Viewer"),
duplicateAttributesCollections
);
//collectionName lists on the right panel
collectionNodeRoutes.get(
"/collections/:projectId",
tokenValidator,
authorizedRoles("Admin", "Editor", "Viewer"),
collectionListsController
);
//graphic Data
collectionNodeRoutes.get(
"/collections/:projectId/:collectionNodeId",
tokenValidator,
authorizedRoles("Admin", "Editor", "Viewer"),
graphicDatas
);
export default collectionNodeRoutes;

View File

@@ -0,0 +1,85 @@
import express from "express";
import { tokenValidator } from "../../shared/utils/token";
import authorizedRoles from "../../shared/middleware/rbacMiddleware";
import {
AddAttributesControllerdummy,
CollectionDatasdummy,
CollectionkeyRenamesdummy,
NodeCreationControllerdummy,
SetCollectionNameControllerdummy,
} from "../controller/dummyController";
const dummyRoutes = express.Router();
//Node creation
dummyRoutes.post(
"/nodesCreate",
// tokenValidator,
// authorizedRoles("Admin", "Editor", "Viewer"),
NodeCreationControllerdummy
);
//collection Added
dummyRoutes.patch(
"/nodes/collectionNamedummy",
// tokenValidator,
// authorizedRoles("Admin", "Editor", "Viewer"),
SetCollectionNameControllerdummy
);
// //duplicate collection
// dummyRoutes.post(
// "/nodes/:collectionNodeId/duplicate",
// tokenValidator,
// authorizedRoles("Admin", "Editor", "Viewer"),
// DuplicateNodeCollectionController
// );
// //particular collection data
dummyRoutes.get(
"/nodesdummyget/:projectId/:collectionNodeId",
// tokenValidator,
// authorizedRoles("Admin", "Editor", "Viewer"),
CollectionDatasdummy
);
//renameKeyvalue
dummyRoutes.patch(
"/nodesdummyKeyrename",
// tokenValidator,
// authorizedRoles("Admin", "Editor", "Viewer"),
CollectionkeyRenamesdummy
);
// //delete collection
// dummyRoutes.patch(
// "/nodes/:projectId/:collectionNodeId",
// tokenValidator,
// authorizedRoles("Admin", "Editor", "Viewer"),
// DeleteCollectionsController
// );
// //Add fields
dummyRoutes.patch(
"/nodesdummy/:collectionNodeId/dummyattributes",
// tokenValidator,
// authorizedRoles("Admin", "Editor", "Viewer"),
AddAttributesControllerdummy
);
// //Collections and fiels based on the project
// dummyRoutes.get(
// "/nodes//:projectId",
// tokenValidator,
// authorizedRoles("Admin", "Editor", "Viewer"),
// NodesCollectionsBasedOnproject
// );
// //update fields
// dummyRoutes.patch(
// "/nodes/:collectionNodeId/attributes/:attributeId",
// tokenValidator,
// authorizedRoles("Admin", "Editor", "Viewer"),
// updateAttributesCollections
// );
// //delete fields
// dummyRoutes.patch(
// "/nodes/:collectionNodeId/attributes/softDelete",
// tokenValidator,
// authorizedRoles("Admin", "Editor", "Viewer"),
// delAttributesCollections
// );
export default dummyRoutes;

View File

@@ -1,8 +1,29 @@
import express from "express";
import { allEdgesController, deleteEdgesController, edgeCreationController } from "../controller/edgeController";
import {
allEdgesController,
deleteEdgesController,
edgeCreationController,
} from "../controller/edgeController";
import { tokenValidator } from "../../shared/utils/token";
import authorizedRoles from "../../shared/middleware/rbacMiddleware";
const edgeRoutes = express.Router();
edgeRoutes.post("/edgeCreate", edgeCreationController);
edgeRoutes.patch("/edgeDelete", deleteEdgesController);
edgeRoutes.get("/allEdges", allEdgesController);
edgeRoutes.post(
"/edge/save",
tokenValidator,
authorizedRoles("Admin", "Editor", "Viewer"),
edgeCreationController
);
edgeRoutes.patch(
"/edge/:projectId/:edgeId",
tokenValidator,
authorizedRoles("Admin", "Editor", "Viewer"),
deleteEdgesController
);
edgeRoutes.get(
"/edges/:projectId",
tokenValidator,
authorizedRoles("Admin", "Editor", "Viewer"),
allEdgesController
);
export default edgeRoutes;

View File

@@ -1,8 +1,17 @@
import express from "express";
import { homePageRecentlyViewedController } from "../controller/homePageController";
import {
homePageRecentlyViewedController,
homePageUserDataController,
} from "../controller/homePageController";
import { tokenValidator } from "../../shared/utils/token";
import authorizedRoles from "../../shared/middleware/rbacMiddleware";
const homeRoutes = express.Router();
homeRoutes.get("/home",tokenValidator,authorizedRoles("Admin","Editor","Viewer"), homePageRecentlyViewedController);
homeRoutes.get(
"/home/recentlyviewed",
tokenValidator,
authorizedRoles("Admin", "Editor", "Viewer"),
homePageRecentlyViewedController
);
homeRoutes.get("/home", tokenValidator, homePageUserDataController);
export default homeRoutes;

View File

@@ -2,46 +2,61 @@ import express, { Response, NextFunction } from "express";
import { AuthenticatedRequest } from "../../shared/utils/token";
import {
accessAproject,
deleteProjectController,
getProjects,
NodesCollectionsBasedOnproject,
projectCreationController,
updateProjectController,
} from "../controller/projectController";
import authorizedRoles from "../../shared/middleware/rbacMiddleware";
import { tokenValidator } from "../../shared/utils/token";
const projectRoutes = express.Router();
//project save
projectRoutes.post(
"/Newproject",
"/project/save",
tokenValidator,
authorizedRoles("Admin", "Editor"),
projectCreationController
);
//all nodes based on the project
projectRoutes.get(
"/nodes/:organization/:projectId",
"/project/:organization/:projectId",
tokenValidator,
authorizedRoles("Viewer", "Admin", "Editor"),
NodesCollectionsBasedOnproject
);
//listing of all projects
projectRoutes.get(
"/Allprojects/:organization",
"/projects/:skip/:limit",
tokenValidator,
authorizedRoles("Admin", "Editor", "Viewer"),
getProjects
);
//view a project
projectRoutes.get(
"/Aproject/:projectId",
"/project/:projectId",
tokenValidator,
authorizedRoles("Admin", "Editor", "Viewer"),
accessAproject
);
projectRoutes.put(
"/node/deleteproject/:projectId",
//delete Project
projectRoutes.patch(
"/project/deleteproject/:projectId",
tokenValidator,
authorizedRoles("Admin", "Editor"),
accessAproject
deleteProjectController
);
projectRoutes.patch(
"/project/updateproject",
tokenValidator,
authorizedRoles("Admin", "Editor", "Viewer"),
updateProjectController
);
export default projectRoutes;

View File

@@ -6,6 +6,54 @@ interface ConnectionCache {
const connections: ConnectionCache = {};
dotenv.config();
// const MainModel = async<T>(
// db: string,
// modelName: string,
// schema: Schema<T>,
// collectionName: string
// ): Model<T> => {
// const db1_url = `${process.env.MONGO_URI}${db}`;
// const authOptions = {
// user: process.env.MONGO_USER,
// pass: process.env.MONGO_PASSWORD,
// authSource: process.env.MONGO_AUTH_DB || "admin",
// maxPoolSize: 50,
// };
// if (connections[db]) {
// return connections[db].model<T>(modelName, schema, collectionName);
// }
// // if (connections[db]) {
// // if (connections[db].readyState === 1) {
// // return connections[db].model<T>(modelName, schema, collectionName);
// // }
// // console.warn(`Reconnecting to MongoDB database: ${db}`);
// // }
// try {
// const db1 = mongoose.createConnection(db1_url, authOptions);
// // await db1.asPromise();
// connections[db] = db1;
// // connections[db] = db1;
// db1.on("connected", () => {
// console.log(`Connected to MongoDB database: ${db}`);
// });
// db1.on("error", (err) => {
// console.error(
// `MongoDB connection error for database ${db}:`,
// err.message
// );
// });
// return db1.model<T>(modelName, schema, collectionName);
// } catch (error) {
// console.error("Database connection error:", (error as Error).message);
// throw error;
// }
// };
const MainModel = <T>(
db: string,
modelName: string,
@@ -34,10 +82,7 @@ const MainModel = <T>(
});
db1.on("error", (err) => {
console.error(
`MongoDB connection error for database ${db}:`,
err.message
);
console.error(`MongoDB connection error for database ${db}`, err.message);
});
return db1.model<T>(modelName, schema, collectionName);
@@ -46,5 +91,4 @@ const MainModel = <T>(
throw error;
}
};
export default MainModel;

View File

@@ -7,14 +7,19 @@ type IattributeTypes =
| "Array"
| "Date"
| "Enum"
| "undefined"
| "object"
| "Undefined"
| "Object"
| "ObjectId"
| "number"
| "boolean";
| "Number"
| "Boolean"
| "Null"
| "Map"
| "Buffer"
| "Mixed";
interface IAttributes {
isArchive: boolean;
primary?: boolean;
key: string;
type: IattributeTypes;
refKey?: object;
@@ -23,12 +28,29 @@ interface IAttributes {
unique?: boolean;
index?: boolean;
}
interface ICollectionNode extends Document {
export interface ICollectionNode extends Document {
type: string;
projectId: IProject["_id"];
collectionNodeName: string;
parentCollectionNodeId: ICollectionNode["_id"];
isSubCollection: boolean;
attributeparentId: ICollectionNode["_id"];
collectionName: string;
attributes: IAttributes[];
backgroundColor: BackgroundColor;
borderColor: BackgroundColor;
lineColor: BackgroundColor;
fontColor: BackgroundColor;
isArchive: boolean;
position: [number, number, number];
lineThickness: number;
fontName: string;
lineType: string;
borderThickness: number;
cornerRadius: number;
fontSize: number;
position: {
x: number;
y: number;
};
}
const attributeSchema = new Schema<IAttributes>({
key: { type: String, required: true },
@@ -37,29 +59,76 @@ const attributeSchema = new Schema<IAttributes>({
required: true,
enum: [
"string",
"number",
"boolean",
"Number",
"Boolean",
"Date",
"ObjectId",
"Array",
"Enum",
"object",
"Object",
"any",
"Undefined",
"Mixed",
"Buffer",
"Map",
"Null",
],
},
required: { type: Boolean },
refKey: { type: Object },
default: { type: Schema.Types.Mixed },
unique: { type: Boolean },
primary: { type: Boolean },
index: { type: Boolean },
isArchive: { type: Boolean, default: false },
});
interface ColorHex {
type: "HEX";
value: string;
}
interface ColorRGB {
type: "RGB";
value: { r: number; g: number; b: number };
}
interface ColorHSL {
type: "HSL";
value: { h: number; s: number; l: number };
}
type BackgroundColor = ColorHex | ColorRGB | ColorHSL;
const backgroundColorSchema = new Schema({
type: {
type: String,
enum: ["HEX", "RGB", "HSL"],
required: true,
},
value: {
type: Schema.Types.Mixed,
required: true,
},
});
const collectionSchema: Schema<ICollectionNode> = new Schema(
{
projectId: { type: Schema.Types.ObjectId, ref: "Project" },
collectionNodeName: { type: String },
position: { type: [Number], required: true },
parentCollectionNodeId: { type: Schema.Types.ObjectId, ref: "Collection" },
attributeparentId: { type: Schema.Types.ObjectId, ref: "Collection" },
collectionName: { type: String },
type: { type: String, enum: ["collectionNode", "objectNode"] },
backgroundColor: { type: backgroundColorSchema },
borderColor: { type: backgroundColorSchema },
fontColor: { type: backgroundColorSchema },
lineColor: { type: backgroundColorSchema },
position: {
x: { type: Number },
y: { type: Number },
},
lineThickness: { type: Number },
fontName: { type: String },
lineType: { type: String },
borderThickness: { type: Number },
cornerRadius: { type: Number },
fontSize: { type: Number },
isArchive: { type: Boolean, default: false },
isSubCollection: { type: Boolean, default: false },
attributes: [attributeSchema],
},
{
@@ -70,4 +139,4 @@ const collectionSchema: Schema<ICollectionNode> = new Schema(
const collectionsModel = (db: any) => {
return MainModel(db, "collectionNode", collectionSchema, "collectionNode");
};
export default collectionsModel;
export default collectionsModel;

View File

@@ -0,0 +1,110 @@
import { Schema, Document } from "mongoose";
import MainModel from "../connection/connection";
import { IProject } from "./projectmodel";
export const attributeTypes = [
"string",
"any",
"Array",
"Date",
"Enum",
"undefined",
"object",
"ObjectId",
"number",
"boolean",
] as const;
export type IattributeTypes = (typeof attributeTypes)[number];
interface IField {
type: IattributeTypes;
isArchive: boolean;
}
interface IcollectionData {
isArchive: boolean;
fields: Map<string, IField>;
}
interface ColorHex {
type: "HEX";
value: string;
}
interface ColorRGB {
type: "RGB";
value: { r: number; g: number; b: number };
}
interface ColorHSL {
type: "HSL";
value: { h: number; s: number; l: number };
}
type BackgroundColor = ColorHex | ColorRGB | ColorHSL;
const backgroundColorSchema = new Schema({
type: {
type: String,
enum: ["HEX", "RGB", "HSL"],
required: true,
},
value: {
type: Schema.Types.Mixed,
required: true,
},
});
export interface ICollectionNode extends Document {
projectId: IProject["_id"];
parentCollectionNodeId: ICollectionNode["_id"];
isSubCollection: boolean;
attributeparentId: ICollectionNode["_id"];
collectionName: string;
collections: IcollectionData[];
position: [number, number, number];
backgroundColor: BackgroundColor;
borderColor: BackgroundColor;
lineColor: BackgroundColor;
fontColor: BackgroundColor;
isArchive: boolean;
}
const fieldSchema = new Schema<IField>({
type: { type: String, enum: attributeTypes, required: true },
isArchive: { type: Boolean, default: false },
});
const collectionSchema = new Schema<IcollectionData>({
fields: {
type: Map,
of: fieldSchema,
default: () => new Map<string, IField>(),
},
});
const nodeSchema: Schema<ICollectionNode> = new Schema(
{
projectId: { type: Schema.Types.ObjectId, ref: "Project" },
collectionName: { type: String },
parentCollectionNodeId: { type: Schema.Types.ObjectId, ref: "Collection" },
attributeparentId: { type: Schema.Types.ObjectId, ref: "Collection" },
position: { type: [Number], required: true },
isArchive: { type: Boolean, default: false },
collections: [collectionSchema],
isSubCollection: { type: Boolean, default: false },
backgroundColor: { type: backgroundColorSchema },
borderColor: { type: backgroundColorSchema },
fontColor: { type: backgroundColorSchema },
lineColor: { type: backgroundColorSchema },
},
{
timestamps: true,
}
);
const dummyModel = (db: any) => {
return MainModel(
db,
"collectionNodeDummy",
nodeSchema,
"collectionNodeDummy"
);
};
export default dummyModel;

View File

@@ -1,29 +1,32 @@
import { Schema, Document } from "mongoose";
import MainModel from "../connection/connection";
import { IProject } from "./projectmodel";
interface IEdgeModel extends Document {
projectId: IProject["_id"];
from: { collection_id: string; field: string };
to: { collection_id: string };
cardinality: "one-to-one" | "one-to-many"|"many-to-many"
isArchive: boolean;
createdAt: number;
export interface IEdgeModel extends Document {
projectId: IProject["_id"];
from: { collection_id: string; field: string };
to: { collection_id: string };
cardinality: "one-to-one" | "one-to-many" | "many-to-many";
isArchive: boolean;
createdAt: number;
}
const EdgeSchema = new Schema<IEdgeModel>({
projectId: { type: Schema.Types.ObjectId, ref: "Project", required: true },
from: {
collection_id: { type: String, required: true },
field: { type: String, required: true },
},
to: {
collection_id: { type: String, required: true },
},
cardinality: { type: String, enum: ["one-to-one", "one-to-many", "many-to-many"], required: true },
isArchive: { type: Boolean, default: false },
createdAt: { type: Number, default: Date.now },
projectId: { type: Schema.Types.ObjectId, ref: "Project", required: true },
from: {
collection_id: { type: String, required: true },
field: { type: String, required: true },
},
to: {
collection_id: { type: String, required: true },
},
cardinality: {
type: String,
enum: ["one-to-one", "one-to-many", "many-to-many"],
required: true,
},
isArchive: { type: Boolean, default: false },
createdAt: { type: Number, default: Date.now },
});
const edgeModel = (db: any) => {
return MainModel(db, "edge", EdgeSchema, "edge");
return MainModel(db, "edge", EdgeSchema, "edge");
};
export default edgeModel;

View File

@@ -1,34 +1,40 @@
import { Schema, Document } from "mongoose";
import MainModel from "../connection/connection";
import { IUser } from "./userModel";
export interface IProject extends Document {
projectName: string;
appType: string;
thumbnail: string;
application: string;
slug: string;
isArchive: boolean;
createdBy: string;
createdBy: IUser["_id"];
description: string;
members: [string];
useableLanguage: string;
language: string;
typeOfDB: string;
DBName: string;
architecture: string;
apiType: string;
apiProtocol: string;
}
const projectSchema: Schema = new Schema(
{
projectName: { type: String },
appType:{type:String,enum:["Backend","Frontend"]},
thumbnail: { type: String },
application: {
type: String,
enum: ["Web App", "Mobile App", "Desktop App", "IoT", "Microservices"],
},
slug: { type: String },
isArchive: { type: Boolean, default: false },
createdBy: { type: String },
createdBy: { type: Schema.Types.ObjectId, ref: "User" },
description: { type: String },
DBName: { type: String },
typeOfDB: { type: String },
useableLanguage: { type: String },
architecture: { type: String },
apiType: {
language: { type: String },
architecture: { type: String, enum: ["MVVM", "MVP", "MVC", "CQRS"] },
apiProtocol: {
type: String,
enum: ["RESTful", "SOAP", "GraphQL", "RPC", "WebSocket"],
enum: ["REST", "SOAP", "GraphQL", "gRPC", "WebSockets"],
},
members: { type: [String] },
},

View File

@@ -1,10 +1,10 @@
import mongoose, { Document, Schema } from "mongoose";
import MainModel from "../connection/connection";
import { IProject } from "./projectmodel";
import { User } from "./userModel";
import { IUser } from "./userModel";
export interface ISharedUser {
userId: User["_id"];
userId: IUser["_id"];
accessLevel: "Viewer" | "Editor" | "Admin";
}

View File

@@ -1,8 +1,8 @@
import { Schema, Document } from "mongoose";
import MainModel from "../connection/connection";
import { User } from "./userModel";
import { IUser } from "./userModel";
export interface IUserToken extends Document {
userId: User["_id"];
userId: IUser["_id"];
isArchive: boolean;
refreshToken: string;
resetTokenExpiry?: Date;

View File

@@ -1,8 +1,8 @@
import { Schema, Document } from "mongoose";
import MainModel from "../connection/connection";
import { User } from "./userModel";
import { IUser } from "./userModel";
export interface IUserData extends Document {
userId: User["_id"];
userId: IUser["_id"];
isArchive: boolean;
profilePicture: string;
recentlyViewed: string[];

View File

@@ -1,6 +1,6 @@
import { Schema, Document } from "mongoose";
import MainModel from "../connection/connection";
export interface User extends Document {
export interface IUser extends Document {
userName: string;
email: string;
password: string;

View File

@@ -0,0 +1,35 @@
import { Schema, Document } from "mongoose";
import MainModel from "../connection/connection";
import { IProject } from "./projectmodel";
import { IUser } from "./userModel";
export interface Version extends Document {
versionName: string;
previous_Version: string;
projectId: IProject["_id"];
createdBy: IUser["_id"];
isArchive: boolean;
version: number;
rollBackComment: string;
description: string;
parentVersionID: Version["_id"];
}
const versionSchema: Schema = new Schema(
{
versionName: { type: String, default: "" },
rollBackComment: { type: String },
description: { type: String, default: "" },
version: { type: Number },
parentVersionID: { type: Schema.Types.ObjectId, ref: "version" },
previous_Version: { type: String },
isArchive: { type: Boolean, default: false },
projectId: { type: Schema.Types.ObjectId, ref: "Project" },
createdBy: { type: Schema.Types.ObjectId, ref: "User" },
},
{ timestamps: true }
);
const versionModel = (db: string) => {
return MainModel(db, "Versions", versionSchema, "Versions");
};
export default versionModel;

View File

@@ -13,13 +13,18 @@ interface Iresponse {
interface Isignup {
userName: string;
email: string;
password: string;
confirmPassword: string;
password: string
}
interface Isignin {
email: string;
password: string;
}
interface signout {
email: string;
password: string;
}
interface IforGotPassword {
email: string;
}
@@ -32,15 +37,15 @@ export async function existingUserData(email: string, organization: string) {
return existingData;
}
export const signupService = async (data: Isignup): Promise<Iresponse> => {
const { userName, email, password, confirmPassword } = data;
const { userName, email, password } = data;
try {
const mailCaseChange = email.toLocaleLowerCase();
const organization = email.split("@")[1].split(".")[0];
const mailExistance = await existingUserData(mailCaseChange, organization);
if (mailExistance !== null) return { status: "User Already exists" };
if (password !== confirmPassword) {
return { status: "Passwords do not match" };
}
// if (password !== confirmPassword) {
// return { status: "Passwords do not match" };
// }
let role;
const passwordHashed = await hashGenerate(password);
const userCount = await userModel(organization).countDocuments({});
@@ -72,8 +77,7 @@ export const signinService = async (data: Isignin): Promise<Iresponse> => {
const mailCaseChange = email.toLocaleLowerCase();
const organization = email.split("@")[1].split(".")[0];
const mailExistance = await existingUserData(mailCaseChange, organization);
if (mailExistance == null)
return { status: "User not found!!! Kindly Signup" };
if (!mailExistance) return { status: "User not found!!! Kindly Signup" };
const comparePassword = await hashValidator(
password,
mailExistance.password
@@ -230,3 +234,39 @@ export const forgetPassword = async ({
}
}
};
export const signOutService = async (data: signout): Promise<Iresponse> => {
const { email } = data;
try {
const mailCaseChange = email.toLocaleLowerCase();
const organization = email.split("@")[1].split(".")[0];
const mailExistance = await existingUserData(mailCaseChange, organization);
if (!mailExistance) return { status: "User not found!!! Kindly Signup" };
const tokenData = await tokenModel(organization).findOne({
userId: mailExistance._id,
isArchive: false,
});
if (!tokenData) return { status: "Token not found" };
await Promise.all([
redis.del(`token:${mailCaseChange}`),
redis.del(`user:${mailCaseChange}`),
]);
tokenData.refreshToken = "";
await tokenData.save();
mailExistance.visitorBrowserID = "";
await mailExistance.save();
return { status: "Success" };
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};

View File

@@ -1,6 +1,8 @@
import mongoose from "mongoose";
import ProjectType from "../../shared/model/projectmodel";
import collectionsModel from "../model/collectionModel";
import edgeModel from "../model/edgeModel";
import userModel from "../model/userModel";
interface Iresponse {
status: string;
data?: any;
@@ -8,6 +10,8 @@ interface Iresponse {
interface IcollectionNode {
projectId: string;
userId: string;
collectionName: string;
type: string;
organization: string;
position: [number];
}
@@ -21,6 +25,15 @@ interface IcollectionNodeName {
organization: string;
collectionNodeId: string;
collectionName: string;
backgroundColor: string;
borderColor: string;
lineColor: string;
fontColor: string;
lineThickness: number;
fontName: string;
lineType: string;
borderThickness: number;
cornerRadius: number;
position: [number];
}
interface IcollectionAttributes {
@@ -41,6 +54,11 @@ interface IcollectionNodeById {
userId: string;
collectionNodeId: string;
}
interface IcollectionLists {
projectId: string;
organization: string;
userId: string;
}
interface IAttributesEdit {
projectId: string;
userId: string;
@@ -49,6 +67,7 @@ interface IAttributesEdit {
attributeId: string;
key?: string;
type?: string;
primary:boolean
required?: boolean;
defaultValue?: any;
unique?: boolean;
@@ -76,12 +95,25 @@ interface IDuplicateCollectionNode {
position: [number];
attributes: [];
}
interface IDuplicateattributes {
projectId: string;
userId: string;
collectionNodeId: string;
organization: string;
attrKey: string;
}
export const Nodecreation = async (
data: IcollectionNode
): Promise<Iresponse> => {
const { organization, projectId, position, userId } = data;
const { organization, projectId, position, userId, collectionName, type } =
data;
try {
const ExistingUser = await userModel(organization).findOne({
_id: userId,
isArchive: false,
});
if (!ExistingUser) return { status: "User not found" };
const existingProject = await ProjectType(organization).findOne({
_id: projectId,
isArchive: false,
@@ -89,29 +121,52 @@ export const Nodecreation = async (
if (!existingProject) {
return { status: "project not found" };
} else {
const existingCollection = await collectionsModel(organization).findOne({
projectId: projectId,
isArchive: false,
collectionName: collectionName,
});
if (existingCollection)
return { status: "CollectionName already exists" };
let attributes = [{ key: "auto_id", type: "string" }];
const newAttributes = attributes;
const updatedAttributesMap = new Map<string, any>();
// for (const attr of existingAttributes) {
// updatedAttributesMap.set(attr.key, attr);
// }
for (const attr of newAttributes) {
if (!updatedAttributesMap.has(attr.key)) {
updatedAttributesMap.set(attr.key, attr);
}
}
const updatedAttributes = Array.from(updatedAttributesMap.values());
const newCollectionnode = await collectionsModel(organization).create({
projectId: projectId,
isArchive: false,
position: position,
type,
collectionName: collectionName,
attributes: updatedAttributes,
});
if (!newCollectionnode)
return { status: "Collection node creation unsuccessfull" };
else return { status: "Success", data: newCollectionnode._id };
}
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
if (error instanceof mongoose.Error.ValidationError) {
return { status: "Validation Error", data: error.message };
} else if (error instanceof Error) {
return { status: error.message };
} else {
return {
status: "An unexpected error occurred",
};
return { status: "An unexpected error occurred" };
}
}
};
export const SetCollectionName = async (
export const updatecollection = async (
data: IcollectionNodeName
): Promise<Iresponse> => {
const {
@@ -119,10 +174,25 @@ export const SetCollectionName = async (
projectId,
position,
collectionNodeId,
backgroundColor,
borderColor,
fontColor,
lineColor,
lineThickness,
fontName,
lineType,
borderThickness,
cornerRadius,
collectionName,
userId,
} = data;
try {
const ExistingUser = await userModel(organization).findOne({
_id: userId,
isArchive: false,
});
if (!ExistingUser) return { status: "User not found" };
const existingProject = await ProjectType(organization).findOne({
_id: projectId,
isArchive: false,
@@ -146,7 +216,19 @@ export const SetCollectionName = async (
isArchive: false,
_id: collectionNodeId,
},
{ collectionNodeName: collectionName },
{
collectionName: collectionName,
backgroundColor,
borderColor,
fontColor,
lineColor,
position,
lineThickness,
fontName,
lineType,
borderThickness,
cornerRadius,
},
{ new: true }
);
return { status: "Success" };
@@ -170,6 +252,12 @@ export const addAttributes = async (
const { organization, projectId, userId, collectionNodeId, attributes } =
data;
try {
const ExistingUser = await userModel(organization).findOne({
_id: userId,
isArchive: false,
});
if (!ExistingUser) return { status: "User not found" };
const existingProject = await ProjectType(organization).findOne({
_id: projectId,
isArchive: false,
@@ -211,6 +299,41 @@ export const addAttributes = async (
{ attributes: updatedAttributes },
{ new: true }
);
if (AttributesAdded) {
for (const attr of AttributesAdded.attributes) {
if (attr.type === "Object") {
const existingsubcollection = await collectionsModel(
organization
).findOne({
projectId: projectId,
parentCollectionNodeId: collectionNodeId,
attributeparentId: (attr as any)._id,
isArchive: false,
});
if (!existingsubcollection) {
const newCollection = await collectionsModel(organization).create(
{
type: "objectNode",
isArchive: false,
projectId: projectId,
collectionName: attr.key,
parentCollectionNodeId: collectionNodeId,
attributeparentId: (attr as any)._id,
attributes: [],
// position: [0, 0, 0],
}
);
AttributesAdded.isSubCollection = true;
await AttributesAdded.save();
} else {
return {
status: "Subcollection already added for the object data",
};
}
}
}
await AttributesAdded.save();
}
return { status: "Success" };
}
} catch (error: unknown) {
@@ -226,11 +349,18 @@ export const addAttributes = async (
}
};
//both collections and edges in projects
export const GetNodesInProject = async (
data: IcollectionNodes
): Promise<Iresponse> => {
const { organization, userId, projectId } = data;
try {
const ExistingUser = await userModel(organization).findOne({
_id: userId,
isArchive: false,
});
if (!ExistingUser) return { status: "User not found" };
const existingProject = await ProjectType(organization).findOne({
_id: projectId,
isArchive: false,
@@ -238,23 +368,83 @@ export const GetNodesInProject = async (
if (!existingProject) {
return { status: "project not found" };
} else {
const collectionNodes = await collectionsModel(organization)
let collectionNodes = await collectionsModel(organization)
.find({ projectId: projectId, isArchive: false })
.select("collectionNodeName attributes position -_id ");
.select(
"collectionName attributes position _id type parentCollectionNodeId attributeparentId"
);
if (!collectionNodes)
return { status: "No collection Nodes present", data: [] };
else {
const formattedCollections = collectionNodes.map((collection) => ({
position: collection.position,
collectionNodeName: collection.collectionNodeName,
attributes: collection.attributes
.filter((attr: any) => !attr.isArchive)
.map((attr: any) => {
const { isArchive, ...rest } = attr.toObject();
return { ...rest };
}),
}));
return { status: "Success", data: formattedCollections };
const edgeDatas = await edgeModel(organization).find({
isArchive: false,
});
const filteredEdges = await Promise.all(
edgeDatas.map(async (e: any) => {
const targetCollection = await collectionsModel(organization)
.findOne({ _id: e.to.collection_id, isArchive: false })
.lean();
let targetFieldKey = null;
if (targetCollection && targetCollection.attributes?.length > 0) {
const refAttribute = targetCollection.attributes.find(
(attr: any) =>
attr.refKey &&
attr.refKey.collection_id?.toString() ===
e.from.collection_id.toString()
);
if (refAttribute) {
targetFieldKey = refAttribute.key;
}
}
return {
edgeId: e._id,
source: e.from.collection_id,
sourceHandle: e.from.field,
target: e.to.collection_id,
targetHandle: targetFieldKey || e.to.collection_id,
};
})
);
const formattedCollections = collectionNodes.map((collection: any) => {
const baseData = {
collectionId: collection._id,
position: collection.position,
type: collection.type,
data: {
collectionName: collection.collectionName,
collectionData: collection.attributes
.filter((attr: any) => !attr.isArchive)
.map((attr: any) => {
if (attr.length === 0) {
return {};
}
const { isArchive, refKey, ...rest } = attr.toObject
? attr.toObject()
: attr;
return { ...rest };
}),
},
};
if (collection.type === "objectNode") {
return {
...baseData,
parentId: collection.parentCollectionNodeId,
parentFieldId: collection.attributeparentId,
};
}
return baseData;
});
const finalResult = {
nodes: formattedCollections,
edges: filteredEdges,
};
return { status: "Success", data: finalResult };
}
}
} catch (error: unknown) {
@@ -270,6 +460,105 @@ export const GetNodesInProject = async (
}
};
// export const GetNodesInProject = async (
// data: IcollectionNodes
// ): Promise<Iresponse> => {
// const { organization, userId, projectId } = data;
// try {
// const existingProject = await ProjectType(organization).findOne({
// _id: projectId,
// isArchive: false,
// });
// if (!existingProject) {
// return { status: "project not found" };
// } else {
// const collectionNodes = await collectionsModel(organization)
// .find({ projectId: projectId, isArchive: false })
// .select("collectionName attributes position -_id isSubCollection");
// if (!collectionNodes)
// return { status: "No collection Nodes present", data: [] };
// else {
// const fetchNestedAttributes = async (
// parentCollectionNodeId: string,
// attributeId: string
// ): Promise<any> => {
// const subCollection = await collectionsModel(organization)
// .findOne({
// parentCollectionNodeId,
// attributeparentId: attributeId,
// isArchive: false,
// })
// .select("collectionName attributes");
// if (!subCollection) {
// return {}; // If no sub-collection exists, return empty object
// }
// const nestedAttributes: Record<string, any> = {};
// for (const attr of subCollection.attributes) {
// if (attr.type === "object") {
// nestedAttributes[attr.key] = {
// type: "object",
// attributes: await fetchNestedAttributes(
// subCollection._id as string,
// (attr as any)._id
// ),
// };
// } else {
// nestedAttributes[attr.key] = attr.type;
// }
// }
// return nestedAttributes;
// };
// // Format the main collections
// const formattedCollections = await Promise.all(
// collectionNodes.map(async (collection) => {
// const formattedAttributes: Record<string, any> = {};
// for (const attr of collection.attributes) {
// if (attr.type === "object") {
// formattedAttributes[attr.key] = {
// type: "object",
// attributes: await fetchNestedAttributes(
// collection._id as string,
// (attr as any)._id
// ),
// };
// } else {
// formattedAttributes[attr.key] = attr.type;
// }
// }
// return {
// position: collection.position,
// collectionName: collection.collectionName,
// attributes: formattedAttributes,
// };
// })
// );
// return {
// status: "Success",
// data: formattedCollections,
// };
// }
// }
// // }
// } catch (error: unknown) {
// if (error instanceof Error) {
// return {
// status: error.message,
// };
// } else {
// return {
// status: "An unexpected error occurred",
// };
// }
// }
// };
export const UpdateAttributes = async (
data: IAttributesEdit
): Promise<Iresponse> => {
@@ -287,6 +576,12 @@ export const UpdateAttributes = async (
type,
} = data;
try {
const ExistingUser = await userModel(organization).findOne({
_id: userId,
isArchive: false,
});
if (!ExistingUser) return { status: "User not found" };
const existingProject = await ProjectType(organization).findOne({
_id: projectId,
isArchive: false,
@@ -344,6 +639,12 @@ export const DelAttributes = async (
const { organization, userId, projectId, collectionNodeId, AttributeId } =
data;
try {
const ExistingUser = await userModel(organization).findOne({
_id: userId,
isArchive: false,
});
if (!ExistingUser) return { status: "User not found" };
const existingProject = await ProjectType(organization).findOne({
_id: projectId,
isArchive: false,
@@ -398,6 +699,12 @@ export const delCollection = async (
): Promise<Iresponse> => {
const { organization, userId, projectId, collectionNodeId } = data;
try {
const ExistingUser = await userModel(organization).findOne({
_id: userId,
isArchive: false,
});
if (!ExistingUser) return { status: "User not found" };
const existingProject = await ProjectType(organization).findOne({
_id: projectId,
isArchive: false,
@@ -444,6 +751,12 @@ export const GetcollectionNode = async (
): Promise<Iresponse> => {
const { organization, userId, projectId, collectionNodeId } = data;
try {
const ExistingUser = await userModel(organization).findOne({
_id: userId,
isArchive: false,
});
if (!ExistingUser) return { status: "User not found" };
const existingProject = await ProjectType(organization).findOne({
_id: projectId,
isArchive: false,
@@ -461,13 +774,64 @@ export const GetcollectionNode = async (
}
const formattedCollection = {
position: existingCollection.position,
collectionNodeName: existingCollection.collectionNodeName,
attributes: existingCollection.attributes
.filter((attr: any) => !attr.isArchive)
.map((attr: any) => {
const { isArchive, ...rest } = attr.toObject();
return rest;
}),
data: {
collectionName: existingCollection.collectionName,
attributes: existingCollection.attributes
.filter((attr: any) => !attr.isArchive)
.map((attr: any) => {
const { isArchive, ...rest } = attr.toObject();
return rest;
}),
},
};
return { status: "Success", data: formattedCollection };
}
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};
export const GetcollectionGraphicData = async (
data: IcollectionNodeById
): Promise<Iresponse> => {
const { organization, userId, projectId, collectionNodeId } = data;
try {
const ExistingUser = await userModel(organization).findOne({
_id: userId,
isArchive: false,
});
if (!ExistingUser) return { status: "User not found" };
const existingProject = await ProjectType(organization).findOne({
_id: projectId,
isArchive: false,
});
if (!existingProject) {
return { status: "project not found" };
} else {
const existingCollection = await collectionsModel(organization)
.findOne({
projectId: projectId,
isArchive: false,
_id: collectionNodeId,
})
.select(
"backgroundColor borderColor fontColor lineColor position lineThickness fontName lineType borderThickness cornerRadius fontSize"
);
if (!existingCollection) {
return { status: "Collection not found" };
}
const formattedCollection = {
position: existingCollection.position,
collectionName: existingCollection.collectionName,
};
return { status: "Success", data: formattedCollection };
}
@@ -496,7 +860,7 @@ const generateUniqueCollectionName = async (
const existingCollection = await collectionsModel(organization).findOne({
projectId,
isArchive: false,
collectionNodeName: nameToTry,
collectionName: nameToTry,
});
if (!existingCollection) {
return nameToTry;
@@ -509,11 +873,18 @@ const generateUniqueCollectionName = async (
}
}
};
export const DuplicateCollection = async (
data: IDuplicateCollectionNode
): Promise<Iresponse> => {
const { organization, userId, projectId, position, collectionNodeId } = data;
try {
const ExistingUser = await userModel(organization).findOne({
_id: userId,
isArchive: false,
});
if (!ExistingUser) return { status: "User not found" };
const existingProject = await ProjectType(organization).findOne({
_id: projectId,
isArchive: false,
@@ -530,7 +901,7 @@ export const DuplicateCollection = async (
return { status: "CollectionId not found for duplication" };
else {
const NewduplicateName = await generateUniqueCollectionName(
existingCollection.collectionNodeName,
existingCollection.collectionName,
organization,
projectId
);
@@ -541,7 +912,7 @@ export const DuplicateCollection = async (
projectId,
isArchive: false,
position,
collectionNodeName: NewduplicateName,
collectionName: NewduplicateName,
});
if (!NewCollectionDuplicate)
return { status: "Duplication unsuccessfull" };
@@ -570,3 +941,131 @@ export const DuplicateCollection = async (
}
}
};
export const DuplicateAttributes = async (
data: IDuplicateattributes
): Promise<Iresponse> => {
const {
organization,
userId,
projectId,
attrKey,
// position,
collectionNodeId,
} = data;
try {
const ExistingUser = await userModel(organization).findOne({
_id: userId,
isArchive: false,
});
if (!ExistingUser) return { status: "User not found" };
const existingProject = await ProjectType(organization).findOne({
_id: projectId,
isArchive: false,
});
if (!existingProject) {
return { status: "project not found" };
} else {
const existingCollection = await collectionsModel(organization).findOne({
projectId: projectId,
isArchive: false,
_id: collectionNodeId,
});
if (!existingCollection)
return { status: "CollectionId not found for duplication" };
else {
const existingAttr = existingCollection.attributes.find(
(attr: any) => attr.key.toLowerCase() === attrKey.toLowerCase()
);
console.log("existingAttr: ", existingAttr);
if (existingAttr) {
let counter = 1;
let newKey = `${attrKey}(${counter})`;
console.log("attrKey: ", attrKey);
console.log("newKey: ", newKey);
while (
existingCollection.attributes.some(
(attr: any) => attr.key === newKey
)
) {
console.log("hi");
counter++;
newKey = `${attrKey}(${counter})`;
console.log("newKey: ", newKey);
}
console.log("existingAttr.type: ", existingAttr.type);
existingCollection.attributes.push({
key: newKey,
type: existingAttr.type,
isArchive: false,
});
} else {
return { status: "Attribute doesnot match" };
}
await existingCollection.save();
}
return { status: "Success", data: existingCollection };
}
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};
export const GetcollectionLists = async (
data: IcollectionLists
): Promise<Iresponse> => {
const { organization, userId, projectId } = data;
try {
const ExistingUser = await userModel(organization).findOne({
_id: userId,
isArchive: false,
});
if (!ExistingUser) return { status: "User not found" };
const existingProject = await ProjectType(organization).findOne({
_id: projectId,
isArchive: false,
});
if (!existingProject) {
return { status: "project not found" };
} else {
const existingCollection = await collectionsModel(organization)
.find({
projectId: projectId,
isArchive: false,
})
.select("collectionName -_id");
if (!existingCollection) {
return { status: "Collection not found" };
}
const formattedCollection = {
projectName: existingProject.projectName,
application: existingProject.application,
collectionsName: existingCollection || [],
};
return { status: "Success", data: formattedCollection };
}
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};

View File

@@ -0,0 +1,680 @@
import mongoose from "mongoose";
import ProjectType from "../../shared/model/projectmodel";
import collectionsModel from "../model/collectionModel";
import dummyModel from "../model/dummycollectionmodel";
interface Iresponse {
status: string;
data?: any;
}
interface IcollectionNode {
projectId: string;
userId: string;
organization: string;
collectionName: string;
position: [number];
}
interface IAttribute {
key: string;
type: any;
}
interface IcollectionNodeName {
projectId: string;
userId: string;
organization: string;
collectionNodeId: string;
collectionName: string;
position: [number];
}
interface IcollectionAttributes {
projectId: string;
userId: string;
organization: string;
collectionNodeId: string;
attributes: IAttribute[];
}
interface IcollectionNodes {
projectId: string;
userId: string;
organization: string;
}
interface IcollectionNodeById {
projectId: string;
organization: string;
userId: string;
collectionNodeId: string;
}
interface IcollectionNodeRenameKey {
projectId: string;
organization: string;
userId: string;
collectionNodeId: string;
newKeyName: string;
oldKeyName: string;
}
interface IAttributesEdit {
projectId: string;
userId: string;
organization: string;
collectionNodeId: string;
attributeId: string;
key?: string;
type?: string;
required?: boolean;
defaultValue?: any;
unique?: boolean;
index?: boolean;
}
interface IAttributesDel {
projectId: string;
userId: string;
organization: string;
collectionNodeId: string;
AttributeId: string;
}
interface ICollectionDelete {
projectId: string;
organization: string;
userId: string;
collectionNodeId: string;
}
interface IDuplicateCollectionNode {
projectId: string;
userId: string;
collectionNodeId: string;
organization: string;
collectionName: string;
position: [number];
attributes: [];
}
export const Nodecreationdummy = async (
data: IcollectionNode
): Promise<Iresponse> => {
const { organization, projectId, position, userId, collectionName } = data;
try {
const existingProject = await ProjectType(organization).findOne({
_id: projectId,
isArchive: false,
});
if (!existingProject) {
return { status: "project not found" };
} else {
const newCollectionnode = await dummyModel(organization).create({
projectId: projectId,
isArchive: false,
position: position,
collectionName: collectionName,
});
if (!newCollectionnode)
return { status: "Collection node creation unsuccessfull" };
else return { status: "Success", data: newCollectionnode._id };
}
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};
export const SetCollectionNamedummy = async (
data: IcollectionNodeName
): Promise<Iresponse> => {
const {
organization,
projectId,
position,
collectionNodeId,
collectionName,
userId,
} = data;
try {
const existingProject = await ProjectType(organization).findOne({
_id: projectId,
isArchive: false,
});
if (!existingProject) {
return { status: "project not found" };
} else {
const existingCollection = await dummyModel(organization).findOne({
projectId: projectId,
isArchive: false,
_id: collectionNodeId,
});
if (!existingCollection) {
return { status: "Collection not found" };
}
const collectionNameupdate = await dummyModel(
organization
).findOneAndUpdate(
{
projectId: projectId,
isArchive: false,
_id: collectionNodeId,
},
{ collectionName: collectionName },
{ new: true }
);
return { status: "Success" };
}
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};
export const addAttributesdummy = async (
data: IcollectionAttributes
): Promise<Iresponse> => {
const { organization, projectId, userId, collectionNodeId, attributes } =
data;
try {
const existingProject = await ProjectType(organization).findOne({
_id: projectId,
isArchive: false,
});
if (!existingProject) {
return { status: "project not found" };
}
const existingCollection = await dummyModel(organization).findOne({
_id: collectionNodeId,
projectId,
isArchive: false,
});
if (!existingCollection) {
return { status: "Collection not found" };
}
let collections = existingCollection.collections || [];
if (collections.length === 0) {
collections.push({ fields: new Map<string, any>(), isArchive: false });
// collections.push({ fields: {}, isArchive: false });
}
const targetCollection = collections[0];
for (const attr of attributes) {
const key = attr.key.trim();
if (!targetCollection.fields.has(key)) {
(targetCollection.fields as Map<string, any>).set(key, {
type: attr.type,
isArchive: false,
});
}
}
existingCollection.collections = collections;
await existingCollection.save();
for (const [key, field] of targetCollection.fields.entries()) {
if (field.type === "object") {
const existingsubcollection = await dummyModel(organization).findOne({
projectId,
parentCollectionNodeId: collectionNodeId,
attributeparentId: (field as any)._id,
isArchive: false,
});
if (!existingsubcollection) {
const newCollection = await dummyModel(organization).create({
isArchive: false,
projectId,
collectionName: key,
parentCollectionNodeId: collectionNodeId,
attributeparentId: (field as any)._id,
attributes: [],
position: [0, 0, 0],
});
existingCollection.isSubCollection = true;
await existingCollection.save();
}
}
}
return { status: "Success" };
} catch (error: unknown) {
if (error instanceof Error) {
return { status: error.message };
}
return { status: "An unexpected error occurred" };
}
};
// export const GetNodesInProject = async (
// data: IcollectionNodes
// ): Promise<Iresponse> => {
// const { organization, userId, projectId } = data;
// try {
// const existingProject = await ProjectType(organization).findOne({
// _id: projectId,
// isArchive: false,
// });
// if (!existingProject) {
// return { status: "project not found" };
// } else {
// const collectionNodes = await collectionsModel(organization)
// .find({ projectId: projectId, isArchive: false })
// .select("collectionName attributes position -_id ");
// if (!collectionNodes)
// return { status: "No collection Nodes present", data: [] };
// else {
// const formattedCollections = collectionNodes.map((collection) => ({
// position: collection.position,
// collectionName: collection.collectionName,
// attributes: collection.attributes
// .filter((attr: any) => !attr.isArchive)
// .map((attr: any) => {
// const { isArchive, ...rest } = attr.toObject();
// return { ...rest };
// }),
// }));
// return { status: "Success", data: formattedCollections };
// }
// }
// } catch (error: unknown) {
// if (error instanceof Error) {
// return {
// status: error.message,
// };
// } else {
// return {
// status: "An unexpected error occurred",
// };
// }
// }
// };
// export const UpdateAttributes = async (
// data: IAttributesEdit
// ): Promise<Iresponse> => {
// const {
// organization,
// userId,
// projectId,
// collectionNodeId,
// attributeId,
// required,
// defaultValue,
// unique,
// index,
// key,
// type,
// } = data;
// try {
// const existingProject = await ProjectType(organization).findOne({
// _id: projectId,
// isArchive: false,
// });
// if (!existingProject) {
// return { status: "project not found" };
// } else {
// const existingCollection = await collectionsModel(organization).findOne({
// projectId: projectId,
// _id: collectionNodeId,
// isArchive: false,
// });
// if (!existingCollection) return { status: "Collection not found" };
// const editCollection = await collectionsModel(
// organization
// ).findOneAndUpdate(
// {
// projectId: projectId,
// isArchive: false,
// attributes: {
// $elemMatch: { _id: new mongoose.Types.ObjectId(attributeId) },
// },
// },
// {
// $set: {
// "attributes.$.required": required,
// "attributes.$.default": defaultValue,
// "attributes.$.index": index,
// "attributes.$.unique": unique,
// "attributes.$.key": key,
// "attributes.$.type": type,
// },
// },
// { new: true }
// );
// return { status: "Success" };
// }
// } catch (error: unknown) {
// if (error instanceof Error) {
// return {
// status: error.message,
// };
// } else {
// return {
// status: "An unexpected error occurred",
// };
// }
// }
// };
// export const DelAttributes = async (
// data: IAttributesDel
// ): Promise<Iresponse> => {
// const { organization, userId, projectId, collectionNodeId, AttributeId } =
// data;
// try {
// const existingProject = await ProjectType(organization).findOne({
// _id: projectId,
// isArchive: false,
// });
// if (!existingProject) {
// return { status: "project not found" };
// } else {
// const existingCollection = await collectionsModel(organization).findOne({
// projectId: projectId,
// _id: collectionNodeId,
// isArchive: false,
// });
// if (!existingCollection) return { status: "Collection not found" };
// const softDeleteAttribute = await collectionsModel(
// organization
// ).findOneAndUpdate(
// {
// projectId: projectId,
// isArchive: false,
// attributes: {
// $elemMatch: {
// _id: new mongoose.Types.ObjectId(AttributeId),
// isArchive: false,
// },
// },
// },
// {
// $set: {
// "attributes.$.isArchive": true,
// },
// },
// { new: true }
// );
// return { status: "Success" };
// }
// } catch (error: unknown) {
// if (error instanceof Error) {
// return {
// status: error.message,
// };
// } else {
// return {
// status: "An unexpected error occurred",
// };
// }
// }
// };
// export const delCollection = async (
// data: ICollectionDelete
// ): Promise<Iresponse> => {
// const { organization, userId, projectId, collectionNodeId } = data;
// try {
// const existingProject = await ProjectType(organization).findOne({
// _id: projectId,
// isArchive: false,
// });
// if (!existingProject) {
// return { status: "project not found" };
// } else {
// const existingCollection = await collectionsModel(organization).findOne({
// projectId: projectId,
// isArchive: false,
// _id: collectionNodeId,
// });
// if (!existingCollection) {
// return { status: "Collection not found" };
// }
// const collectionSoftDelete = await collectionsModel(
// organization
// ).findOneAndUpdate(
// {
// projectId: projectId,
// isArchive: false,
// _id: collectionNodeId,
// },
// { isArchive: true },
// { new: true }
// );
// return { status: "Success" };
// }
// } catch (error: unknown) {
// if (error instanceof Error) {
// return {
// status: error.message,
// };
// } else {
// return {
// status: "An unexpected error occurred",
// };
// }
// }
// };
export const GetcollectionNodedummy = async (
data: IcollectionNodeById
): Promise<Iresponse> => {
const { organization, userId, projectId, collectionNodeId } = data;
try {
const existingProject = await ProjectType(organization).findOne({
_id: projectId,
isArchive: false,
});
if (!existingProject) {
return { status: "project not found" };
} else {
const existingCollection = await dummyModel(organization).findOne({
projectId: projectId,
isArchive: false,
_id: collectionNodeId,
});
if (!existingCollection) {
return { status: "Collection not found" };
}
const fieldsMap = existingCollection.collections[0]?.fields || new Map();
console.log("fieldsMap: ", fieldsMap);
const formattedAttributes: Record<string, any> = {};
for (const [key, value] of fieldsMap.entries()) {
formattedAttributes[key] = value.type;
if (value.type === "object") {
const childrenData = await dummyModel(organization).findOne({
attributeparentId: (value as any)._id,
parentCollectionNodeId: collectionNodeId,
isArchive: false,
});
if (!childrenData) {
return { status: "subCollection not found" };
}
const fieldsChildrenMap =
childrenData.collections[0]?.fields || new Map();
const formattedChildrenAttributes: Record<string, any> = {};
for (const [childkey, childvalue] of fieldsChildrenMap.entries()) {
formattedChildrenAttributes[childkey] = childvalue.type;
}
formattedAttributes[key] = formattedChildrenAttributes;
}
}
const formattedCollection = {
position: existingCollection.position,
collectionName: existingCollection.collectionName,
collections: formattedAttributes,
};
return { status: "Success", data: formattedCollection };
}
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};
export const collectionKeyRenamedummy = async (
data: IcollectionNodeRenameKey
): Promise<Iresponse> => {
const {
organization,
userId,
projectId,
collectionNodeId,
oldKeyName,
newKeyName,
} = data;
try {
const existingProject = await await ProjectType(organization).findOne({
_id: projectId,
isArchive: false,
});
if (!existingProject) {
return { status: "project not found" };
} else {
const existingCollection = await dummyModel(organization).findOne({
projectId: projectId,
isArchive: false,
_id: collectionNodeId,
});
if (!existingCollection) {
return { status: "Collection not found" };
}
const fieldsMap = existingCollection.collections[0]?.fields || new Map();
console.log("fieldsMap: ", fieldsMap);
if (!fieldsMap.has(oldKeyName)) {
return { status: `Key "${oldKeyName}" not found` };
}
const fieldValue = fieldsMap.get(oldKeyName);
if (fieldValue) {
fieldsMap.delete(oldKeyName);
fieldsMap.set(newKeyName, fieldValue);
}
existingCollection.collections[0].fields = fieldsMap;
await existingCollection.save();
}
return { status: "Success" };
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};
// const generateUniqueCollectionName = async (
// baseName: string,
// organization: string,
// projectId: string
// ): Promise<string> => {
// let nameToTry = baseName;
// let attempt = 0;
// while (true) {
// const existingCollection = await collectionsModel(organization).findOne({
// projectId,
// isArchive: false,
// collectionName: nameToTry,
// });
// if (!existingCollection) {
// return nameToTry;
// }
// attempt++;
// nameToTry = `${baseName} (duplicate${attempt > 1 ? ` ${attempt}` : ""})`;
// if (attempt > 10) {
// throw new Error("Too many duplicate project name attempts");
// }
// }
// };
// export const DuplicateCollection = async (
// data: IDuplicateCollectionNode
// ): Promise<Iresponse> => {
// const { organization, userId, projectId, position, collectionNodeId } = data;
// try {
// const existingProject = await ProjectType(organization).findOne({
// _id: projectId,
// isArchive: false,
// });
// if (!existingProject) {
// return { status: "project not found" };
// } else {
// const existingCollection = await collectionsModel(organization).findOne({
// projectId: projectId,
// isArchive: false,
// _id: collectionNodeId,
// });
// if (!existingCollection)
// return { status: "CollectionId not found for duplication" };
// else {
// const NewduplicateName = await generateUniqueCollectionName(
// existingCollection.collectionName,
// organization,
// projectId
// );
// const NewCollectionDuplicate = await collectionsModel(
// organization
// ).create({
// projectId,
// isArchive: false,
// position,
// collectionName: NewduplicateName,
// });
// if (!NewCollectionDuplicate)
// return { status: "Duplication unsuccessfull" };
// else {
// const data = existingCollection.attributes
// .filter((attr: any) => !attr.isArchive)
// .map((attr: any) => {
// const { isArchive, _id, ...rest } = attr.toObject();
// return rest;
// });
// NewCollectionDuplicate.attributes = data;
// NewCollectionDuplicate.save();
// return { status: "Success" };
// }
// }
// }
// } catch (error: unknown) {
// if (error instanceof Error) {
// return {
// status: error.message,
// };
// } else {
// return {
// status: "An unexpected error occurred",
// };
// }
// }
// };

View File

@@ -1,293 +1,299 @@
import ProjectType from "../../shared/model/projectmodel";
import collectionsModel from "../model/collectionModel";
import edgeModel from "../model/edgeModel";
import userModel from "../model/userModel";
interface Iresponse {
status: string;
data?: any;
status: string;
data?: any;
}
interface IEdge {
organization: string;
projectId: string;
from: { collection_id: string, field: string };
to: { collection_id: string };
cardinality: string
organization: string;
userId: string;
projectId: string;
from: { collection_id: string; field: string };
to: { collection_id: string };
cardinality: string;
}
interface IAllEdge {
organization: string;
projectId: string;
organization: string;
projectId: string;
userId: string;
}
interface IEdgeDelete {
organization: string;
projectId: string;
edgeId: string;
organization: string;
projectId: string;
userId: string;
edgeId: string;
}
interface Attribute {
key: string;
type: string;
isArchive: boolean;
key: string;
type: string;
isArchive: boolean;
refKey?: {
collection_id: any;
fieldId: any;
refKey?: {
collection_id: any;
fieldId: any;
};
}
export const edgecreation = async (data: IEdge): Promise<Iresponse> => {
const { organization, projectId, from, to, cardinality, userId } = data;
try {
const ExistingUser = await userModel(organization).findOne({
_id: userId,
isArchive: false,
});
if (!ExistingUser) return { status: "User not found" };
const existingProject = await ProjectType(organization).findOne({
_id: projectId,
// createdBy: userName,
isArchive: false,
});
if (!existingProject) {
return { status: "project not found" };
}
const existingFromCollection = await collectionsModel(organization).findOne(
{
_id: from.collection_id,
isArchive: false,
}
);
if (!existingFromCollection) {
return { status: "From collection not found" };
}
const existingToCollection = await collectionsModel(organization).findOne({
_id: to.collection_id,
isArchive: false,
});
if (!existingToCollection) {
return { status: "To collection not found" };
}
const capitalizeFirst = (str: string) => {
if (!str) return str;
return str.charAt(0).toUpperCase() + str.slice(1);
};
}
export const edgecreation = async (
data: IEdge
): Promise<Iresponse> => {
const { organization, projectId, from, to, cardinality } = data;
const collectionName = existingFromCollection.collectionName;
const fieldName = from.field;
try {
const existingProject = await ProjectType(organization).findOne({
_id: projectId,
// createdBy: userName,
isArchive: false,
});
const newFieldKey = `${collectionName}_${capitalizeFirst(fieldName)}`;
if (!existingProject) {
return { status: "project not found" };
}
const fromField = existingFromCollection.attributes.find(
(attr: any) => attr.key === from.field
);
const fromFieldId = [fromField].map((attr: any) => attr?._id)[0];
const existingFromCollection = await collectionsModel(organization).findOne({
_id: from.collection_id,isArchive: false,
const fieldType = normalizeType(fromField?.type);
const fieldExists = existingToCollection.attributes.some(
(attr: any) => attr.key === newFieldKey
);
if (!fieldExists) {
const newAttribute: any = {
key: newFieldKey,
type: fieldType,
refKey: {
collection_id: existingFromCollection._id,
fieldId: fromFieldId,
},
};
existingToCollection.attributes.push(newAttribute);
existingToCollection.attributes = existingToCollection.attributes.map(
(attr: any) => ({
...attr,
type: normalizeType(attr.type),
})
);
if (!existingFromCollection) {
return { status: "From collection not found" };
}
const existingToCollection = await collectionsModel(organization).findOne({
_id: to.collection_id,isArchive: false
})
if (!existingToCollection) {
return { status: "To collection not found" };
}
await existingToCollection.save();
console.log(
`Field ${newFieldKey} (type: ${fieldType}) added to TO collection with reference to ${existingFromCollection._id}`
);
const newEdge = {
projectId,
from: { collection_id: existingFromCollection._id, field: from.field },
to: { collection_id: existingToCollection._id },
cardinality,
createdAt: new Date(),
};
const savedEdge = await edgeModel(organization).create(newEdge);
const capitalizeFirst = (str: string) => {
if (!str) return str;
return str.charAt(0).toUpperCase() + str.slice(1);
};
const collectionName = existingFromCollection.collectionNodeName;
const fieldName = from.field;
const newFieldKey = `${collectionName}${capitalizeFirst(fieldName)}`;
const fromField = existingFromCollection.attributes.find(
(attr: any) => attr.key === from.field
);
const fromFieldId = [fromField].map((attr: any) => attr?._id)[0];
const fieldType = normalizeType(fromField?.type);
const fieldExists = existingToCollection.attributes.some(
(attr: any) => attr.key === newFieldKey
);
if (!fieldExists) {
const newAttribute: any = {
key: newFieldKey,
type: fieldType,
refKey: {
collection_id: existingFromCollection._id,
fieldId: fromFieldId
}
};
existingToCollection.attributes.push(newAttribute);
existingToCollection.attributes = existingToCollection.attributes.map((attr: any) => ({
...attr,
type: normalizeType(attr.type),
}));
await existingToCollection.save();
console.log(
`Field ${newFieldKey} (type: ${fieldType}) added to TO collection with reference to ${existingFromCollection._id}`
);
const newEdge = {
projectId,
from: { collection_id: existingFromCollection._id, field: from.field },
to: { collection_id: existingToCollection._id },
cardinality,
createdAt: new Date(),
};
const savedEdge = await edgeModel(organization).create(newEdge);
//
return {
status: "Success",
data: savedEdge, // replace with savedEdge after model integration
};
}
else {
console.log("Field already exists");
return {
status: "Field already exists"
}
}
return {
status: "Success",
data: savedEdge,
};
} else {
console.log("Field already exists");
return {
status: "Field already exists",
};
}
catch (error: unknown) {
console.log('error: ', error);
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
} catch (error: unknown) {
console.log("error: ", error);
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};
export const Alledges = async (
data: IAllEdge
): Promise<Iresponse> => {
const { organization, projectId, } = data;
try {
const existingProject = await ProjectType(organization).findOne({
_id: projectId,
// createdBy: userName,
isArchive: false,
});
export const Alledges = async (data: IAllEdge): Promise<Iresponse> => {
const { organization, projectId, userId } = data;
try {
const ExistingUser = await userModel(organization).findOne({
_id: userId,
isArchive: false,
});
if (!existingProject) {
return { status: "project not found" };
}
const edgeDatas = await edgeModel(organization).find({isArchive: false})
if (!ExistingUser) return { status: "User not found" };
const existingProject = await ProjectType(organization).findOne({
_id: projectId,
// createdBy: userName,
isArchive: false,
});
if (!edgeDatas || edgeDatas.length === 0) {
return { status: "edge not found" };
}
return {
status: "Success",
data: edgeDatas, // replace with savedEdge after model integration
};
} catch (error: unknown) {
console.log('error: ', error);
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
if (!existingProject) {
return { status: "project not found" };
}
const edgeDatas = await edgeModel(organization).find({ isArchive: false });
if (!edgeDatas || edgeDatas.length === 0) {
return { status: "edge not found" };
}
return {
status: "Success",
data: edgeDatas, // replace with savedEdge after model integration
};
} catch (error: unknown) {
console.log("error: ", error);
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};
export const deleteEdge = async (
data: IEdgeDelete
): Promise<Iresponse> => {
const { organization, projectId, edgeId } = data;
export const deleteEdge = async (data: IEdgeDelete): Promise<Iresponse> => {
const { organization, projectId, edgeId, userId } = data;
try {
const existingProject = await ProjectType(organization).findOne({
_id: projectId,
// createdBy: userName,
isArchive: false,
});
try {
const ExistingUser = await userModel(organization).findOne({
_id: userId,
isArchive: false,
});
if (!existingProject) {
return { status: "project not found" };
}
const deleteEdge = await edgeModel(organization).findOneAndUpdate
({ _id: edgeId, isArchive: false }, {
isArchive: true
}, { new: true })
if (!deleteEdge) return { status: "Edge not found" }
const collectionDoc = await collectionsModel(organization).findOne({
_id: deleteEdge?.to?.collection_id, isArchive: false
});
if (!ExistingUser) return { status: "User not found" };
const existingProject = await ProjectType(organization).findOne({
_id: projectId,
// createdBy: userName,
isArchive: false,
});
if (!collectionDoc ) {
return { status: "collection not found" };
}
else {
const attributes = collectionDoc.attributes || [];
const matchedAttr = attributes.find((attr, index) => {
const refKey: any = (attr as any).refKey;
if (refKey) {
return String(refKey.collection_id) === String(deleteEdge?.from?.collection_id);
}
return false;
});
if (matchedAttr) {
const index = attributes.indexOf(matchedAttr);
if (index > -1) {
attributes.splice(index, 1);
await collectionDoc.save();
console.log(`Attribute at index ${index} deleted successfully.`)
}
else {
console.log('Matched attribute not found in array');
}
} else {
// console.log('No attribute matches the given collection_id');
return { status: "No deleted in matched Document" }
}
}
return {status:"Success"}
} catch (error: unknown) {
console.log('error: ', error);
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
if (!existingProject) {
return { status: "project not found" };
}
const deleteEdge = await edgeModel(organization).findOneAndUpdate(
{ _id: edgeId, isArchive: false },
{
isArchive: true,
},
{ new: true }
);
if (!deleteEdge) return { status: "Edge not found" };
const collectionDoc = await collectionsModel(organization).findOne({
_id: deleteEdge?.to?.collection_id,
isArchive: false,
});
if (!collectionDoc) {
return { status: "collection not found" };
} else {
const attributes = collectionDoc.attributes || [];
const matchedAttr = attributes.find((attr, index) => {
const refKey: any = (attr as any).refKey;
if (refKey) {
return (
String(refKey.collection_id) ===
String(deleteEdge?.from?.collection_id)
);
}
return false;
});
if (matchedAttr) {
const index = attributes.indexOf(matchedAttr);
if (index > -1) {
attributes.splice(index, 1);
await collectionDoc.save();
console.log(`Attribute at index ${index} deleted successfully.`);
} else {
console.log("Matched attribute not found in array");
}
} else {
// console.log('No attribute matches the given collection_id');
return { status: "No deleted in matched Document" };
}
}
return { status: "Success" };
} catch (error: unknown) {
console.log("error: ", error);
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};
const normalizeType = (type: any): string => {
if (!type) return "string"; // default
if (typeof type === "string") {
switch (type.toLowerCase()) {
case "boolean":
return "boolean";
case "number":
return "number";
case "string":
return "string";
case "object":
return "object";
case "array":
return "array";
case "date":
return "date";
default:
return "string";
}
if (!type) return "string"; // default
if (typeof type === "string") {
switch (type.toLowerCase()) {
case "boolean":
return "boolean";
case "number":
return "number";
case "string":
return "string";
case "object":
return "object";
case "array":
return "array";
case "date":
return "date";
default:
return "string";
}
}
// Handle cases like [Number], Boolean, Object
if (Array.isArray(type)) return "array";
if (type === Boolean) return "boolean";
if (type === Number) return "number";
if (type === String) return "string";
if (type === Object) return "object";
// Handle cases like [Number], Boolean, Object
if (Array.isArray(type)) return "array";
if (type === Boolean) return "boolean";
if (type === Number) return "number";
if (type === String) return "string";
if (type === Object) return "object";
return "string"; // fallback
};
return "string"; // fallback
};

View File

@@ -6,6 +6,10 @@ interface IrecentlyViewed {
organization: string;
userId: string;
}
interface IuserDetails {
organization: string;
userId: string;
}
interface Iresponse {
status: string;
data?: any;
@@ -49,3 +53,36 @@ export const recentlyViewedServices = async (
}
}
};
export const homeuserProfileServices = async (
data: IuserDetails
): Promise<Iresponse> => {
const { organization, userId } = data;
try {
const ExistingUser = await userModel(organization).findOne({
_id: userId,
isArchive: false,
});
const profileData = await userDataModel(organization)
.findOne({ userId: userId, isArchive: false })
.select("-_id");
if (!ExistingUser) return { status: "User not found" };
else {
const DestructureData = {
Email: ExistingUser.email,
userName: ExistingUser.userName,
profile: profileData || ExistingUser.userName.charAt(0),
};
return { status: "Success", data: DestructureData };
}
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};

View File

@@ -1,3 +1,4 @@
import { skip } from "node:test";
import MVCarcModel from "../../shared/model/mvcModel";
import ProjectType from "../../shared/model/projectmodel";
import collectionsModel from "../model/collectionModel";
@@ -5,16 +6,17 @@ import edgeModel from "../model/edgeModel";
import shareModel from "../model/shareModel";
import userDataModel from "../model/userDataModel";
import userModel from "../model/userModel";
import versionModel from "../model/versionModel";
interface Iresponse {
status: string;
data?: any;
}
interface IProject {
useableLanguage: string;
language: string;
organization: string;
projectName: string;
userId: string;
apiType: string;
apiProtocol: string;
application: string;
architecture: string;
description: string;
@@ -26,24 +28,50 @@ interface IProjectView {
}
interface IProjectstructure {
projectId: string;
userId: string;
organization: string;
}
interface IgetProject {
organization: string;
userId: string;
skipdata: number;
limitdata: number;
}
interface ProjectUpdate {
language: string;
organization: string;
projectName: string;
userId: string;
projectId: string;
application: string;
architecture: string;
description: string;
}
export const previousVersion = async (
projectId: string,
organization: string
) => {
const result = await versionModel(organization).findOne({
projectId: projectId,
isArchive: false,
});
return result;
};
export const projectCreationService = async (
data: IProject
): Promise<Iresponse> => {
const {
organization,
projectName,
useableLanguage,
language,
description,
userId,
apiType,
apiProtocol,
application,
architecture,
} = data;
@@ -60,14 +88,14 @@ export const projectCreationService = async (
if (existingProject) {
return { status: "Project Already Exists" };
} else {
if (architecture.toLowerCase() === "mvc") {
if (architecture.toUpperCase() === "MVC") {
const newProject = await ProjectType(organization).create({
projectName,
createdBy: userId,
useableLanguage,
language,
architecture,
apiType: apiType,
appType: application,
apiProtocol: apiProtocol,
application: application,
description,
});
if (!newProject) return { status: "Project creation unsuccessfull" };
@@ -107,6 +135,34 @@ export const projectCreationService = async (
MVCCreation.folders.push(...createdFolders);
await MVCCreation.save();
const versionData = await previousVersion(
newProject._id,
organization
);
const versionNameDesc = new Date().toLocaleString("en-US", {
month: "short",
day: "numeric",
year: "numeric",
hour: "numeric",
minute: "2-digit",
});
if (!versionData || versionData.length === 0) {
const newVersion = await versionModel(organization).create({
projectId: newProject._id,
createdBy: userId,
version: 0.1,
versionName: versionNameDesc,
description: versionNameDesc,
});
await ProjectType(organization).findByIdAndUpdate(
{ _id: newProject._id, isArchive: false },
{
total_versions: `v-${newVersion.version.toFixed(1)}`,
Present_version: newVersion._id,
}
);
}
return { status: "Success", data: newProject._id };
} else {
return {
@@ -114,7 +170,17 @@ export const projectCreationService = async (
};
}
} else {
return { status: "New architecture" };
const newProject = await ProjectType(organization).create({
projectName,
createdBy: userId,
language,
architecture,
apiProtocol: apiProtocol,
application: application,
description,
});
if (!newProject) return { status: "Project creation unsuccessfull" };
return { status: "Success", data: newProject._id };
}
}
} catch (error: unknown) {
@@ -131,7 +197,7 @@ export const projectCreationService = async (
};
export const projectDatas = async (data: IgetProject): Promise<Iresponse> => {
const { organization, userId } = data;
const { organization, userId, limitdata, skipdata } = data;
try {
const ExistingUser = await userModel(organization).findOne({
_id: userId,
@@ -151,10 +217,16 @@ export const projectDatas = async (data: IgetProject): Promise<Iresponse> => {
} else {
query;
}
console.log("query: ", query);
const projectDatas = await ProjectType(organization)
.find(query)
.select("-__v -isArchive -createdAt -updatedAt");
.select("projectName createdBy thumbnail")
.populate({
path: "createdBy",
model: userModel(organization),
select: "userName",
})
.skip(skipdata)
.limit(limitdata);
if (!projectDatas) return { status: "No project found" };
return { status: "Success", data: projectDatas };
} catch (error: unknown) {
@@ -173,8 +245,15 @@ export const projectDatas = async (data: IgetProject): Promise<Iresponse> => {
export const GetNodesInProject = async (
data: IProjectstructure
): Promise<Iresponse> => {
const { organization, projectId } = data;
const { organization, projectId, userId } = data;
try {
const ExistingUser = await userModel(organization).findOne({
_id: userId,
isArchive: false,
});
if (!ExistingUser) {
return { status: "User not found" };
}
const existingProject = await ProjectType(organization).findOne({
_id: projectId,
isArchive: false,
@@ -184,7 +263,7 @@ export const GetNodesInProject = async (
} else {
const collectionNodesdata = await collectionsModel(organization)
.find({ projectId: projectId, isArchive: false })
.select("collectionNodeName attributes position -_id ");
.select("collectionName attributes position -_id ");
const edgeNodes = await edgeModel(organization)
.find({ projectId: projectId, isArchive: false })
.select("cardinality from to");
@@ -194,7 +273,7 @@ export const GetNodesInProject = async (
else {
const collectionNodes = collectionNodesdata.map((collection) => ({
position: collection.position,
collectionNodeName: collection.collectionNodeName,
collectionName: collection.collectionName,
attributes: collection.attributes
.filter((attr: any) => !attr.isArchive)
.map((attr: any) => {
@@ -254,7 +333,6 @@ export const ViewProjectService = async (
select: "userName",
})
.select("_id projectName createdBy");
console.log("projectData: ", projectData);
if (projectData === null) {
return { status: "Datas not found" };
}
@@ -325,7 +403,68 @@ export const DeleteProject = async (data: IProjectView): Promise<Iresponse> => {
{ isArchive: true },
{ new: true }
);
if(!deleteProject) return {status:"Project Delete unsuccessfull"}
if (!deleteProject) return { status: "Project Delete unsuccessfull" };
return { status: "Success" };
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};
export const projectModification = async (
data: ProjectUpdate
): Promise<Iresponse> => {
try {
const {
projectId,
organization,
userId,
projectName,
application,
description,
language,
architecture,
} = data;
const ExistingUser = await userModel(organization).findOne({
_id: userId,
isArchive: false,
});
if (!ExistingUser) return { status: "User not found" };
let query: any = {
_id: projectId,
isArchive: false,
};
const existingProject = await ProjectType(organization).findOne(query);
if (!existingProject) return { status: "Project not found" };
if (ExistingUser.role === "Editor") {
query = {
...query,
$or: [{ createdBy: userId }, { members: userId }],
};
} else if (ExistingUser.role === "Viewer") {
query = {
...query,
members: userId,
};
} else {
query;
}
const updateProject = await ProjectType(organization).findOneAndUpdate(
query,
{ projectName, application, description, language, architecture },
{ new: true }
);
if (!updateProject) return { status: "Project updated unsuccessfull" };
return { status: "Success" };
} catch (error: unknown) {
if (error instanceof Error) {

View File

@@ -0,0 +1,428 @@
import collectionsModel ,{ICollectionNode} from "../model/collectionModel";
import edgeModel ,{IEdgeModel}from "../model/edgeModel";
import ProjectType from "../model/projectmodel";
import userDataModel from "../model/userDataModel";
import userModel from "../model/userModel";
import versionModel from "../model/versionModel";
import { existingProjectById, existingUser } from "../utils/functionality";
type VersionData = {
Project: {
edges: IEdgeModel[];
collectionNode: ICollectionNode[];
};
};
interface IVersionSave {
organization: string;
hierarchyVersion: string;
versionName: string;
projectId: string;
userId: string;
createdBy: string;
description?: string;
}
interface IVersionRollback {
organization: string;
versionId: string;
projectId: string;
userId: string;
description?: string;
}
interface IVersionHistory {
organization: string;
projectId: string;
userId: string;
page: number;
limit: number;
sortBy?: string;
sortOrder?: string;
}
interface IVersionUpdate {
organization: string;
projectId: string;
userId: string;
page: number;
versionId: string;
versionName?: string;
description?: string;
}
interface IVersionById {
organization: string;
projectId: string;
versionId: string;
userId: string;
}
interface IResult {
status: string;
data?: object;
}
export const CreateVersion = async (data: IVersionSave): Promise<IResult> => {
try {
const {
hierarchyVersion,
projectId,
versionName,
description,
userId,
organization,
createdBy,
} = data;
const ExistingUser = await userModel(organization).findOne({
_id: userId,
isArchive: false,
});
if (!ExistingUser) return { status: "User not found" };
const existingProject = await ProjectType(organization).findOne({
_id: projectId,
isArchive: false,
});
if (!existingProject) {
return { status: "project not found" };
}
const versionData = await versionModel(organization).findOne({
_id: hierarchyVersion,
projectId: projectId,
isArchive: false,
});
if (!versionData) return { status: "Parent Version not found" };
const versionDataprevious = await versionModel(organization)
.findOne({
projectId: projectId,
isArchive: false,
})
.sort({ version: -1 });
const currentVersion = versionDataprevious?.version ?? 0;
const newVersion = parseFloat((currentVersion + 0.1).toFixed(2));
const saveVersion = await versionModel(organization).create({
versionName: versionName,
parentVersionID: versionData._id,
projectId: projectId,
description: description,
createdBy: createdBy,
previous_Version: currentVersion,
version: newVersion,
createdAt: new Date(),
});
const find_User = await userDataModel(organization).findById({
_id: saveVersion.createdBy,
isArchive: false,
});
const responseVersionData = {
versionId: saveVersion._id,
version: saveVersion.version,
description: saveVersion.description,
versionName: saveVersion.versionName,
createdAt: saveVersion.createdAt,
createdBy: {
userId: find_User._id,
userName: find_User.userName,
},
};
await existingProject.updateOne({
Present_version: saveVersion._id,
total_versions: `v-${saveVersion.version.toFixed(1)}`,
});
await AllCloneFornewVersions(
projectId,
organization,
saveVersion._id,
hierarchyVersion
);
return { status: "Success", data: responseVersionData };
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};
export const GetVersionById = async (data: IVersionById): Promise<IResult> => {
try {
const { projectId, userId, organization, versionId } = data;
const userExisting = await existingUser(userId, organization);
if (!userExisting) {
return {
status: "User not found",
};
}
const LivingProject = await existingProjectById(
projectId,
organization,
userId
);
if (!LivingProject) return { status: "Project not found" };
const existingVersion = await versionModel(organization)
.findOne({
_id: versionId,
projectId: projectId,
isArchive: false,
})
.select("version previous_Version");
if (!existingVersion) {
return { status: "Version not found for the project" };
}
const [collectionNode, edges] =
await Promise.all([
collectionsModel(organization).find({
versionId,
projectId,
isArchive: false,
}),
edgeModel(organization).find({
versionId,
projectId,
isArchive: false,
}),
]);
const versionData: VersionData = {
Project: {
collectionNode,
edges
},
};
return {
status: "Success",
data: {
version: existingVersion,
entities: versionData,
},
};
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};
export const RollBackversion = async (
data: IVersionRollback
): Promise<IResult> => {
try {
const { versionId, projectId, userId, organization } = data;
const userExisting = await existingUser(userId, organization);
if (!userExisting) {
return {
status: "User not found",
};
}
const LivingProject = await existingProjectById(
projectId,
organization,
userId
);
if (!LivingProject) return { status: "Project not found" };
const rollbackversion = await versionModel(organization).findOne({
_id: versionId,
projectId: projectId,
isArchive: false,
});
if (!rollbackversion)
return { status: "Mentioned Version not found for the Rollback" };
const versionDataprevious = await versionModel(organization)
.findOne({
projectId: projectId,
isArchive: false,
})
.sort({ version: -1 });
const currentVersion = versionDataprevious?.version ?? 0;
const newVersion = parseFloat((currentVersion + 0.01).toFixed(2));
const saveVersion = await versionModel(organization).create({
parentVersionID: rollbackversion._id,
projectId: projectId,
createdBy: userId,
previous_Version: currentVersion,
version: newVersion,
createdAt: new Date(),
rollBackComment: `RollBack from the version ${rollbackversion.version}`,
});
LivingProject.Present_version = saveVersion._id;
LivingProject.total_versions = `v-${saveVersion.version.toFixed(2)}`;
await LivingProject.save();
await AllCloneFornewVersions(
projectId,
organization,
saveVersion._id,
rollbackversion._id
);
return { status: "Success", data: saveVersion._id };
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};
export const VersionHistory = async (
data: IVersionHistory
): Promise<IResult> => {
try {
const { organization, userId, projectId, page, limit, sortOrder } = data;
const userExisting = await existingUser(userId, organization);
if (!userExisting) return { status: "User not found" };
const LivingProject = await existingProjectById(
projectId,
organization,
userId
);
if (!LivingProject) return { status: "Project not found" };
const filter: object = { projectId, isArchive: false };
const total = await versionModel(organization).countDocuments(filter);
const versiondatas = await versionModel(organization)
.find(filter)
.sort({ ["version"]: sortOrder === "asc" ? 1 : -1 })
.skip((page - 1) * limit)
.limit(limit)
.select("version createdBy createdAt description versionName")
.populate({
path: "createdBy",
model: userDataModel(organization),
select: "userName",
});
// .populate({
// path: "createdBy",
// model: UsersDataModel(organization),
// select: "profilePicture",
// });
// console.log('versiondatas: ', versiondatas);
if (!versiondatas)
return {
status: "Versions not found",
};
const versions = versiondatas.map((version) => {
return {
versionId: version._id,
version: version.version,
createdAt: version.createdAt,
description: version.description,
versionName: version.versionName,
createdBy: {
userId: version.createdBy._id,
userName: version.createdBy.userName,
},
};
});
return {
status: "Success",
data: {
versions,
Metadatas: {
total,
page,
limit,
hasNextPage: page * limit < total,
},
},
};
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};
export const updateVersion = async (data: IVersionUpdate): Promise<IResult> => {
try {
const {
organization,
userId,
projectId,
versionId,
versionName,
description,
} = data;
const userExisting = await existingUser(userId, organization);
if (!userExisting) return { status: "User not found" };
const LivingProject = await existingProjectById(
projectId,
organization,
userId
);
if (!LivingProject) return { status: "Project not found" };
const existingVersionId = await versionModel(organization).findOne({
_id: versionId,
isArchive: false,
projectId: projectId,
});
if (!existingVersionId) {
return { status: "VersionId not match" };
} else {
existingVersionId.versionName = versionName;
existingVersionId.description = description;
await existingVersionId.save();
return { status: "Version Updated successfully" };
}
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};
export const AllCloneFornewVersions = async (
projectId: string,
organization: string,
versionId: string,
oldeVersionId: string
) => {
const cloneDocuments = async (model: any, modelName: string) => {
const docs = await model(organization).find({
projectId,
isArchive: false,
versionId: oldeVersionId,
});
if (!docs.length) return;
const clonedDocs = docs.map((doc: any) => {
const { _id, __v, ...rest } = doc.toObject();
return { ...rest, versionId };
});
const created = await model(organization).create(clonedDocs);
};
await Promise.all([
cloneDocuments(collectionsModel, "collections"),
cloneDocuments(edgeModel, "edges"),
]);
};

View File

@@ -0,0 +1,27 @@
import { Types } from "mongoose";
import ProjectType from "../model/projectmodel";
import userModel from "../model/userModel";
export const existingUser = async (userId: string, organization: string) => {
if (!Types.ObjectId.isValid(userId)) {
console.log("Invalid ObjectId format");
return null;
}
const userData = await userModel(organization).findOne({
_id: userId,
isArchive: false,
});
return userData;
};
export const existingProjectById = async (
projectId: string,
organization: string,
userId: string
) => {
const projectData = await ProjectType(organization).findOne({
_id: projectId,
isArchive: false,
});
return projectData;
};

View File

@@ -1,70 +1,74 @@
import { Socket, Server } from "socket.io";
import { EVENTS } from "../events/events";
import { ErrorResponse, FinalResponse, validateFields } from "../utils/socketfunctionHelpers";
import {
ErrorResponse,
FinalResponse,
validateFields,
} from "../utils/socketfunctionHelpers";
import { emitToSenderAndAdmins } from "../utils/emitEventResponse";
import { projectCreationService } from "../../shared/services/projectService";
export const projectHandleEvent = async (
event: string,
socket: Socket,
io: Server,
data: any,
connectedUsersByOrg: {
[org: string]: { socketId: string; userId: string; role: string }[];
}
event: string,
socket: Socket,
io: Server,
data: any,
connectedUsersByOrg: {
[org: string]: { socketId: string; userId: string; role: string }[];
}
) => {
if (event !== EVENTS.projectCreate || !data?.organization) return;
const requiredFields = [
"application",
"architecture",
"apiType",
"projectName",
"useableLanguage",
"organization",
];
const missingFields = validateFields(data, requiredFields);
if (event !== EVENTS.projectCreate || !data?.organization) return;
const requiredFields = [
"application",
"architecture",
"apiProtocol",
"projectName",
"language",
"organization",
];
const missingFields = validateFields(data, requiredFields);
if (missingFields.length > 0) {
emitToSenderAndAdmins(
io,
socket,
data.organization,
EVENTS.projectCreateResponse,
ErrorResponse(missingFields, socket, data.organization),
connectedUsersByOrg
);
return;
}
const result = await projectCreationService(data);
const status = typeof result?.status === "string" ? result.status : "unknown";
const messages: Record<string, { message: string }> = {
Success: { message: "Project Created Successfully" },
"Project Already Exists": { message: "Project Already Exists" },
"Already MVC architecture assigned to this projectId": { message: "Already MVC architecture assigned to this projectId" },
"Project creation unsuccessfull": {
message: "Project creation unsuccessfull",
},
"New architecture": { message: "New architecture" },
};
const result_Datas =
status === "Success" && result?.data ? result.data : undefined;
const response = FinalResponse(
status,
socket,
data.organization,
messages,
result_Datas
);
if (missingFields.length > 0) {
emitToSenderAndAdmins(
io,
socket,
data.organization,
EVENTS.projectCreateResponse,
response,
connectedUsersByOrg
io,
socket,
data.organization,
EVENTS.projectCreateResponse,
ErrorResponse(missingFields, socket, data.organization),
connectedUsersByOrg
);
};
return;
}
const result = await projectCreationService(data);
const status = typeof result?.status === "string" ? result.status : "unknown";
const messages: Record<string, { message: string }> = {
Success: { message: "Project Created Successfully" },
"Project Already Exists": { message: "Project Already Exists" },
"Already MVC architecture assigned to this projectId": {
message: "Already MVC architecture assigned to this projectId",
},
"Project creation unsuccessfull": {
message: "Project creation unsuccessfull",
},
"New architecture": { message: "New architecture" },
};
const result_Datas =
status === "Success" && result?.data ? result.data : undefined;
const response = FinalResponse(
status,
socket,
data.organization,
messages,
result_Datas
);
emitToSenderAndAdmins(
io,
socket,
data.organization,
EVENTS.projectCreateResponse,
response,
connectedUsersByOrg
);
};