Project create APi and collection create API completed

This commit is contained in:
2025-08-26 15:30:50 +05:30
parent 3c93c1b3b4
commit eec6f8feed
16 changed files with 402 additions and 333 deletions

4
.env
View File

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

18
src/api-server/app.ts Normal file
View File

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

View File

@@ -0,0 +1,51 @@
import { Request, Response } from "express";
import { collectionNodecreation } from "../../shared/services/collectionService";
export const collectionNodeCreationController = async (
req: Request,
res: Response
): Promise<void> => {
try {
const { organization, projectId, position } = req.body;
if (!organization || !projectId || !position) {
res.status(400).json({
message: "All fields are required",
});
return;
}
const data = {
organization,
projectId,
position,
};
const result = await collectionNodecreation(data);
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",
});
}
};

View File

@@ -1,302 +0,0 @@
import fs from "node:fs";
import { Request, Response } from "express";
import path from "path";
import MVCarcModel from "../../shared/model/mvcModel";
import ProjectType from "../../shared/model/projectmodel";
export const createcontroller = async (
req: Request,
res: Response
): Promise<any> => {
const {
pathName,
organization,
BaseName,
useableLanguage,
typeOfDB,
DBName,
userName,
architecture,
} = req.body;
try {
const existing = await ProjectType(organization).findOne({
createdBy: userName,
DBName: DBName,
typeOfDB: typeOfDB,
useableLanguage: useableLanguage,
architecture: architecture.toLowerCase(),
});
if (existing) {
return res.status(403).json({
message: "Project Already Exists",
});
} else {
if (architecture.toLowerCase() === "mvc") {
const basePath = path.join(pathName, BaseName, "src");
let folders: any[];
const existingMvcForBase = await MVCarcModel(organization).findOne({
BaseName: BaseName,
architecture: architecture.toLowerCase(),
});
if (!existingMvcForBase) {
const getUniqueBasePath = (
pathName: string,
BaseName: string
): { finalBaseName: string; fullPath: string } => {
let counter = 0;
let newBaseName = BaseName;
let fullPath = path.join(pathName, newBaseName, "src");
if (fs.existsSync(basePath)) {
counter++;
newBaseName = `${BaseName}-${counter}`;
fullPath = path.join(pathName, newBaseName, "src");
}
return { finalBaseName: newBaseName, fullPath };
};
const folderStructureFunction = async (
folders: string[],
rootPath: string
): Promise<any> => {
const folderStatus: string[] = [];
for (const folder of folders) {
const fullPath = path.join(rootPath, folder);
if (!fs.existsSync(fullPath)) {
fs.mkdirSync(fullPath, { recursive: true });
folderStatus.push(`Created: ${folder}`);
console.log("folder: ", folder);
BaseDataSave.folderNames.push(folder);
await BaseDataSave.save();
} else {
folderStatus.push(`Already exists: ${folder}`);
}
}
return folderStatus;
};
const mainFileCreate = async (rootPath: string): Promise<any> => {
const mainfile = path.join(rootPath, "app.ts");
try {
await fs.promises.access(rootPath);
} catch {
await fs.promises.mkdir(rootPath, { recursive: true });
}
try {
await fs.promises.access(mainfile);
return res
.status(200)
.json({ message: "Model file already exists in this name" });
} catch {
await fs.promises.writeFile(mainfile, "");
}
};
let folderStatus: string[] = [];
let basicName: string;
let rootPath: string;
if (fs.existsSync(basePath)) {
let { finalBaseName, fullPath } = getUniqueBasePath(
pathName,
BaseName
);
basicName = finalBaseName;
rootPath = fullPath;
fs.mkdirSync(fullPath, { recursive: true });
mainFileCreate(rootPath);
} else {
basicName = BaseName;
rootPath = basePath;
fs.mkdirSync(basePath, { recursive: true });
mainFileCreate(rootPath);
}
let BaseDataSave = await ProjectType(organization).create({
organization,
BaseName: basicName,
useableLanguage,
typeOfDB,
DBName,
createdBy: userName,
architecture: architecture.toLowerCase(),
});
const MVCCreation = await MVCarcModel(organization).create({
BaseName: basicName,
baseId: BaseDataSave._id,
createdBy: userName,
controllers: true,
routes: true,
models: true,
services: true,
middleware: true,
utils: true,
config: true,
});
const mvcData = MVCCreation.toObject();
const excludedKeys = ["baseId", "_id", "__v"];
const folders = Object.keys(mvcData).filter(
(key) => !excludedKeys.includes(key) && mvcData[key] === true
);
folderStatus = await folderStructureFunction(folders, rootPath);
return res.status(201).json({
message: "Base structure created successfully",
folderStatus,
});
}
} else {
console.log("New Architecture flow");
}
}
} catch (error: unknown) {
res.send("error");
}
};
// export const createcontroller = async (
// req: Request,
// res: Response
// ): Promise<any> => {
// const {
// pathName,
// organization,
// BaseName,
// useableLanguage,
// typeOfDB,
// DBName,
// userName,
// architecture,
// } = req.body;
// try {
// const existing = await ProjectType(organization).findOne({
// createdBy: userName,
// DBName: DBName,
// typeOfDB: typeOfDB,
// useableLanguage: useableLanguage,
// architecture: architecture.toLowerCase(),
// });
// if (existing) {
// return res.status(403).json({
// message: "Project Already Exists",
// });
// } else {
// if (architecture.toLowerCase() === "mvc") {
// const basePath = path.join(pathName, BaseName, "src");
// let folders: any[];
// const existingMvcForBase = await MVCarcModel(organization).findOne({
// BaseName: BaseName,
// architecture: architecture.toLowerCase(),
// });
// if (!existingMvcForBase) {
// const getUniqueBasePath = (
// pathName: string,
// BaseName: string
// ): { finalBaseName: string; fullPath: string } => {
// let counter = 0;
// let newBaseName = BaseName;
// let fullPath = path.join(pathName, newBaseName, "src");
// if (fs.existsSync(basePath)) {
// counter++;
// newBaseName = `${BaseName}-${counter}`;
// fullPath = path.join(pathName, newBaseName, "src");
// }
// return { finalBaseName: newBaseName, fullPath };
// };
// const folderStructureFunction = async (
// folders: string[],
// rootPath: string
// ): Promise<any> => {
// const folderStatus: string[] = [];
// for (const folder of folders) {
// const fullPath = path.join(rootPath, folder);
// if (!fs.existsSync(fullPath)) {
// fs.mkdirSync(fullPath, { recursive: true });
// folderStatus.push(`Created: ${folder}`);
// console.log("folder: ", folder);
// BaseDataSave.folderNames.push(folder);
// await BaseDataSave.save();
// } else {
// folderStatus.push(`Already exists: ${folder}`);
// }
// }
// return folderStatus;
// };
// const mainFileCreate = async (rootPath: string): Promise<any> => {
// const mainfile = path.join(rootPath, "app.ts");
// try {
// await fs.promises.access(rootPath);
// } catch {
// await fs.promises.mkdir(rootPath, { recursive: true });
// }
// try {
// await fs.promises.access(mainfile);
// return res
// .status(200)
// .json({ message: "Model file already exists in this name" });
// } catch {
// await fs.promises.writeFile(mainfile, "");
// }
// };
// let folderStatus: string[] = [];
// let basicName: string;
// let rootPath: string;
// if (fs.existsSync(basePath)) {
// let { finalBaseName, fullPath } = getUniqueBasePath(
// pathName,
// BaseName
// );
// basicName = finalBaseName;
// rootPath = fullPath;
// fs.mkdirSync(fullPath, { recursive: true });
// mainFileCreate(rootPath);
// } else {
// basicName = BaseName;
// rootPath = basePath;
// fs.mkdirSync(basePath, { recursive: true });
// mainFileCreate(rootPath);
// }
// let BaseDataSave = await ProjectType(organization).create({
// organization,
// BaseName: basicName,
// useableLanguage,
// typeOfDB,
// DBName,
// createdBy: userName,
// architecture: architecture.toLowerCase(),
// });
// const MVCCreation = await MVCarcModel(organization).create({
// BaseName: basicName,
// baseId: BaseDataSave._id,
// createdBy: userName,
// controllers: true,
// routes: true,
// models: true,
// services: true,
// middleware: true,
// utils: true,
// config: true,
// });
// const mvcData = MVCCreation.toObject();
// const excludedKeys = [
// "baseId",
// "_id",
// "__v",
// ];
// const folders = Object.keys(mvcData).filter(
// (key) => !excludedKeys.includes(key) && mvcData[key] === true
// );
// folderStatus = await folderStructureFunction(folders, rootPath);
// return res.status(201).json({
// message: "Base structure created successfully",
// folderStatus,
// });
// }
// } else {
// console.log("New Architecture flow");
// }
// }
// } catch (error: unknown) {
// res.send("error");
// }
// };

View File

@@ -0,0 +1,120 @@
import { Request, Response } from "express";
import {
projectCreationService,
projectDatas,
} from "../../shared/services/projectService";
export const projectCreationController = async (
req: Request,
res: Response
): Promise<void> => {
try {
const {
organization,
useableLanguage,
projectName,
userName,
apiType,
architecture,
description,
} = req.body;
if (
!organization ||
!useableLanguage ||
!projectName ||
!userName ||
!apiType ||
!architecture
) {
res.status(400).json({
message: "All fields are required",
});
return;
}
const data = {
organization,
projectName,
useableLanguage,
description,
userName,
apiType,
architecture,
};
const result = await projectCreationService(data);
switch (result.status) {
case "Project Already Exists":
res.status(403).json({
message: "Project Already Exists",
});
break;
case "Already MVC architecture assigned to this projectId":
res.status(403).json({
message: "Already MVC architecture assigned to this projectId",
});
break;
case "Project creation unsuccessfull":
res.status(200).json({
message: "Project creation unsuccessfull",
});
break;
case "Success":
res.status(200).json({
message: "Project created successfully",
projectId: result.data,
});
break;
case "New architecture":
res.status(200).json({
message: "New architecture",
});
break;
default:
res.status(500).json({
message: "Internal server error",
});
break;
}
} catch (error) {
res.status(500).json({
message: "Unknown error",
});
}
};
export const getProjects = async (
req: Request,
res: Response
): Promise<void> => {
try {
const { organization } = req.body;
if (!organization) {
res.status(400).json({
message: "All fields are required",
});
return;
}
const result = await projectDatas(organization);
switch (result.status) {
case "No project found":
res.status(200).json({});
break;
case "Success":
res.status(200).json({
message: "Project created successfully",
projectDatas: result.data,
});
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,5 @@
import express from "express";
const app = express();
import appRoutes from "../api-server/routes/routes";
import bodyParser from "body-parser";
import cors from "cors";
app.use(bodyParser.json());
app.use(cors());
app.use(appRoutes);
const port = 9696;
import app from "./app";
const port = process.env.API_PORT;
app.listen(port, () => {
console.log(`Port is running on the ${port}`);
});

View File

@@ -0,0 +1,7 @@
import express from "express";
import { collectionNodeCreationController } from "../controller/collectionNodeController";
collectionNodeCreationController;
const collectionNodeRoutes = express.Router();
collectionNodeRoutes.post("/NewNode", collectionNodeCreationController);
export default collectionNodeRoutes;

View File

@@ -0,0 +1,8 @@
import express from "express";
import { projectCreationController } from "../controller/projectController";
const projectRoutes = express.Router();
projectRoutes.post("/Newproject", projectCreationController);
// appRoutes.post("/createfileModel", fileModelCreatecontroller);
export default projectRoutes;

View File

@@ -1,8 +0,0 @@
import express from "express";
import { createcontroller } from "../../api-server/controller/controller";
import { fileModelCreatecontroller } from "../../api-server/controller/fileModelController";
const appRoutes = express.Router();
appRoutes.post("/createfolder", createcontroller);
appRoutes.post("/createfileModel", fileModelCreatecontroller);
export default appRoutes

View File

@@ -13,6 +13,7 @@ const MainModel = <T>(
collectionName: string
): Model<T> => {
const db1_url = `${process.env.MONGO_URI}${db}`;
console.log('process.env.MONGO_URI: ', process.env.MONGO_URI);
const authOptions = {
user: process.env.MONGO_USER,
pass: process.env.MONGO_PASSWORD,

View File

View File

@@ -1,22 +1,23 @@
import { Schema, Document } from "mongoose";
import MainModel from "../connection/connection";
import { IProject } from "./projectmodel";
interface IFileModel extends Document {
interface ICollectionNode extends Document {
projectId: IProject["_id"];
collectionNodeName: string;
attributes: [];
createdAt: number;
isArchive: boolean;
position: [number, number, number];
}
const collectionSchema: Schema<IFileModel> = new Schema({
const collectionSchema: Schema<ICollectionNode> = new Schema({
projectId: { type: Schema.Types.ObjectId, ref: "Project" },
collectionNodeName: { type: String, required: true },
position: { type: [Number], required: true },
isArchive: { type: Boolean, default: false },
attributes: { type: [], required: true },
createdAt: { type: Number, default: Date.now() },
});
},
{
timestamps: true,
});
const collectionsModel = (db: any) => {
return MainModel(db, "collectionNode", collectionSchema, "collectionNode");

View File

@@ -5,13 +5,10 @@ interface Ifolders extends Document {
folderName: string;
createdAt: number;
}
const folderSchema: Schema = new Schema(
{
folderName: { type: String, required: true },
createdAt: { type: Date, default: Date.now },
},
{ _id: false }
);
const folderSchema: Schema = new Schema({
folderName: { type: String, required: true },
createdAt: { type: Date, default: Date.now },
});
export interface IMVCPrject extends Document {
projectId: IProject["_id"];
controllers: boolean;
@@ -36,6 +33,6 @@ const mvcSchema: Schema = new Schema({
});
const MVCarcModel = (db: any) => {
return MainModel(db, "MVCArc", mvcSchema, "MVCArc");
return MainModel(db, "MVC", mvcSchema, "MVC");
};
export default MVCarcModel;

View File

@@ -11,6 +11,7 @@ export interface IProject extends Document {
typeOfDB: string;
DBName: string;
architecture: string;
apiType: string;
}
const projectSchema: Schema = new Schema(
{
@@ -23,6 +24,10 @@ const projectSchema: Schema = new Schema(
typeOfDB: { type: String },
useableLanguage: { type: String },
architecture: { type: String },
apiType: {
type: String,
enum: ["RESTful", "SOAP", "GraphQL", "RPC", "WebSocket"],
},
members: { type: [String] },
},
{

View File

@@ -0,0 +1,45 @@
import ProjectType from "../../shared/model/projectmodel";
import collectionsModel from "../model/collectionModel";
interface Iresponse {
status: string;
data?: any;
}
interface IcollectionNode {
projectId: string;
organization: string;
position: [number];
}
export const collectionNodecreation = async (
data: IcollectionNode
): Promise<Iresponse> => {
const { organization, projectId, position } = data;
try {
const existingProject = await ProjectType(organization).findOne({
_id: projectId,
// createdBy: userName,
isArchive: false,
});
if (!existingProject) {
return { status: "project not found" };
} else {
const newCollectionnode = await collectionsModel(organization).create({
projectId: projectId,
isArchive: false,
position: position,
});
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",
};
}
}
};

View File

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