First commit

This commit is contained in:
2025-08-27 17:48:45 +05:30
parent 38ac249f3b
commit 477e39f6dc
17 changed files with 2248 additions and 2248 deletions

View File

@@ -1,20 +1,20 @@
import express from "express"; import express from "express";
import cors from "cors"; import cors from "cors";
import dotenv from "dotenv"; import dotenv from "dotenv";
import projectRoutes from "./routes/projectRoutes"; import projectRoutes from "./routes/projectRoutes";
import collectionNodeRoutes from "./routes/collectionRoutes"; import collectionNodeRoutes from "./routes/collectionRoutes";
import edgeRoutes from "./routes/edgeRoutes"; import edgeRoutes from "./routes/edgeRoutes";
dotenv.config({ quiet: true }); dotenv.config({ quiet: true });
const app = express(); const app = express();
app.use(cors()); app.use(cors());
app.use(express.json({ limit: "50mb" })); app.use(express.json({ limit: "50mb" }));
app.use( app.use(
express.urlencoded({ limit: "50mb", extended: true, parameterLimit: 50000 }) express.urlencoded({ limit: "50mb", extended: true, parameterLimit: 50000 })
); );
app.use("/api/v1", projectRoutes); app.use("/api/v1", projectRoutes);
app.use("/api/v1", collectionNodeRoutes); app.use("/api/v1", collectionNodeRoutes);
app.use("/api/v1", edgeRoutes); app.use("/api/v1", edgeRoutes);
export default app; export default app;

View File

@@ -1,459 +1,459 @@
import { Request, Response } from "express"; import { Request, Response } from "express";
import { import {
addAttributes, addAttributes,
DelAttributes, DelAttributes,
delCollection, delCollection,
DuplicateCollection, DuplicateCollection,
GetcollectionNode, GetcollectionNode,
GetNodesInProject, GetNodesInProject,
Nodecreation, Nodecreation,
SetCollectionName, SetCollectionName,
UpdateAttributes, UpdateAttributes,
} from "../../shared/services/collectionService"; } from "../../shared/services/collectionService";
export const NodeCreationController = async ( export const NodeCreationController = async (
req: Request, req: Request,
res: Response res: Response
): Promise<void> => { ): Promise<void> => {
try { try {
const { organization, projectId, position } = req.body; const { organization, projectId, position } = req.body;
if (!organization || !projectId || !position) { if (!organization || !projectId || !position) {
res.status(400).json({ res.status(400).json({
message: "All fields are required", message: "All fields are required",
}); });
return; return;
} }
const data = { const data = {
organization, organization,
projectId, projectId,
position, position,
}; };
const result = await Nodecreation(data); const result = await Nodecreation(data);
switch (result.status) { switch (result.status) {
case "project not found": case "project not found":
res.status(200).json({ res.status(200).json({
message: "project not found", message: "project not found",
}); });
break; break;
case "Collection node creation unsuccessfull": case "Collection node creation unsuccessfull":
res.status(200).json({ res.status(200).json({
message: "Collection node creation unsuccessfull", message: "Collection node creation unsuccessfull",
}); });
break; break;
case "Success": case "Success":
res.status(200).json({ res.status(200).json({
message: "Node created successfully", message: "Node created successfully",
collectionNodeId: result.data, collectionNodeId: result.data,
}); });
break; break;
default: default:
res.status(500).json({ res.status(500).json({
message: "Internal server error", message: "Internal server error",
}); });
break; break;
} }
} catch (error) { } catch (error) {
res.status(500).json({ res.status(500).json({
message: "Unknown error", message: "Unknown error",
}); });
} }
}; };
export const SetCollectionNameController = async ( export const SetCollectionNameController = async (
req: Request, req: Request,
res: Response res: Response
): Promise<void> => { ): Promise<void> => {
try { try {
const { const {
organization, organization,
projectId, projectId,
collectionNodeId, collectionNodeId,
collectionName, collectionName,
position, position,
} = req.body; } = req.body;
if (!organization || !projectId || !collectionName || !collectionNodeId) { if (!organization || !projectId || !collectionName || !collectionNodeId) {
res.status(400).json({ res.status(400).json({
message: "All fields are required", message: "All fields are required",
}); });
return; return;
} }
const data = { const data = {
organization, organization,
projectId, projectId,
collectionNodeId, collectionNodeId,
collectionName, collectionName,
position, position,
}; };
const result = await SetCollectionName(data); const result = await SetCollectionName(data);
switch (result.status) { switch (result.status) {
case "project not found": case "project not found":
res.status(200).json({ res.status(200).json({
message: "project not found", message: "project not found",
}); });
break; break;
case "Collection not found": case "Collection not found":
res.status(200).json({ res.status(200).json({
message: "Collection not found", message: "Collection not found",
}); });
break; break;
case "Success": case "Success":
res.status(200).json({ res.status(200).json({
message: "collection name updated", message: "collection name updated",
}); });
break; break;
default: default:
res.status(500).json({ res.status(500).json({
message: "Internal server error", message: "Internal server error",
}); });
break; break;
} }
} catch (error) { } catch (error) {
res.status(500).json({ res.status(500).json({
message: "Unknown error", message: "Unknown error",
}); });
} }
}; };
export const CollectionDatas = async ( export const CollectionDatas = async (
req: Request, req: Request,
res: Response res: Response
): Promise<void> => { ): Promise<void> => {
try { try {
const { projectId, organization, collectionNodeId } = req.params; const { projectId, organization, collectionNodeId } = req.params;
if (!organization || !projectId || !collectionNodeId) { if (!organization || !projectId || !collectionNodeId) {
res.status(400).json({ res.status(400).json({
message: "All fields are required", message: "All fields are required",
}); });
return; return;
} }
const data = { const data = {
organization, organization,
projectId, projectId,
collectionNodeId, collectionNodeId,
}; };
const result = await GetcollectionNode(data); const result = await GetcollectionNode(data);
switch (result.status) { switch (result.status) {
case "project not found": case "project not found":
res.status(200).json({ res.status(200).json({
message: "project not found", message: "project not found",
}); });
break; break;
case "No collection Nodes present": case "No collection Nodes present":
res.status(200).json({ res.status(200).json({
message: "No collection Nodes present", message: "No collection Nodes present",
Collections: result.data, Collections: result.data,
}); });
break; break;
case "Success": case "Success":
res.status(200).json(result.data); res.status(200).json(result.data);
break; break;
default: default:
res.status(500).json({ res.status(500).json({
message: "Internal server error", message: "Internal server error",
}); });
break; break;
} }
} catch (error) { } catch (error) {
res.status(500).json({ res.status(500).json({
message: "Unknown error", message: "Unknown error",
}); });
} }
}; };
export const DeleteCollectionsController = async ( export const DeleteCollectionsController = async (
req: Request, req: Request,
res: Response res: Response
): Promise<void> => { ): Promise<void> => {
try { try {
const { organization, projectId, collectionNodeId } = req.params; const { organization, projectId, collectionNodeId } = req.params;
if (!organization || !projectId || !collectionNodeId) { if (!organization || !projectId || !collectionNodeId) {
res.status(400).json({ res.status(400).json({
message: "All fields are required", message: "All fields are required",
}); });
return; return;
} }
const data = { const data = {
organization, organization,
projectId, projectId,
collectionNodeId, collectionNodeId,
}; };
const result = await delCollection(data); const result = await delCollection(data);
switch (result.status) { switch (result.status) {
case "project not found": case "project not found":
res.status(200).json({ res.status(200).json({
message: "project not found", message: "project not found",
}); });
break; break;
case "Collection not found": case "Collection not found":
res.status(200).json({ res.status(200).json({
message: "Collection not found", message: "Collection not found",
}); });
break; break;
case "Success": case "Success":
res.status(200).json({ message: "Collection deleted successfully" }); res.status(200).json({ message: "Collection deleted successfully" });
break; break;
default: default:
res.status(500).json({ res.status(500).json({
message: "Internal server error", message: "Internal server error",
}); });
break; break;
} }
} catch (error) { } catch (error) {
res.status(500).json({ res.status(500).json({
message: "Unknown error", message: "Unknown error",
}); });
} }
}; };
export const DuplicateNodeCollectionController = async ( export const DuplicateNodeCollectionController = async (
req: Request, req: Request,
res: Response res: Response
): Promise<void> => { ): Promise<void> => {
try { try {
const { collectionNodeId } = req.params; const { collectionNodeId } = req.params;
const { projectId, organization, collectionName, position, attributes } = const { projectId, organization, collectionName, position, attributes } =
req.body; req.body;
if (!organization || !projectId || !collectionNodeId) { if (!organization || !projectId || !collectionNodeId) {
res.status(400).json({ res.status(400).json({
message: "All fields are required", message: "All fields are required",
}); });
return; return;
} }
const data = { const data = {
organization, organization,
projectId, projectId,
collectionName, collectionName,
position, position,
attributes, attributes,
collectionNodeId, collectionNodeId,
}; };
const result = await DuplicateCollection(data); const result = await DuplicateCollection(data);
switch (result.status) { switch (result.status) {
case "project not found": case "project not found":
res.status(200).json({ res.status(200).json({
message: "project not found", message: "project not found",
}); });
break; break;
case "Duplication unsuccessfull": case "Duplication unsuccessfull":
res.status(200).json({ res.status(200).json({
message: "Duplication unsuccessfull", message: "Duplication unsuccessfull",
}); });
break; break;
case "Success": case "Success":
res.status(200).json({ message: "Duplicated successfully" }); res.status(200).json({ message: "Duplicated successfully" });
break; break;
default: default:
res.status(500).json({ res.status(500).json({
message: "Internal server error", message: "Internal server error",
}); });
break; break;
} }
} catch (error) { } catch (error) {
res.status(500).json({ res.status(500).json({
message: "Unknown error", message: "Unknown error",
}); });
} }
}; };
export const NodesCollectionsBasedOnproject = async ( export const NodesCollectionsBasedOnproject = async (
req: Request, req: Request,
res: Response res: Response
): Promise<void> => { ): Promise<void> => {
try { try {
const { projectId, organization } = req.params; const { projectId, organization } = req.params;
if (!organization || !projectId) { if (!organization || !projectId) {
res.status(400).json({ res.status(400).json({
message: "All fields are required", message: "All fields are required",
}); });
return; return;
} }
const data = { const data = {
organization, organization,
projectId, projectId,
}; };
const result = await GetNodesInProject(data); const result = await GetNodesInProject(data);
switch (result.status) { switch (result.status) {
case "project not found": case "project not found":
res.status(200).json({ res.status(200).json({
message: "project not found", message: "project not found",
}); });
break; break;
case "No collection Nodes present": case "No collection Nodes present":
res.status(200).json({ res.status(200).json({
message: "No collection Nodes present", message: "No collection Nodes present",
Collections: result.data, Collections: result.data,
}); });
break; break;
case "Success": case "Success":
res.status(200).json({ Collections: result.data }); res.status(200).json({ Collections: result.data });
break; break;
default: default:
res.status(500).json({ res.status(500).json({
message: "Internal server error", message: "Internal server error",
}); });
break; break;
} }
} catch (error) { } catch (error) {
res.status(500).json({ res.status(500).json({
message: "Unknown error", message: "Unknown error",
}); });
} }
}; };
export const AddAttributesController = async ( export const AddAttributesController = async (
req: Request, req: Request,
res: Response res: Response
): Promise<void> => { ): Promise<void> => {
try { try {
const { collectionNodeId } = req.params; const { collectionNodeId } = req.params;
const { organization, projectId, attributes } = req.body; const { organization, projectId, attributes } = req.body;
if (!organization || !projectId || !attributes || !collectionNodeId) { if (!organization || !projectId || !attributes || !collectionNodeId) {
res.status(400).json({ res.status(400).json({
message: "All fields are required", message: "All fields are required",
}); });
return; return;
} }
const data = { const data = {
organization, organization,
projectId, projectId,
collectionNodeId, collectionNodeId,
attributes, attributes,
}; };
const result = await addAttributes(data); const result = await addAttributes(data);
switch (result.status) { switch (result.status) {
case "project not found": case "project not found":
res.status(200).json({ res.status(200).json({
message: "project not found", message: "project not found",
}); });
break; break;
case "Collection not found": case "Collection not found":
res.status(200).json({ res.status(200).json({
message: "Collection not found", message: "Collection not found",
}); });
break; break;
case "Success": case "Success":
res.status(200).json({ res.status(200).json({
message: "collection Attributes Added", message: "collection Attributes Added",
}); });
break; break;
default: default:
res.status(500).json({ res.status(500).json({
message: "Internal server error", message: "Internal server error",
}); });
break; break;
} }
} catch (error) { } catch (error) {
res.status(500).json({ res.status(500).json({
message: "Unknown error", message: "Unknown error",
}); });
} }
}; };
export const updateAttributesCollections = async ( export const updateAttributesCollections = async (
req: Request, req: Request,
res: Response res: Response
): Promise<void> => { ): Promise<void> => {
try { try {
const { collectionNodeId, attributeId } = req.params; const { collectionNodeId, attributeId } = req.params;
const { const {
organization, organization,
projectId, projectId,
required, required,
defaultValue, defaultValue,
unique, unique,
index, index,
key, key,
type, type,
} = req.body; } = req.body;
if (!organization || !projectId || !collectionNodeId || !attributeId) { if (!organization || !projectId || !collectionNodeId || !attributeId) {
res.status(400).json({ res.status(400).json({
message: "All fields are required", message: "All fields are required",
}); });
return; return;
} }
const data = { const data = {
organization, organization,
projectId, projectId,
collectionNodeId, collectionNodeId,
attributeId, attributeId,
required, required,
defaultValue, defaultValue,
unique, unique,
index, index,
key, key,
type, type,
}; };
const result = await UpdateAttributes(data); const result = await UpdateAttributes(data);
switch (result.status) { switch (result.status) {
case "project not found": case "project not found":
res.status(200).json({ res.status(200).json({
message: "project not found", message: "project not found",
}); });
break; break;
case "Collection not found": case "Collection not found":
res.status(200).json({ res.status(200).json({
message: "Collection not found", message: "Collection not found",
}); });
break; break;
case "Success": case "Success":
res.status(200).json({ message: "Field updated successfully" }); res.status(200).json({ message: "Field updated successfully" });
break; break;
default: default:
res.status(500).json({ res.status(500).json({
message: "Internal server error", message: "Internal server error",
}); });
break; break;
} }
} catch (error) { } catch (error) {
res.status(500).json({ res.status(500).json({
message: "Unknown error", message: "Unknown error",
}); });
} }
}; };
export const delAttributesCollections = async ( export const delAttributesCollections = async (
req: Request, req: Request,
res: Response res: Response
): Promise<void> => { ): Promise<void> => {
try { try {
const { collectionNodeId } = req.params; const { collectionNodeId } = req.params;
const { organization, projectId, AttributeId } = req.body; const { organization, projectId, AttributeId } = req.body;
if (!organization || !projectId || !collectionNodeId || !AttributeId) { if (!organization || !projectId || !collectionNodeId || !AttributeId) {
res.status(400).json({ res.status(400).json({
message: "All fields are required", message: "All fields are required",
}); });
return; return;
} }
const data = { const data = {
organization, organization,
projectId, projectId,
collectionNodeId, collectionNodeId,
AttributeId, AttributeId,
}; };
const result = await DelAttributes(data); const result = await DelAttributes(data);
switch (result.status) { switch (result.status) {
case "project not found": case "project not found":
res.status(200).json({ res.status(200).json({
message: "project not found", message: "project not found",
}); });
break; break;
case "Collection not found": case "Collection not found":
res.status(200).json({ res.status(200).json({
message: "Collection not found", message: "Collection not found",
Collections: result.data, Collections: result.data,
}); });
break; break;
case "Success": case "Success":
res.status(200).json({ message: "Field deleted successfully" }); res.status(200).json({ message: "Field deleted successfully" });
break; break;
default: default:
res.status(500).json({ res.status(500).json({
message: "Internal server error", message: "Internal server error",
}); });
break; break;
} }
} catch (error) { } catch (error) {
res.status(500).json({ res.status(500).json({
message: "Unknown error", message: "Unknown error",
}); });
} }
}; };

View File

@@ -1,157 +1,157 @@
import { Request, Response } from "express"; import { Request, Response } from "express";
import { Alledges, deleteEdge, edgecreation } from "../../shared/services/edgeService"; import { Alledges, deleteEdge, edgecreation } from "../../shared/services/edgeService";
export const edgeCreationController = async ( export const edgeCreationController = async (
req: Request, req: Request,
res: Response res: Response
): Promise<void> => { ): Promise<void> => {
try { try {
const { organization, projectId, from,to,cardinality } = req.body; const { organization, projectId, from,to,cardinality } = req.body;
if (!organization || !projectId || !from || !to) { if (!organization || !projectId || !from || !to) {
res.status(400).json({ res.status(400).json({
message: "All fields are required", message: "All fields are required",
}); });
return; return;
} }
const data = { const data = {
organization, organization,
projectId, projectId,
from, from,
to, to,
cardinality cardinality
}; };
const result = await edgecreation(data); const result = await edgecreation(data);
switch (result.status) { switch (result.status) {
case "project not found": case "project not found":
res.status(200).json({ res.status(200).json({
message: "project not found", message: "project not found",
}); });
break; break;
case "From collection not found": case "From collection not found":
res.status(200).json({ res.status(200).json({
message: "From collection not found", message: "From collection not found",
}); });
break; break;
case "To collection not found": case "To collection not found":
res.status(200).json({ res.status(200).json({
message: "To collection not found", message: "To collection not found",
}); });
break; break;
case "Field already exists": case "Field already exists":
res.status(200).json({ res.status(200).json({
message: "Field already exists", message: "Field already exists",
}); });
break; break;
case "Success": case "Success":
res.status(200).json({ res.status(200).json({
message:"Edge created successfully", message:"Edge created successfully",
collectionNodeId: result.data, collectionNodeId: result.data,
}); });
break; break;
default: default:
res.status(500).json({ res.status(500).json({
message: "Internal server error", message: "Internal server error",
}); });
break; break;
} }
} catch (error) { } catch (error) {
res.status(500).json({ res.status(500).json({
message: "Unknown error", message: "Unknown error",
}); });
} }
}; };
export const allEdgesController = async ( export const allEdgesController = async (
req: Request, req: Request,
res: Response res: Response
): Promise<void> => { ): Promise<void> => {
try { try {
const { organization, projectId, } = req.body; const { organization, projectId, } = req.body;
if (!organization || !projectId ) { if (!organization || !projectId ) {
res.status(400).json({ res.status(400).json({
message: "All fields are required", message: "All fields are required",
}); });
return; return;
} }
const data = { const data = {
organization, organization,
projectId, projectId,
}; };
const result = await Alledges(data); const result = await Alledges(data);
switch (result.status) { switch (result.status) {
case "project not found": case "project not found":
res.status(200).json({ res.status(200).json({
message: "project not found", message: "project not found",
}); });
break; break;
case "edge not found": case "edge not found":
res.status(200).json({ res.status(200).json({
message: "edge not found", message: "edge not found",
}); });
break; break;
case "Success": case "Success":
res.status(200).json({ res.status(200).json({
message:"fetch all Edge datas successfully", message:"fetch all Edge datas successfully",
collectionNodeId: result.data, collectionNodeId: result.data,
}); });
break; break;
default: default:
res.status(500).json({ res.status(500).json({
message: "Internal server error", message: "Internal server error",
}); });
break; break;
} }
} catch (error) { } catch (error) {
res.status(500).json({ res.status(500).json({
message: "Unknown error", message: "Unknown error",
}); });
} }
}; };
export const deleteEdgesController = async ( export const deleteEdgesController = async (
req: Request, req: Request,
res: Response res: Response
): Promise<void> => { ): Promise<void> => {
try { try {
const { organization, projectId, edgeId} = req.body; const { organization, projectId, edgeId} = req.body;
if (!organization || !projectId ||!edgeId) { if (!organization || !projectId ||!edgeId) {
res.status(400).json({ res.status(400).json({
message: "All fields are required", message: "All fields are required",
}); });
return; return;
} }
const data = { const data = {
organization, organization,
projectId, projectId,
edgeId edgeId
}; };
const result = await deleteEdge(data); const result = await deleteEdge(data);
switch (result.status) { switch (result.status) {
case "project not found": case "project not found":
res.status(200).json({ res.status(200).json({
message: "project not found", message: "project not found",
}); });
break; break;
case "edge not found": case "edge not found":
res.status(200).json({ res.status(200).json({
message: "edge not found", message: "edge not found",
}); });
break; break;
case "Success": case "Success":
res.status(200).json({ res.status(200).json({
message:"Edge deleted successfully", message:"Edge deleted successfully",
collectionNodeId: result.data, collectionNodeId: result.data,
}); });
break; break;
default: default:
res.status(500).json({ res.status(500).json({
message: "Internal server error", message: "Internal server error",
}); });
break; break;
} }
} catch (error) { } catch (error) {
res.status(500).json({ res.status(500).json({
message: "Unknown error", message: "Unknown error",
}); });
} }
}; };

View File

@@ -1,95 +1,95 @@
import fs from "node:fs"; import fs from "node:fs";
import { Request, Response } from "express"; import { Request, Response } from "express";
import path from "path"; import path from "path";
import baseType from "../../shared/model/projectmodel"; import baseType from "../../shared/model/projectmodel";
import FileMode from "../../shared/model/collectionModel"; import FileMode from "../../shared/model/collectionModel";
export const fileModelCreatecontroller = async ( export const fileModelCreatecontroller = async (
req: Request, req: Request,
res: Response res: Response
): Promise<any> => { ): Promise<any> => {
const { pathName, baseId, modelName, organization, attributes } = req.body; const { pathName, baseId, modelName, organization, attributes } = req.body;
try { try {
const findBaseName = await baseType(organization).findById(baseId); const findBaseName = await baseType(organization).findById(baseId);
const attrToSchema = (attr: any) => { const attrToSchema = (attr: any) => {
const mapType: any = { const mapType: any = {
string: "String", string: "String",
number: "Number", number: "Number",
boolean: "Boolean", boolean: "Boolean",
}; };
const lines = []; const lines = [];
for (const [key, config] of Object.entries(attr)) { for (const [key, config] of Object.entries(attr)) {
const line: string[] = []; const line: string[] = [];
line.push(`${key}: {`); line.push(`${key}: {`);
line.push(` type: ${mapType[(config as any).type] || "String"},`); line.push(` type: ${mapType[(config as any).type] || "String"},`);
if ((config as any).required) line.push(` required: true,`); if ((config as any).required) line.push(` required: true,`);
if ((config as any).default !== undefined) if ((config as any).default !== undefined)
line.push(` default: ${(config as any).default},`); line.push(` default: ${(config as any).default},`);
if ((config as any).minLength) if ((config as any).minLength)
line.push(` minlength: ${(config as any).minLength},`); line.push(` minlength: ${(config as any).minLength},`);
if ((config as any).maxLength) if ((config as any).maxLength)
line.push(` maxlength: ${(config as any).maxLength},`); line.push(` maxlength: ${(config as any).maxLength},`);
if ((config as any).min !== undefined) if ((config as any).min !== undefined)
line.push(` min: ${(config as any).min},`); line.push(` min: ${(config as any).min},`);
if ((config as any).max !== undefined) if ((config as any).max !== undefined)
line.push(` max: ${(config as any).max},`); line.push(` max: ${(config as any).max},`);
line.push("},"); line.push("},");
lines.push(line.join("\n")); lines.push(line.join("\n"));
} }
return lines.join("\n"); return lines.join("\n");
}; };
const schemaCode = ` const schemaCode = `
import mongoose from 'mongoose'; import mongoose from 'mongoose';
const ${modelName}Schema = new mongoose.Schema({ const ${modelName}Schema = new mongoose.Schema({
${attrToSchema(attributes)} ${attrToSchema(attributes)}
}); });
export const ${modelName} = mongoose.model('${modelName}', ${modelName}Schema); export const ${modelName} = mongoose.model('${modelName}', ${modelName}Schema);
`; `;
const basePath = path.join( const basePath = path.join(
pathName, pathName,
findBaseName.BaseName, findBaseName.BaseName,
"src", "src",
"Models" "Models"
); );
const modelFilePath = path.join(basePath, `${modelName}SchemaModel.ts`); const modelFilePath = path.join(basePath, `${modelName}SchemaModel.ts`);
// Read all subfolders inside basePath // Read all subfolders inside basePath
if (!fs.existsSync(basePath)) { if (!fs.existsSync(basePath)) {
fs.mkdirSync(basePath, { recursive: true }); fs.mkdirSync(basePath, { recursive: true });
} }
fs.writeFileSync(modelFilePath, schemaCode.trim()); fs.writeFileSync(modelFilePath, schemaCode.trim());
return res return res
.status(200) .status(200)
.json({ message: "Model file created successfully." }); .json({ message: "Model file created successfully." });
// const folders = ["Controller", "Routes", "Models", "Services"]; // const folders = ["Controller", "Routes", "Models", "Services"];
// if (!fs.existsSync(basePath)) { // if (!fs.existsSync(basePath)) {
// fs.mkdirSync(basePath, { recursive: true }); // fs.mkdirSync(basePath, { recursive: true });
// console.log(`Created root path: ${basePath}`); // console.log(`Created root path: ${basePath}`);
// } // }
// folders.forEach(async (folder) => { // folders.forEach(async (folder) => {
// const fullPath = path.join(basePath, folder); // const fullPath = path.join(basePath, folder);
// if (!fs.existsSync(fullPath)) { // if (!fs.existsSync(fullPath)) {
// fs.mkdirSync(fullPath, { recursive: true }); // fs.mkdirSync(fullPath, { recursive: true });
// const BaseDataSave = await FileMode(organization).create({ // const BaseDataSave = await FileMode(organization).create({
// baseId, // baseId,
// modelName, // modelName,
// attributes, // attributes,
// }); // });
// } else { // } else {
// res.send(`Folder already exists: ${fullPath}`); // res.send(`Folder already exists: ${fullPath}`);
// console.log(`Folder already exists: ${folder}`); // console.log(`Folder already exists: ${folder}`);
// } // }
// }); // });
} catch (error: unknown) { } catch (error: unknown) {
res.send(error); res.send(error);
} }
}; };

View File

@@ -1,168 +1,168 @@
import { Request, Response } from "express"; import { Request, Response } from "express";
import { import {
GetNodesInProject, GetNodesInProject,
projectCreationService, projectCreationService,
projectDatas, projectDatas,
} from "../../shared/services/projectService"; } from "../../shared/services/projectService";
export const projectCreationController = async ( export const projectCreationController = async (
req: Request, req: Request,
res: Response res: Response
): Promise<void> => { ): Promise<void> => {
try { try {
const { const {
organization, organization,
useableLanguage, useableLanguage,
projectName, projectName,
userName, userName,
apiType, apiType,
application, application,
architecture, architecture,
description, description,
} = req.body; } = req.body;
if ( if (
!organization || !organization ||
!useableLanguage || !useableLanguage ||
!projectName || !projectName ||
!userName || !userName ||
!apiType || !apiType ||
!architecture|| !application !architecture|| !application
) { ) {
res.status(400).json({ res.status(400).json({
message: "All fields are required", message: "All fields are required",
}); });
return; return;
} }
const data = { const data = {
organization, organization,
projectName, projectName,
useableLanguage, useableLanguage,
description,application, description,application,
userName, userName,
apiType, apiType,
architecture, architecture,
}; };
const result = await projectCreationService(data); const result = await projectCreationService(data);
switch (result.status) { switch (result.status) {
case "Project Already Exists": case "Project Already Exists":
res.status(403).json({ res.status(403).json({
message: "Project Already Exists", message: "Project Already Exists",
}); });
break; break;
case "Already MVC architecture assigned to this projectId": case "Already MVC architecture assigned to this projectId":
res.status(403).json({ res.status(403).json({
message: "Already MVC architecture assigned to this projectId", message: "Already MVC architecture assigned to this projectId",
}); });
break; break;
case "Project creation unsuccessfull": case "Project creation unsuccessfull":
res.status(200).json({ res.status(200).json({
message: "Project creation unsuccessfull", message: "Project creation unsuccessfull",
}); });
break; break;
case "Success": case "Success":
res.status(200).json({ res.status(200).json({
message: "Project created successfully", message: "Project created successfully",
projectId: result.data, projectId: result.data,
}); });
break; break;
case "New architecture": case "New architecture":
res.status(200).json({ res.status(200).json({
message: "New architecture", message: "New architecture",
}); });
break; break;
default: default:
res.status(500).json({ res.status(500).json({
message: "Internal server error", message: "Internal server error",
}); });
break; break;
} }
} catch (error) { } catch (error) {
res.status(500).json({ res.status(500).json({
message: "Unknown error", message: "Unknown error",
}); });
} }
}; };
export const getProjects = async ( export const getProjects = async (
req: Request, req: Request,
res: Response res: Response
): Promise<void> => { ): Promise<void> => {
try { try {
const { organization } = req.body; const { organization } = req.body;
if (!organization) { if (!organization) {
res.status(400).json({ res.status(400).json({
message: "All fields are required", message: "All fields are required",
}); });
return; return;
} }
const result = await projectDatas(organization); const result = await projectDatas(organization);
switch (result.status) { switch (result.status) {
case "No project found": case "No project found":
res.status(200).json({}); res.status(200).json({});
break; break;
case "Success": case "Success":
res.status(200).json({ res.status(200).json({
message: "Project created successfully", message: "Project created successfully",
projectDatas: result.data, projectDatas: result.data,
}); });
break; break;
default: default:
res.status(500).json({ res.status(500).json({
message: "Internal server error", message: "Internal server error",
}); });
break; break;
} }
} catch (error) { } catch (error) {
res.status(500).json({ res.status(500).json({
message: "Unknown error", message: "Unknown error",
}); });
} }
}; };
export const NodesCollectionsBasedOnproject = async ( export const NodesCollectionsBasedOnproject = async (
req: Request, req: Request,
res: Response res: Response
): Promise<void> => { ): Promise<void> => {
try { try {
const { projectId, organization } = req.params; const { projectId, organization } = req.params;
if (!organization || !projectId) { if (!organization || !projectId) {
res.status(400).json({ res.status(400).json({
message: "All fields are required", message: "All fields are required",
}); });
return; return;
} }
const data = { const data = {
organization, organization,
projectId, projectId,
}; };
const result = await GetNodesInProject(data); const result = await GetNodesInProject(data);
switch (result.status) { switch (result.status) {
case "project not found": case "project not found":
res.status(200).json({ res.status(200).json({
message: "project not found", message: "project not found",
}); });
break; break;
case "No collection Nodes present": case "No collection Nodes present":
res.status(200).json({ res.status(200).json({
message: "No collection Nodes present", message: "No collection Nodes present",
Collections: result.data, Collections: result.data,
}); });
break; break;
case "Success": case "Success":
res.status(200).json(result.data); res.status(200).json(result.data);
break; break;
default: default:
res.status(500).json({ res.status(500).json({
message: "Internal server error", message: "Internal server error",
}); });
break; break;
} }
} catch (error) { } catch (error) {
res.status(500).json({ res.status(500).json({
message: "Unknown error", message: "Unknown error",
}); });
} }
}; };

View File

@@ -1,5 +1,5 @@
import app from "./app"; import app from "./app";
const port = process.env.API_PORT; const port = process.env.API_PORT;
app.listen(port, () => { app.listen(port, () => {
console.log(`Port is running on the ${port}`); console.log(`Port is running on the ${port}`);
}); });

View File

@@ -1,58 +1,58 @@
import express from "express"; import express from "express";
import { import {
AddAttributesController, AddAttributesController,
CollectionDatas, CollectionDatas,
delAttributesCollections, delAttributesCollections,
DeleteCollectionsController, DeleteCollectionsController,
DuplicateNodeCollectionController, DuplicateNodeCollectionController,
NodeCreationController, NodeCreationController,
NodesCollectionsBasedOnproject, NodesCollectionsBasedOnproject,
SetCollectionNameController, SetCollectionNameController,
updateAttributesCollections, updateAttributesCollections,
} from "../controller/collectionNodeController"; } from "../controller/collectionNodeController";
const collectionNodeRoutes = express.Router(); const collectionNodeRoutes = express.Router();
//Node creation //Node creation
collectionNodeRoutes.post("/nodes", NodeCreationController); collectionNodeRoutes.post("/nodes", NodeCreationController);
//collection Added //collection Added
collectionNodeRoutes.patch( collectionNodeRoutes.patch(
"/nodes/collectionName", "/nodes/collectionName",
SetCollectionNameController SetCollectionNameController
); );
//duplicate collection //duplicate collection
collectionNodeRoutes.post( collectionNodeRoutes.post(
"/nodes/:collectionNodeId/duplicate", "/nodes/:collectionNodeId/duplicate",
DuplicateNodeCollectionController DuplicateNodeCollectionController
); );
//particular collection data //particular collection data
collectionNodeRoutes.get( collectionNodeRoutes.get(
"/nodes/:organization/:projectId/:collectionNodeId", "/nodes/:organization/:projectId/:collectionNodeId",
CollectionDatas CollectionDatas
); );
//delete collection //delete collection
collectionNodeRoutes.patch( collectionNodeRoutes.patch(
"/nodes/:organization/:projectId/:collectionNodeId", "/nodes/:organization/:projectId/:collectionNodeId",
DeleteCollectionsController DeleteCollectionsController
); );
//Add fields //Add fields
collectionNodeRoutes.patch( collectionNodeRoutes.patch(
"/nodes/:collectionNodeId/attributes", "/nodes/:collectionNodeId/attributes",
AddAttributesController AddAttributesController
); );
//Collections and fiels based on the project //Collections and fiels based on the project
collectionNodeRoutes.get( collectionNodeRoutes.get(
"/nodes/:organization/:projectId", "/nodes/:organization/:projectId",
NodesCollectionsBasedOnproject NodesCollectionsBasedOnproject
); );
//update fields //update fields
collectionNodeRoutes.patch( collectionNodeRoutes.patch(
"/nodes/:collectionNodeId/attributes/:attributeId", "/nodes/:collectionNodeId/attributes/:attributeId",
updateAttributesCollections updateAttributesCollections
); );
//delete fields //delete fields
collectionNodeRoutes.patch( collectionNodeRoutes.patch(
"/nodes/:collectionNodeId/attributes/softDelete", "/nodes/:collectionNodeId/attributes/softDelete",
delAttributesCollections delAttributesCollections
); );
export default collectionNodeRoutes; export default collectionNodeRoutes;

View File

@@ -1,8 +1,8 @@
import express from "express"; import express from "express";
import { allEdgesController, deleteEdgesController, edgeCreationController } from "../controller/edgeController"; import { allEdgesController, deleteEdgesController, edgeCreationController } from "../controller/edgeController";
const edgeRoutes = express.Router(); const edgeRoutes = express.Router();
edgeRoutes.post("/edgeCreate", edgeCreationController); edgeRoutes.post("/edgeCreate", edgeCreationController);
edgeRoutes.patch("/edgeDelete", deleteEdgesController); edgeRoutes.patch("/edgeDelete", deleteEdgesController);
edgeRoutes.get("/allEdges", allEdgesController); edgeRoutes.get("/allEdges", allEdgesController);
export default edgeRoutes; export default edgeRoutes;

View File

@@ -1,12 +1,12 @@
import express from "express"; import express from "express";
import { NodesCollectionsBasedOnproject, projectCreationController } from "../controller/projectController"; import { NodesCollectionsBasedOnproject, projectCreationController } from "../controller/projectController";
const projectRoutes = express.Router(); const projectRoutes = express.Router();
projectRoutes.post("/Newproject", projectCreationController); projectRoutes.post("/Newproject", projectCreationController);
projectRoutes.get( projectRoutes.get(
"/nodes/:organization/:projectId", "/nodes/:organization/:projectId",
NodesCollectionsBasedOnproject NodesCollectionsBasedOnproject
); );
// appRoutes.post("/createfileModel", fileModelCreatecontroller); // appRoutes.post("/createfileModel", fileModelCreatecontroller);
export default projectRoutes; export default projectRoutes;

View File

@@ -1,50 +1,50 @@
import mongoose, { Schema, Connection, Model } from "mongoose"; import mongoose, { Schema, Connection, Model } from "mongoose";
import dotenv from "dotenv"; import dotenv from "dotenv";
interface ConnectionCache { interface ConnectionCache {
[key: string]: Connection; [key: string]: Connection;
} }
const connections: ConnectionCache = {}; const connections: ConnectionCache = {};
dotenv.config({ quiet: true }); dotenv.config({ quiet: true });
const MainModel = <T>( const MainModel = <T>(
db: string, db: string,
modelName: string, modelName: string,
schema: Schema<T>, schema: Schema<T>,
collectionName: string collectionName: string
): Model<T> => { ): Model<T> => {
const db1_url = `${process.env.MONGO_URI}${db}`; const db1_url = `${process.env.MONGO_URI}${db}`;
const authOptions = { const authOptions = {
user: process.env.MONGO_USER, user: process.env.MONGO_USER,
pass: process.env.MONGO_PASSWORD, pass: process.env.MONGO_PASSWORD,
authSource: process.env.MONGO_AUTH_DB || "admin", authSource: process.env.MONGO_AUTH_DB || "admin",
maxPoolSize: 50, maxPoolSize: 50,
}; };
if (connections[db]) { if (connections[db]) {
return connections[db].model<T>(modelName, schema, collectionName); return connections[db].model<T>(modelName, schema, collectionName);
} }
try { try {
const db1 = mongoose.createConnection(db1_url, authOptions); const db1 = mongoose.createConnection(db1_url, authOptions);
connections[db] = db1; connections[db] = db1;
db1.on("connected", () => { db1.on("connected", () => {
console.log(`Connected to MongoDB database: ${db}`); console.log(`Connected to MongoDB database: ${db}`);
}); });
db1.on("error", (err) => { db1.on("error", (err) => {
console.error( console.error(
`MongoDB connection error for database ${db}:`, `MongoDB connection error for database ${db}:`,
err.message err.message
); );
}); });
return db1.model<T>(modelName, schema, collectionName); return db1.model<T>(modelName, schema, collectionName);
} catch (error) { } catch (error) {
console.error("Database connection error:", (error as Error).message); console.error("Database connection error:", (error as Error).message);
throw error; throw error;
} }
}; };
export default MainModel; export default MainModel;

View File

@@ -1,73 +1,73 @@
import { Schema, Document } from "mongoose"; import { Schema, Document } from "mongoose";
import MainModel from "../connection/connection"; import MainModel from "../connection/connection";
import { IProject } from "./projectmodel"; import { IProject } from "./projectmodel";
type IattributeTypes = type IattributeTypes =
| "string" | "string"
| "any" | "any"
| "Array" | "Array"
| "Date" | "Date"
| "Enum" | "Enum"
| "undefined" | "undefined"
| "object" | "object"
| "ObjectId" | "ObjectId"
| "number" | "number"
| "boolean"; | "boolean";
interface IAttributes { interface IAttributes {
isArchive: boolean; isArchive: boolean;
key: string; key: string;
type: IattributeTypes; type: IattributeTypes;
refKey?: object; refKey?: object;
required?: boolean; required?: boolean;
default?: any; default?: any;
unique?: boolean; unique?: boolean;
index?: boolean; index?: boolean;
} }
interface ICollectionNode extends Document { interface ICollectionNode extends Document {
projectId: IProject["_id"]; projectId: IProject["_id"];
collectionNodeName: string; collectionNodeName: string;
attributes: IAttributes[]; attributes: IAttributes[];
isArchive: boolean; isArchive: boolean;
position: [number, number, number]; position: [number, number, number];
} }
const attributeSchema = new Schema<IAttributes>({ const attributeSchema = new Schema<IAttributes>({
key: { type: String, required: true }, key: { type: String, required: true },
type: { type: {
type: String, type: String,
required: true, required: true,
enum: [ enum: [
"string", "string",
"number", "number",
"boolean", "boolean",
"Date", "Date",
"ObjectId", "ObjectId",
"Array", "Array",
"Enum", "Enum",
"object", "object",
"any", "any",
], ],
}, },
required: { type: Boolean }, required: { type: Boolean },
refKey: { type: Object }, refKey: { type: Object },
default: { type: Schema.Types.Mixed }, default: { type: Schema.Types.Mixed },
unique: { type: Boolean }, unique: { type: Boolean },
index: { type: Boolean }, index: { type: Boolean },
isArchive: { type: Boolean, default: false }, isArchive: { type: Boolean, default: false },
}); });
const collectionSchema: Schema<ICollectionNode> = new Schema( const collectionSchema: Schema<ICollectionNode> = new Schema(
{ {
projectId: { type: Schema.Types.ObjectId, ref: "Project" }, projectId: { type: Schema.Types.ObjectId, ref: "Project" },
collectionNodeName: { type: String }, collectionNodeName: { type: String },
position: { type: [Number], required: true }, position: { type: [Number], required: true },
isArchive: { type: Boolean, default: false }, isArchive: { type: Boolean, default: false },
attributes: [attributeSchema], attributes: [attributeSchema],
}, },
{ {
timestamps: true, timestamps: true,
} }
); );
const collectionsModel = (db: any) => { const collectionsModel = (db: any) => {
return MainModel(db, "collectionNode", collectionSchema, "collectionNode"); return MainModel(db, "collectionNode", collectionSchema, "collectionNode");
}; };
export default collectionsModel; export default collectionsModel;

View File

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

View File

@@ -1,38 +1,38 @@
import { Schema, Document } from "mongoose"; import { Schema, Document } from "mongoose";
import MainModel from "../connection/connection"; import MainModel from "../connection/connection";
import { IProject } from "./projectmodel"; import { IProject } from "./projectmodel";
interface Ifolders extends Document { interface Ifolders extends Document {
folderName: string; folderName: string;
createdAt: number; createdAt: number;
} }
const folderSchema: Schema = new Schema({ const folderSchema: Schema = new Schema({
folderName: { type: String, required: true }, folderName: { type: String, required: true },
createdAt: { type: Date, default: Date.now }, createdAt: { type: Date, default: Date.now },
}); });
export interface IMVCPrject extends Document { export interface IMVCPrject extends Document {
projectId: IProject["_id"]; projectId: IProject["_id"];
controllers: boolean; controllers: boolean;
routes: boolean; routes: boolean;
models: boolean; models: boolean;
services: boolean; services: boolean;
middleware: boolean; middleware: boolean;
utils: boolean; utils: boolean;
config: boolean; config: boolean;
folders: Ifolders[]; folders: Ifolders[];
} }
const mvcSchema: Schema = new Schema({ const mvcSchema: Schema = new Schema({
projectId: { type: Schema.Types.ObjectId, ref: "Project" }, projectId: { type: Schema.Types.ObjectId, ref: "Project" },
controllers: { type: Boolean }, controllers: { type: Boolean },
routes: { type: Boolean }, routes: { type: Boolean },
models: { type: Boolean }, models: { type: Boolean },
services: { type: Boolean }, services: { type: Boolean },
middleware: { type: Boolean }, middleware: { type: Boolean },
utils: { type: Boolean }, utils: { type: Boolean },
config: { type: Boolean }, config: { type: Boolean },
folders: [folderSchema], folders: [folderSchema],
}); });
const MVCarcModel = (db: any) => { const MVCarcModel = (db: any) => {
return MainModel(db, "MVC", mvcSchema, "MVC"); return MainModel(db, "MVC", mvcSchema, "MVC");
}; };
export default MVCarcModel; export default MVCarcModel;

View File

@@ -1,43 +1,43 @@
import { Schema, Document } from "mongoose"; import { Schema, Document } from "mongoose";
import MainModel from "../connection/connection"; import MainModel from "../connection/connection";
export interface IProject extends Document { export interface IProject extends Document {
projectName: string; projectName: string;
appType: string; appType: string;
slug: string; slug: string;
isArchive: boolean; isArchive: boolean;
createdBy: string; createdBy: string;
description: string; description: string;
members: [string]; members: [string];
useableLanguage: string; useableLanguage: string;
typeOfDB: string; typeOfDB: string;
DBName: string; DBName: string;
architecture: string; architecture: string;
apiType: string; apiType: string;
} }
const projectSchema: Schema = new Schema( const projectSchema: Schema = new Schema(
{ {
projectName: { type: String }, projectName: { type: String },
appType:{type:String,enum:["Backend","Frontend"]}, appType:{type:String,enum:["Backend","Frontend"]},
slug: { type: String }, slug: { type: String },
isArchive: { type: Boolean, default: false }, isArchive: { type: Boolean, default: false },
createdBy: { type: String }, createdBy: { type: String },
description: { type: String }, description: { type: String },
DBName: { type: String }, DBName: { type: String },
typeOfDB: { type: String }, typeOfDB: { type: String },
useableLanguage: { type: String }, useableLanguage: { type: String },
architecture: { type: String }, architecture: { type: String },
apiType: { apiType: {
type: String, type: String,
enum: ["RESTful", "SOAP", "GraphQL", "RPC", "WebSocket"], enum: ["RESTful", "SOAP", "GraphQL", "RPC", "WebSocket"],
}, },
members: { type: [String] }, members: { type: [String] },
}, },
{ {
timestamps: true, timestamps: true,
} }
); );
const ProjectType = (db: any) => { const ProjectType = (db: any) => {
return MainModel(db, "Project", projectSchema, "Project"); return MainModel(db, "Project", projectSchema, "Project");
}; };
export default ProjectType; export default ProjectType;

File diff suppressed because it is too large Load Diff

View File

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

View File

@@ -1,185 +1,185 @@
import MVCarcModel from "../../shared/model/mvcModel"; import MVCarcModel from "../../shared/model/mvcModel";
import ProjectType from "../../shared/model/projectmodel"; import ProjectType from "../../shared/model/projectmodel";
import collectionsModel from "../model/collectionModel"; import collectionsModel from "../model/collectionModel";
import edgeModel from "../model/edgeModel"; import edgeModel from "../model/edgeModel";
interface Iresponse { interface Iresponse {
status: string; status: string;
data?: any; data?: any;
} }
interface IProject { interface IProject {
useableLanguage: string; useableLanguage: string;
organization: string; organization: string;
projectName: string; projectName: string;
userName: string; userName: string;
apiType: string; apiType: string;
application: string; application: string;
architecture: string; architecture: string;
description: string; description: string;
} }
interface IProjectstructure { interface IProjectstructure {
projectId: string; projectId: string;
organization: string; organization: string;
} }
export const projectCreationService = async ( export const projectCreationService = async (
data: IProject data: IProject
): Promise<Iresponse> => { ): Promise<Iresponse> => {
const { const {
organization, organization,
projectName, projectName,
useableLanguage, useableLanguage,
description, description,
userName, userName,
apiType, apiType,
application, application,
architecture, architecture,
} = data; } = data;
try { try {
const existingProject = await ProjectType(organization).findOne({ const existingProject = await ProjectType(organization).findOne({
projectName: projectName, projectName: projectName,
createdBy: userName, createdBy: userName,
isArchive: false, isArchive: false,
}); });
if (existingProject) { if (existingProject) {
return { status: "Project Already Exists" }; return { status: "Project Already Exists" };
} else { } else {
if (architecture.toLowerCase() === "mvc") { if (architecture.toLowerCase() === "mvc") {
const newProject = await ProjectType(organization).create({ const newProject = await ProjectType(organization).create({
projectName, projectName,
createdBy: userName, createdBy: userName,
useableLanguage, useableLanguage,
architecture, architecture,
apiType: apiType, apiType: apiType,
appType: application, appType: application,
description, description,
}); });
if (!newProject) return { status: "Project creation unsuccessfull" }; if (!newProject) return { status: "Project creation unsuccessfull" };
const existingProjectinMVC = await MVCarcModel(organization).findOne({ const existingProjectinMVC = await MVCarcModel(organization).findOne({
projectId: newProject._id, projectId: newProject._id,
isArchive: false, isArchive: false,
}); });
if (!existingProjectinMVC) { if (!existingProjectinMVC) {
const MVCCreation = await MVCarcModel(organization).create({ const MVCCreation = await MVCarcModel(organization).create({
projectId: newProject._id, projectId: newProject._id,
createdBy: userName, createdBy: userName,
controllers: true, controllers: true,
routes: true, routes: true,
models: true, models: true,
services: true, services: true,
middleware: true, middleware: true,
utils: true, utils: true,
config: true, config: true,
}); });
const mvcData = MVCCreation.toObject(); const mvcData = MVCCreation.toObject();
const excludedKeys = [ const excludedKeys = [
"projectId", "projectId",
"_id", "_id",
"__v", "__v",
"createdBy", "createdBy",
"isArchive", "isArchive",
"folders", "folders",
]; ];
const folders = Object.keys(mvcData).filter( const folders = Object.keys(mvcData).filter(
(key) => !excludedKeys.includes(key) && mvcData[key] === true (key) => !excludedKeys.includes(key) && mvcData[key] === true
); );
const createdFolders = folders.map((folderName) => ({ const createdFolders = folders.map((folderName) => ({
folderName, folderName,
createdAt: new Date(), createdAt: new Date(),
})); }));
MVCCreation.folders.push(...createdFolders); MVCCreation.folders.push(...createdFolders);
await MVCCreation.save(); await MVCCreation.save();
return { status: "Success", data: newProject._id }; return { status: "Success", data: newProject._id };
} else { } else {
return { return {
status: "Already MVC architecture assigned to this projectId", status: "Already MVC architecture assigned to this projectId",
}; };
} }
} else { } else {
return { status: "New architecture" }; return { status: "New architecture" };
} }
} }
} catch (error: unknown) { } catch (error: unknown) {
if (error instanceof Error) { if (error instanceof Error) {
return { return {
status: error.message, status: error.message,
}; };
} else { } else {
return { return {
status: "An unexpected error occurred", status: "An unexpected error occurred",
}; };
} }
} }
}; };
export const projectDatas = async (data: IProject): Promise<Iresponse> => { export const projectDatas = async (data: IProject): Promise<Iresponse> => {
const { organization } = data; const { organization } = data;
try { try {
const projectDatas = await ProjectType(organization) const projectDatas = await ProjectType(organization)
.findOne({ .findOne({
isArchive: false, isArchive: false,
}) })
.select("-__v -isArchive -createdAt -updatedAt"); .select("-__v -isArchive -createdAt -updatedAt");
if (!projectDatas) return { status: "No project found" }; if (!projectDatas) return { status: "No project found" };
return { status: "Success", data: projectDatas }; return { status: "Success", data: projectDatas };
} catch (error: unknown) { } catch (error: unknown) {
if (error instanceof Error) { if (error instanceof Error) {
return { return {
status: error.message, status: error.message,
}; };
} else { } else {
return { return {
status: "An unexpected error occurred", status: "An unexpected error occurred",
}; };
} }
} }
}; };
export const GetNodesInProject = async ( export const GetNodesInProject = async (
data: IProjectstructure data: IProjectstructure
): Promise<Iresponse> => { ): Promise<Iresponse> => {
const { organization, projectId } = data; const { organization, projectId } = data;
try { try {
const existingProject = await ProjectType(organization).findOne({ const existingProject = await ProjectType(organization).findOne({
_id: projectId, _id: projectId,
isArchive: false, isArchive: false,
}); });
if (!existingProject) { if (!existingProject) {
return { status: "project not found" }; return { status: "project not found" };
} else { } else {
const collectionNodesdata = await collectionsModel(organization) const collectionNodesdata = await collectionsModel(organization)
.find({ projectId: projectId, isArchive: false }) .find({ projectId: projectId, isArchive: false })
.select("collectionNodeName attributes position -_id "); .select("collectionNodeName attributes position -_id ");
const edgeNodes = await edgeModel(organization) const edgeNodes = await edgeModel(organization)
.find({ projectId: projectId, isArchive: false }) .find({ projectId: projectId, isArchive: false })
.select("cardinality from to"); .select("cardinality from to");
if(!edgeNodes) return {status:'No edge Nodes present',data:[]} if(!edgeNodes) return {status:'No edge Nodes present',data:[]}
if (!collectionNodesdata) if (!collectionNodesdata)
return { status: "No collection Nodes present", data: [] }; return { status: "No collection Nodes present", data: [] };
else { else {
const collectionNodes = collectionNodesdata.map((collection) => ({ const collectionNodes = collectionNodesdata.map((collection) => ({
position: collection.position, position: collection.position,
collectionNodeName: collection.collectionNodeName, collectionNodeName: collection.collectionNodeName,
attributes: collection.attributes attributes: collection.attributes
.filter((attr: any) => !attr.isArchive) .filter((attr: any) => !attr.isArchive)
.map((attr: any) => { .map((attr: any) => {
const { isArchive, ...rest } = attr.toObject(); const { isArchive, ...rest } = attr.toObject();
return { ...rest,edgeNodes }; return { ...rest,edgeNodes };
}), }),
})); }));
return { status: "Success", data: {collectionNodes,edgeNodes} }; return { status: "Success", data: {collectionNodes,edgeNodes} };
} }
} }
} catch (error: unknown) { } catch (error: unknown) {
if (error instanceof Error) { if (error instanceof Error) {
return { return {
status: error.message, status: error.message,
}; };
} else { } else {
return { return {
status: "An unexpected error occurred", status: "An unexpected error occurred",
}; };
} }
} }
}; };