Skip to content

Commit

Permalink
Merge pull request #28 from ozkeisar/build-server-from-swagger
Browse files Browse the repository at this point in the history
Build server from swagger
  • Loading branch information
ozkeisar authored Sep 26, 2024
2 parents 1c57945 + 3a80106 commit d8611e1
Show file tree
Hide file tree
Showing 30 changed files with 1,052 additions and 256 deletions.
1 change: 1 addition & 0 deletions assets/svg/Swagger.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
58 changes: 58 additions & 0 deletions src/backend/actions/parents.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { RouteParent } from "../../types";
import { EVENT_KEYS } from "../../types/events";
import { isParentExist, parentsProperties } from "../../utils/parent";
import { projectsManager } from "../managers";
import { emitGlobalSocketMessage } from "../socket";
import { hasUncommittedChanges, updateRouteParentFile } from "../utils";


export const createParent = async (projectName: string, serverName: string, parent: RouteParent)=>{

const serversHash = await projectsManager.getProjectServersHash(projectName)
const server = serversHash[serverName]

if(!server){
throw new Error("server not exist");
}

const {
filenames,
paths,
graphQlNames,
restPaths,
graphQlPaths
} = parentsProperties(server)


const {
parentExist,
} = isParentExist(server, {
filenames,
paths,
graphQlNames,
restPaths,
graphQlPaths
}, parent)

if(parentExist){
throw new Error("parent already exist");
}

await updateRouteParentFile(projectName, serverName, parent);

projectsManager.setProjectChanged(projectName)

const hasDiffs = await hasUncommittedChanges(projectName);

emitGlobalSocketMessage(EVENT_KEYS.UPDATE_ROUTES_FILE, {
success: true,
content: parent,
filename: parent.filename,
projectName,
serverName,
hasDiffs,
});

return parent

}
54 changes: 54 additions & 0 deletions src/backend/actions/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { Route } from "../../types";
import { EVENT_KEYS } from "../../types/events";
import { isRouteExist } from "../../utils/route";
import { projectsManager } from "../managers";
import { emitGlobalSocketMessage } from "../socket";
import { hasUncommittedChanges, updateRouteParentFile } from "../utils";


export const createRoute = async(projectName: string, serverName: string, parentId: string, route: Route)=>{

const serverHash = await projectsManager.getProjectServersHash(projectName);
const server = serverHash[serverName]

if(!server){
throw new Error("server not exist");
}

const parent = server.parentRoutesHash[parentId]

if(!parent){
throw new Error("parent not exist");
}

const routeExist = isRouteExist(route, parent)

if(routeExist){
throw new Error("route already exist");
}

if(parent.routesHash){
parent.routesHash[route.id] = route
}else{
parent.routesHash = {
[route.id]: route
}
}

await updateRouteParentFile(projectName, serverName, parent);

projectsManager.setProjectChanged(projectName)

const hasDiffs = await hasUncommittedChanges(projectName);

emitGlobalSocketMessage(EVENT_KEYS.UPDATE_ROUTES_FILE, {
success: true,
content: parent,
filename: parent.filename,
projectName,
serverName,
hasDiffs,
});

return route
}
62 changes: 13 additions & 49 deletions src/backend/managers/projectsManager.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// import chokidar from 'chokidar';
import path from 'path';
import { SUPPORTED_PROJECT_DATA_VERSION } from '../../consts';
import {
Expand All @@ -8,7 +7,7 @@ import {
} from '../utils/files';
import { migrateProjectData } from '../utils/migrations';
import { listToHashmap } from '../utils/utils';
import { ProjectDataNew } from '../../types';
import { ProjectDataNew, ServersHash } from '../../types';
import {
isGitRepository,
getBranches,
Expand All @@ -19,14 +18,19 @@ import { getProjectServers, isFirstVersionGreater } from '../utils/general';
// import { socketIo } from "../app";

class ProjectsManager {
private projectChange: {
[key: string]: boolean
} = {};

private projects: {
[key: string]: ProjectDataNew;
} = {};

// constructor() {}

public async getProjectServersHash(projectName: string) {
public async getProjectServersHash(projectName: string): Promise<ServersHash> {
await this.loadProject(projectName);

return this.projects[projectName].serversHash;
}

Expand All @@ -45,57 +49,17 @@ class ProjectsManager {
return this.projects[projectName];
}

private handleProjectDataChanged(
projectName: string,
changeType: string,
itemPath: string,
): void {
const relativePath = path.relative(process.cwd(), itemPath);
console.log(`changes in: ${projectName} :${changeType}: ${relativePath}`);
this.readProjectData(projectName);
// socketIo.emit('reload', {projectName});
}

// eslint-disable-next-line class-methods-use-this
private async watchProjectFolder(projectName: string) {
const projectPath = await getProjectPath(projectName);

// const watcher = chokidar.watch(projectPath, {
// eslint-disable-next-line no-useless-escape
// ignored: /(^|[\/\\])\.git/,
// persistent: true,
// ignoreInitial: true,
// depth: 99, // Adjust depth as needed
// });

// watcher
// .on('add', (filePath) =>
// this.handleProjectDataChanged(projectName, 'File added', filePath),
// .on('change', (filePath) =>
// this.handleProjectDataChanged(projectName, 'File changed', filePath),
// .on('unlink', (filePath) =>
// this.handleProjectDataChanged(projectName, 'File removed', filePath),
// .on('addDir', (dirPath) =>
// this.handleProjectDataChanged(projectName, 'Directory added', dirPath),
// .on('unlinkDir', (dirPath) =>
// this.handleProjectDataChanged(
// projectName,
// 'Directory removed',
// dirPath,
// ),
// )
// .on('error', (error) => console.error('Error watching files:', error));

console.log(`---Watching changes for ${projectName} in: ${projectPath}`);
public setProjectChanged(projectName: string){
this.projectChange[projectName] = true;
}


private async loadProject(projectName: string) {
if (this.projects[projectName]) {
if (this.projects[projectName] && !this.projectChange[projectName]) {
console.log('project already loaded');
} else {
await this.readProjectData(projectName);
await this.watchProjectFolder(projectName);
}
}
}

private async readProjectData(projectName: string): Promise<void> {
Expand Down Expand Up @@ -141,7 +105,7 @@ class ProjectsManager {
} catch (error) {
this.projects[projectName] = {
presetFoldersHash: null,
serversHash: null,
serversHash: {},
settings: null,
name: projectName,
isDataUnsupported: false,
Expand Down
44 changes: 44 additions & 0 deletions src/backend/routers/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import {
handleRestartServer,
handleStartServer,
} from '../actions';
import { addRoutesFromSwaggerJson, addRoutesFromSwaggerUrl } from '../utils';
import { checkIServerUp } from '../server';

const serverRouter = Router();

Expand Down Expand Up @@ -100,4 +102,46 @@ serverRouter.post('/restart', async (req: Request, res: Response) => {
}
});



serverRouter.post('/load-swagger', async (req: Request, res: Response) => {
try {
const { projectName, serverName, type, swaggerUrl, swaggerJson } = req.body as {
projectName: string,
serverName: string,
type: 'json' | 'url',
swaggerUrl: string,
swaggerJson: any
};

const iServerUp = checkIServerUp()
/// check if server is running
if(iServerUp){
handleCloseServer();
}

logger('start load from swagger', { projectName, serverName });

if(type === 'url'){
await addRoutesFromSwaggerUrl(projectName, serverName, swaggerUrl)
} else if(type === 'json'){
await addRoutesFromSwaggerJson(projectName, serverName, JSON.parse(swaggerJson))
}else {
throw new Error("type must be type 'url' | 'json' ");
}

/// check if server was running
if(iServerUp){
await handleStartServer(projectName);
}

res.status(200).send({ success: true });
} catch (error: any) {
console.log(error);
logger('Error load from swagger', error?.message);

res.status(500).send({ success: false, message: error?.message || 'fail to load from swagger' });
}
});

export { serverRouter };
39 changes: 39 additions & 0 deletions src/backend/swagger_output.json
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,45 @@
}
}
},
"/servers/load-swagger": {
"post": {
"description": "",
"responses": {
"200": {
"description": "OK"
},
"500": {
"description": "Internal Server Error"
}
},
"requestBody": {
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"projectName": {
"example": "any"
},
"serverName": {
"example": "any"
},
"type": {
"example": "any"
},
"swaggerUrl": {
"example": "any"
},
"swaggerJson": {
"example": "any"
}
}
}
}
}
}
}
},
"/parents/{projectName}/{serverName}/{parentId}": {
"get": {
"description": "",
Expand Down
1 change: 1 addition & 0 deletions src/backend/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ export * from './events';
export * from './files';
export * from './git';
export * from './general';
export * from './swaggerBuilder'
Loading

0 comments on commit d8611e1

Please sign in to comment.