Skip to content
This repository has been archived by the owner on Apr 19, 2023. It is now read-only.

Commit

Permalink
✨ Nested controller support
Browse files Browse the repository at this point in the history
  • Loading branch information
AnandChowdhary committed Jul 24, 2019
1 parent 519d8d6 commit cbc8089
Show file tree
Hide file tree
Showing 7 changed files with 141 additions and 107 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "staart-manager",
"version": "1.0.103",
"version": "1.0.104",
"main": "index.js",
"repository": "[email protected]:AnandChowdhary/staart.git",
"author": "Anand Chowdhary <[email protected]>",
Expand Down Expand Up @@ -135,5 +135,5 @@
"setup"
],
"snyk": true,
"staart-version": "1.0.103"
"staart-version": "1.0.104"
}
187 changes: 106 additions & 81 deletions setup/controllers.js
Original file line number Diff line number Diff line change
Expand Up @@ -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));
9 changes: 6 additions & 3 deletions src/controllers/admin.ts → src/controllers/v1/admin.ts
Original file line number Diff line number Diff line change
@@ -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")
Expand Down
20 changes: 13 additions & 7 deletions src/controllers/auth.ts → src/controllers/v1/auth.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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,
Expand All @@ -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) => (
Expand Down
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ import {
getOrganizationWebhookForUser,
updateWebhookForUser,
deleteWebhookForUser
} from "../rest/organization";
} from "../../rest/organization";
import {
Get,
Put,
Expand All @@ -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")
Expand Down
8 changes: 4 additions & 4 deletions src/controllers/user.ts → src/controllers/v1/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import {
getUserAccessTokenForUser,
createAccessTokenForUser,
getUserAccessTokensForUser
} from "../rest/user";
} from "../../rest/user";
import {
Get,
Patch,
Expand All @@ -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")
Expand Down

0 comments on commit cbc8089

Please sign in to comment.