diff --git a/package.json b/package.json index fdd3286a4..aa748f6cf 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "staart-manager", - "version": "1.0.103", + "version": "1.0.104", "main": "index.js", "repository": "git@github.com:AnandChowdhary/staart.git", "author": "Anand Chowdhary ", @@ -135,5 +135,5 @@ "setup" ], "snyk": true, - "staart-version": "1.0.103" + "staart-version": "1.0.104" } \ No newline at end of file diff --git a/setup/controllers.js b/setup/controllers.js index e3b1e09cc..2981f414f 100644 --- a/setup/controllers.js +++ b/setup/controllers.js @@ -6,93 +6,118 @@ const recursive = require("recursive-readdir"); const SRC = path.join(__dirname, "..", "src"); let server = fs.readFileSync(path.join(SRC, "server.ts")).toString(); -// Controller routes -const controllers = fs.readdirSync(path.join(SRC, "controllers")); -const exportName = []; -controllers.forEach(controller => { - const controllerFile = fs - .readFileSync(path.join(SRC, "controllers", controller)) - .toString(); - exportName.push(controllerFile.split("export class ")[1].split(" ")[0]); -}); -const importCode = `${exportName - .map( - (e, i) => - `import { ${e} } from "./controllers/${controllers[i].split(".ts")[0]}";` - ) - .join("\n")}`; -const insertCode = ` - // start automatic code - super.addControllers([${exportName.map(e => `new ${e}()`).join(", ")}]); - // staart-autogenerated -`; -server = importCode + server.replace("// staart:setup/controllers", insertCode); -console.log("✅ Generated paths"); - -// Redirects -let redirects = []; -try { - redirects = yaml.parse( - fs.readFileSync(path.join(SRC, "redirects.yml")).toString() +const generateControllers = async () => { + const controllers = (await recursive(path.join(SRC, "controllers"))).map( + file => file.split(path.join(SRC, "controllers").toString())[1] ); -} catch (error) { - console.log("✅ Processed no redirect rules"); -} -const redirectCode = ` - ${redirects + const exportName = []; + const generatedName = []; + controllers.forEach((controller, index) => { + const controllerFile = fs + .readFileSync(path.join(SRC, "controllers", controller)) + .toString(); + exportName.push(controllerFile.split("export class ")[1].split(" ")[0]); + generatedName.push(`Controller${index}`); + }); + const importCode = `${exportName .map( - rule => ` - this.app.get("${rule.split(" ")[0]}", (req, res) => res.redirect("${ - rule.split(" ")[1] - }")); - ` + (e, i) => + `import { ${e} as ${generatedName[i]} } from "./controllers${ + controllers[i].split(".ts")[0] + }";` ) - .join("")} + .join("\n")}`; + const insertCode = ` + // start automatic code + super.addControllers([${generatedName.map(e => `new ${e}()`).join(", ")}]); // staart-autogenerated -`; -server = server.replace("// staart-autogenerated", redirectCode); -if (redirects.length) - console.log(`✅ Processed ${redirects.length} redirect rules`); + `; + server = + importCode + server.replace("// staart:setup/controllers", insertCode); + console.log("✅ Generated paths"); +}; -// Cron jobs -const crons = fs.readdirSync(path.join(SRC, "crons")); -const cronImport = crons - .map( - cronFile => - `import cron_${cronFile.split(".ts")[0]} from "./crons/${ - cronFile.split(".ts")[0] - }";` - ) - .join("\n"); -const cronCode = ` -${crons.map(cronFile => `cron_${cronFile.split(".ts")[0]}();`)} -`; -server = cronImport + "\n" + cronCode + "\n" + server; -if (crons.length) console.log(`✅ Setup ${crons.length} cron jobs`); - -// Static files -recursive(path.join(SRC, "..", "static")) - .then(files => { - const staticFiles = files.map( - file => file.split(path.join(SRC, "..", "static").toString())[1] +const generateRedirects = async () => { + let redirects = []; + try { + redirects = yaml.parse( + fs.readFileSync(path.join(SRC, "redirects.yml")).toString() ); - const staticCode = ` - ${staticFiles - .map( - staticFile => ` - this.app.get("${staticFile}", (req, res) => res.sendFile(join(__dirname, "..", "static", "${staticFile}"))); - ` - ) - .join("")} - // staart-autogenerated - `; - server = server.replace("// staart-autogenerated", staticCode); - console.log(`✅ Serving ${staticFiles.length} static files`); - }) - .catch(() => {}) + } catch (error) { + console.log("✅ Processed no redirect rules"); + } + const redirectCode = ` + ${redirects + .map( + rule => ` + this.app.get("${rule.split(" ")[0]}", (req, res) => res.redirect("${ + rule.split(" ")[1] + }")); + ` + ) + .join("")} + // staart-autogenerated + `; + server = server.replace("// staart-autogenerated", redirectCode); + if (redirects.length) + console.log(`✅ Processed ${redirects.length} redirect rules`); +}; + +const generateCrons = async () => { + const crons = fs.readdirSync(path.join(SRC, "crons")); + const cronImport = crons + .map( + cronFile => + `import cron_${cronFile.split(".ts")[0]} from "./crons/${ + cronFile.split(".ts")[0] + }";` + ) + .join("\n"); + const cronCode = ` + ${crons.map(cronFile => `cron_${cronFile.split(".ts")[0]}();`)} + `; + server = cronImport + "\n" + cronCode + "\n" + server; + if (crons.length) console.log(`✅ Setup ${crons.length} cron jobs`); +}; + +const generateStaticFiles = async () => { + const files = await recursive(path.join(SRC, "..", "static")); + const staticFiles = files.map( + file => file.split(path.join(SRC, "..", "static").toString())[1] + ); + const staticCode = ` + ${staticFiles + .map( + staticFile => ` + this.app.get("${staticFile}", (req, res) => res.sendFile(join(__dirname, "..", "static", "${staticFile}"))); + ` + ) + .join("")} + // staart-autogenerated + `; + server = server.replace("// staart-autogenerated", staticCode); + console.log(`✅ Serving ${staticFiles.length} static files`); +}; + +const writeServerFile = async () => { + await fs.writeFile( + path.join(SRC, "app.ts"), + server.replace("// staart-autogenerated", "") + ); + console.log("✅ Generated app.ts file"); +}; + +const setup = async () => { + await generateControllers(); + await generateRedirects(); + await generateCrons(); + await generateStaticFiles(); + await writeServerFile(); +}; + +setup() .then(() => { - fs.writeFileSync(path.join(SRC, "app.ts"), server); - console.log("✅ Generated app.ts file"); console.log("⌛ Compiling TypeScript"); process.exit(0); - }); + }) + .catch(error => console.log("Error in setup", error)); diff --git a/src/controllers/admin.ts b/src/controllers/v1/admin.ts similarity index 82% rename from src/controllers/admin.ts rename to src/controllers/v1/admin.ts index c5b1cd678..e1d2cb883 100644 --- a/src/controllers/admin.ts +++ b/src/controllers/v1/admin.ts @@ -1,13 +1,16 @@ import { Request, Response } from "express"; -import { ErrorCode } from "../interfaces/enum"; -import { getAllOrganizationForUser, getAllUsersForUser } from "../rest/admin"; +import { ErrorCode } from "../../interfaces/enum"; +import { + getAllOrganizationForUser, + getAllUsersForUser +} from "../../rest/admin"; import { Get, Controller, ClassMiddleware, ClassWrapper } from "@overnightjs/core"; -import { authHandler } from "../helpers/middleware"; +import { authHandler } from "../../helpers/middleware"; import asyncHandler from "express-async-handler"; @Controller("admin") diff --git a/src/controllers/auth.ts b/src/controllers/v1/auth.ts similarity index 95% rename from src/controllers/auth.ts rename to src/controllers/v1/auth.ts index 4dbad4562..f8cdffba8 100644 --- a/src/controllers/auth.ts +++ b/src/controllers/v1/auth.ts @@ -1,5 +1,5 @@ import { Request, Response, NextFunction, RequestHandler } from "express"; -import { ErrorCode, UserRole, Tokens } from "../interfaces/enum"; +import { ErrorCode, UserRole, Tokens } from "../../interfaces/enum"; import { sendPasswordReset, login, @@ -10,8 +10,8 @@ import { verifyEmail, register, login2FA -} from "../rest/auth"; -import { verifyToken, LoginResponse } from "../helpers/jwt"; +} from "../../rest/auth"; +import { verifyToken, LoginResponse } from "../../helpers/jwt"; import { Get, Post, @@ -25,13 +25,19 @@ import { authHandler, bruteForceHandler, validator -} from "../helpers/middleware"; +} from "../../helpers/middleware"; import { CREATED } from "http-status-codes"; import asyncHandler from "express-async-handler"; -import { safeRedirect, joiValidate } from "../helpers/utils"; +import { safeRedirect, joiValidate } from "../../helpers/utils"; import Joi from "@hapi/joi"; -import { FRONTEND_URL, BASE_URL } from "../config"; -import { salesforce, github, microsoft, google, facebook } from "../rest/oauth"; +import { FRONTEND_URL, BASE_URL } from "../../config"; +import { + salesforce, + github, + microsoft, + google, + facebook +} from "../../rest/oauth"; import { stringify } from "querystring"; const OAuthRedirector = (action: RequestHandler) => ( diff --git a/src/controllers/membership.ts b/src/controllers/v1/membership.ts similarity index 86% rename from src/controllers/membership.ts rename to src/controllers/v1/membership.ts index e169cfb32..e5ffed54c 100644 --- a/src/controllers/membership.ts +++ b/src/controllers/v1/membership.ts @@ -1,11 +1,11 @@ import { Request, Response } from "express"; -import { ErrorCode } from "../interfaces/enum"; +import { ErrorCode } from "../../interfaces/enum"; import { getMembershipDetailsForUser, inviteMemberToOrganization, deleteMembershipForUser, updateMembershipForUser -} from "../rest/membership"; +} from "../../rest/membership"; import { Get, Patch, @@ -16,11 +16,11 @@ import { ClassWrapper, Middleware } from "@overnightjs/core"; -import { authHandler, validator } from "../helpers/middleware"; +import { authHandler, validator } from "../../helpers/middleware"; import asyncHandler from "express-async-handler"; import Joi from "@hapi/joi"; -import { joiValidate } from "../helpers/utils"; -import i18n from "../i18n"; +import { joiValidate } from "../../helpers/utils"; +import i18n from "../../i18n"; @Controller("memberships") @ClassWrapper(asyncHandler) diff --git a/src/controllers/organization.ts b/src/controllers/v1/organization.ts similarity index 98% rename from src/controllers/organization.ts rename to src/controllers/v1/organization.ts index b541e1d69..efa4af86a 100644 --- a/src/controllers/organization.ts +++ b/src/controllers/v1/organization.ts @@ -37,7 +37,7 @@ import { getOrganizationWebhookForUser, updateWebhookForUser, deleteWebhookForUser -} from "../rest/organization"; +} from "../../rest/organization"; import { Get, Put, @@ -49,16 +49,16 @@ import { Middleware, Post } from "@overnightjs/core"; -import { authHandler, validator } from "../helpers/middleware"; -import { MembershipRole } from "../interfaces/enum"; +import { authHandler, validator } from "../../helpers/middleware"; +import { MembershipRole } from "../../interfaces/enum"; import { CREATED } from "http-status-codes"; import asyncHandler from "express-async-handler"; -import { inviteMemberToOrganization } from "../rest/membership"; +import { inviteMemberToOrganization } from "../../rest/membership"; import { joiValidate, organizationUsernameToId, localsToTokenOrKey -} from "../helpers/utils"; +} from "../../helpers/utils"; import Joi from "@hapi/joi"; @Controller("organizations") diff --git a/src/controllers/user.ts b/src/controllers/v1/user.ts similarity index 98% rename from src/controllers/user.ts rename to src/controllers/v1/user.ts index 597b9c1cd..b308cdab0 100644 --- a/src/controllers/user.ts +++ b/src/controllers/v1/user.ts @@ -19,7 +19,7 @@ import { getUserAccessTokenForUser, createAccessTokenForUser, getUserAccessTokensForUser -} from "../rest/user"; +} from "../../rest/user"; import { Get, Patch, @@ -31,17 +31,17 @@ import { ClassWrapper, Middleware } from "@overnightjs/core"; -import { authHandler, validator } from "../helpers/middleware"; +import { authHandler, validator } from "../../helpers/middleware"; import { getAllEmailsForUser, addEmailToUserForUser, deleteEmailFromUserForUser, getEmailForUser, resendEmailVerificationForUser -} from "../rest/email"; +} from "../../rest/email"; import { CREATED } from "http-status-codes"; import asyncHandler from "express-async-handler"; -import { joiValidate, userUsernameToId } from "../helpers/utils"; +import { joiValidate, userUsernameToId } from "../../helpers/utils"; import Joi from "@hapi/joi"; @Controller("users")