very-express 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/index.js +661 -493
  2. package/dist/templates/_middlewares/Authentication.ts +45 -0
  3. package/dist/templates/_plugins/auth/JWTKeyStore.ts +71 -0
  4. package/dist/templates/_plugins/auth/jwt.ts +57 -0
  5. package/dist/templates/_plugins/auth/oauthVerify.ts +83 -0
  6. package/dist/templates/_plugins/auth/profileMapping.ts +69 -0
  7. package/dist/templates/_plugins/auth/token.ts +25 -0
  8. package/dist/templates/_routes/oauth/OAuthRouteFactory.ts +88 -0
  9. package/dist/templates/_services/VexDbConnector.ts +3 -1
  10. package/dist/templates/_types/response/index.ts +10 -0
  11. package/dist/templates/_types/response/responseCode.ts +13 -0
  12. package/dist/templates/_types/response/responseMsg.ts +23 -0
  13. package/dist/templates/_types/response/responseStatusToCode.ts +70 -0
  14. package/dist/templates/_utils/index.ts +6 -2
  15. package/dist/templates/_utils/logger.ts +5 -5
  16. package/dist/templates/_utils/processTimer.ts +6 -0
  17. package/dist/templates/_utils/response.ts +25 -11
  18. package/dist/templates/jsonSchema/User.json +41 -14
  19. package/dist/templates/root/.env +10 -1
  20. package/dist/templates/root/Dockerfile +20 -0
  21. package/dist/templates/root/README.md +5 -0
  22. package/dist/templates/root/package.json +13 -4
  23. package/dist/templates/root/scripts/build.js +39 -0
  24. package/docs/roadMap/v0-6-0.md +8 -3
  25. package/docs/roadMap/v0-7-0.md +2 -1
  26. package/package.json +4 -14
  27. package/scripts/copyTsTemplates.js +6 -0
  28. package/vex.config.json +5 -7
  29. package/dist/templates/_plugins/PassportGoogle.ts +0 -84
  30. package/dist/templates/_plugins/oauthVerify.ts +0 -39
  31. package/dist/templates/_types/responseMsg.ts +0 -20
  32. /package/docs/{roadMap → releaseNote}/v0-5-0.md +0 -0
@@ -0,0 +1,45 @@
1
+ // {{headerComment}}
2
+
3
+ import { Request, Response, NextFunction } from "express";
4
+ import * as jwt from "../_plugins/auth/jwt.gen";
5
+ import Log from "../_utils/logger.gen";
6
+ import responseGen from "../_utils/response.gen";
7
+
8
+ export default class Authentication {
9
+
10
+ public middleware = (req: Request, res: Response, next: NextFunction) => {
11
+ try {
12
+ Log.info("Authentication.middleware", req.headers.authorization);
13
+
14
+ if (!req.headers.authorization) {
15
+ Log.ok("no Header", req.headers.authorization);
16
+ responseGen.send(res, 401);
17
+ return;
18
+ }
19
+
20
+ // verify token with jwt.verify
21
+ const token = req.headers.authorization.split(" ")[1];
22
+ const clientIndex = req.cookies.tokenIndex;
23
+ const tokenData = jwt.verifyToken(token, clientIndex);
24
+
25
+ if (!tokenData) {
26
+ Log.ok("tokenInvalid", tokenData);
27
+ throw 401;
28
+ }
29
+
30
+ // if token is valid, set req.user to the decoded token
31
+ Log.ok("tokenValid", tokenData);
32
+ req.user = tokenData;
33
+ next();
34
+ }
35
+ catch (e: any) {
36
+ if (typeof e === "number") {
37
+ responseGen.send(res, e);
38
+ }
39
+ else {
40
+ Log.errorNoExit(e);
41
+ responseGen.send(res, 500, e?.message);
42
+ }
43
+ }
44
+ };
45
+ }
@@ -0,0 +1,71 @@
1
+ // {{headerComment}}
2
+
3
+ import dotenv from "dotenv";
4
+ dotenv.config();
5
+
6
+ export class JWTKeyStore{
7
+ readonly expireTime: string | undefined = process.env.JWT_EXPIRE_TIME;
8
+ private keys: string[] = [];
9
+
10
+ constructor(){
11
+ this.keys = [
12
+ process.env.JWT_KEY0 || undefined,
13
+ process.env.JWT_KEY1 || undefined,
14
+ process.env.JWT_KEY2 || undefined,
15
+ process.env.JWT_KEY3 || undefined,
16
+ process.env.JWT_KEY4 || undefined,
17
+ process.env.JWT_KEY5 || undefined,
18
+ process.env.JWT_KEY6 || undefined,
19
+ process.env.JWT_KEY7 || undefined,
20
+ process.env.JWT_KEY8 || undefined,
21
+ process.env.JWT_KEY9 || undefined,
22
+ ].filter((key) => key !== undefined);
23
+ }
24
+
25
+ /**
26
+ * @return {number}
27
+ * - key
28
+ * - index (actual index of key)
29
+ * - client index (index with random string)
30
+ */
31
+ public getRandomKey(): { index: number, clientIndex:string, key: string } {
32
+ // get leng of keys and return random key
33
+ const len = this.keys.length;
34
+ const tokenInfo = {
35
+ index: 0,
36
+ clientIndex: "",
37
+ key: ""
38
+ };
39
+ if (len > 1) {
40
+ tokenInfo.index = Math.floor(Math.random() * len);
41
+ }
42
+
43
+ tokenInfo.clientIndex = this.getRandomCharString() + tokenInfo.index;
44
+ tokenInfo.key = this.keys[tokenInfo.index];
45
+
46
+ return tokenInfo;
47
+ }
48
+
49
+ /**
50
+ * retrive key by index or client index
51
+ */
52
+ public getKey(index:number|string): string {
53
+ if (typeof index === "string") {
54
+ index = parseInt(index.replace(/\D/g, ""));
55
+ }
56
+
57
+ return this.keys[index];
58
+ }
59
+
60
+ private getRandomCharString(length: number = 3): string {
61
+ const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
62
+ let result = "";
63
+ for (let i = 0; i < length; i++) {
64
+ const randomIndex = Math.floor(Math.random() * characters.length);
65
+ result += characters[randomIndex];
66
+ }
67
+ return result;
68
+ }
69
+ }
70
+
71
+ export default JWTKeyStore;
@@ -0,0 +1,57 @@
1
+ // {{headerComment}}
2
+
3
+ import jwt from "jsonwebtoken";
4
+ import JWTKeyStore from "./JWTKeyStore.gen";
5
+
6
+ const keys = new JWTKeyStore();
7
+
8
+ export function generateToken(
9
+ data: any,
10
+ expiresIn?: string
11
+ ): {
12
+ token: string,
13
+ index: number,
14
+ clientIndex: string
15
+ } {
16
+ const keyInfo = keys.getRandomKey();
17
+ const token = jwt.sign(
18
+ data,
19
+ keyInfo.key,
20
+ {
21
+ expiresIn: expiresIn || keys.expireTime || "1h",
22
+ }
23
+ );
24
+
25
+ return {
26
+ token: token,
27
+ index: keyInfo.index,
28
+ clientIndex: keyInfo.clientIndex
29
+ };
30
+ }
31
+
32
+ /**
33
+ * Verifies a JSON Web Token (JWT) using the provided token and key index.
34
+ *
35
+ * @param {string} token - The JSON Web Token to be verified.
36
+ * @param {number} index - The index of the key used to verify the token.
37
+ * @return {jwt.JwtPayload | string | false} The decoded token payload, an error message, or false if verification fails.
38
+ */
39
+ export function verifyToken(token: string, index?: number|string): jwt.JwtPayload | string | false {
40
+ try {
41
+ if(!index) {
42
+ return false;
43
+ }
44
+ const key = keys.getKey(index);
45
+ return jwt.verify(token, key);
46
+ } catch (e) {
47
+ if(e instanceof jwt.TokenExpiredError) {
48
+ throw e;
49
+ }
50
+ else if (e instanceof jwt.JsonWebTokenError) {
51
+ throw e;
52
+ }
53
+ else {
54
+ return false;
55
+ }
56
+ }
57
+ }
@@ -0,0 +1,83 @@
1
+ // {{headerComment}}
2
+
3
+ import { UserModel, UserDocument } from "./../../_models/UserModel.gen";
4
+ import { User } from "./../../_types/User.gen";
5
+ import profileMapping, { IProfile } from "./profileMapping.gen";
6
+ import returnToken from "./token.gen";
7
+ import vex from "../../_utils/index.gen";
8
+
9
+ export default async function oauthVerify(accessToken: string, refreshToken: string, profile: IProfile, done: (error: any, user?: any) => void) : Promise<void> {
10
+ try {
11
+
12
+ let user: UserDocument;
13
+ const authUser = profileMapping(profile);
14
+
15
+ // find user by authProfiles.authId or email
16
+ const existingUser = await UserModel.findOne<UserDocument>({
17
+ email: authUser.email,
18
+ $or: authUser.authProfiles?.map((p) => {
19
+ return { "authProfiles.authId": p.authId };
20
+ }),
21
+ });
22
+
23
+ // 1. create new user
24
+ if ( !existingUser ){
25
+ user = await createNewUser(authUser);
26
+ }
27
+ // 2. update existing user
28
+ else {
29
+ console.log("OAuthVerify UpdateUser");
30
+ user = await processExistingUser(authUser, existingUser);
31
+ }
32
+
33
+ done(null, returnToken(user));
34
+ }
35
+ catch(err) {
36
+ return done(err);
37
+ }
38
+ }
39
+
40
+ async function createNewUser(authProfile: User): Promise<UserDocument>{
41
+ vex.log.info("OAuthVerify > createNewUser");
42
+ const newUser = new UserModel(authProfile);
43
+ return await newUser.save();
44
+ }
45
+
46
+ async function processExistingUser( authUser: User, existingUser: UserDocument): Promise<UserDocument>{
47
+ vex.log.info("OAuthVerify > processExistingUser");
48
+
49
+ let userUpdated = false;
50
+ const authProfile = authUser.authProfiles?.[0] || undefined;
51
+ const userProfiles = existingUser.authProfiles as User["authProfiles"] || [];
52
+
53
+ if(!authProfile){
54
+ vex.log.errorNoExit("OAuthVerify > Invalid OAuth Callback \"authProfile\"");
55
+ throw new Error("Invalid OAuth Callback \"authProfile\"");
56
+ }
57
+
58
+ // B.1. check current provider exist in authProfiles
59
+ const providerExists = userProfiles.length > 0 && userProfiles.find((p) => {
60
+ return (p.provider === authProfile.provider) && (p.authId === authProfile.authId);
61
+ });
62
+
63
+ // B.2. add if not exist
64
+ if (!providerExists){
65
+ vex.log.info("OAuthVerify > add new provider",authProfile.provider);
66
+ userProfiles.push(authProfile);
67
+ userUpdated = true;
68
+ }
69
+ // B.3 update if username changed
70
+ else if (providerExists && providerExists.username !== authProfile.username){
71
+ vex.log.info("OAuthVerify > update username", authProfile.provider);
72
+ providerExists.username = authProfile.username;
73
+ userUpdated = true;
74
+ }
75
+
76
+ if (userUpdated){
77
+ vex.log.info("OAuthVerify > Update user");
78
+ return await existingUser.updateOne({ authProfiles: userProfiles });
79
+ }
80
+ else {
81
+ return existingUser;
82
+ }
83
+ }
@@ -0,0 +1,69 @@
1
+ // {{headerComment}}
2
+
3
+ import { Profile } from "passport";
4
+ import { User } from "./../../_types/User.gen";
5
+
6
+ export interface IProfile extends Profile {
7
+ [key: string]: any;
8
+ }
9
+ export default function profileMapping(oauthProfile: IProfile): User
10
+ {
11
+ let authProfile: User;
12
+ switch(oauthProfile.provider){
13
+ case "github":
14
+ authProfile = GithubProfileMapping(oauthProfile);
15
+ break;
16
+ case "google":
17
+ authProfile = GoogleProfileMapping(oauthProfile);
18
+ break;
19
+ default:
20
+ throw new Error("Invalid OAuth Provider");
21
+ break;
22
+ }
23
+
24
+ // if ( !authProfile.email){
25
+ // console.log('missingEmail');
26
+ // authProfile.profileErrors?.push('missingEmail');
27
+ // authProfile.active = false;
28
+ // }
29
+ return authProfile;
30
+ }
31
+
32
+ export function GithubProfileMapping(oauthProfile: IProfile): User
33
+ {
34
+ const user: User = {
35
+ active: true,
36
+ authProfiles: [{
37
+ provider: oauthProfile.provider,
38
+ authId: oauthProfile.id,
39
+ username: oauthProfile.username || oauthProfile.displayName
40
+ }],
41
+ roles: undefined,
42
+ name: oauthProfile.username || oauthProfile.displayName,
43
+ email: oauthProfile._json.email || oauthProfile._json.notification_email || undefined,
44
+ locale: undefined,
45
+ profileErrors: []
46
+ };
47
+
48
+ return user;
49
+ }
50
+
51
+ export function GoogleProfileMapping(oauthProfile: IProfile): User
52
+ {
53
+ const user: User = {
54
+ active: true,
55
+ authProfiles: [{
56
+ provider: oauthProfile.provider,
57
+ authId: oauthProfile.id,
58
+ username: oauthProfile.username || oauthProfile.displayName
59
+ }],
60
+ roles: undefined,
61
+ name: oauthProfile.username || oauthProfile.displayName,
62
+ // data below could be missing depend on the provider
63
+ email: oauthProfile._json.email || oauthProfile._json.notification_email || undefined,
64
+ locale: oauthProfile._json.locale || undefined,
65
+ profileErrors: []
66
+ };
67
+
68
+ return user;
69
+ }
@@ -0,0 +1,25 @@
1
+ // {{headerComment}}
2
+
3
+ import { generateToken } from "./../auth/jwt.gen";
4
+ import { UserDocument } from "./../../_models/UserModel.gen";
5
+
6
+ export default function returnToken(userProfile: UserDocument){
7
+ const sanitizedProfile = sanitizeUser(userProfile);
8
+ const tokenInfo = generateToken(sanitizedProfile);
9
+ return {
10
+ profile: sanitizedProfile,
11
+ tokenInfo: tokenInfo
12
+ };
13
+ }
14
+
15
+ function sanitizeUser(user: UserDocument){
16
+ return {
17
+ _id: user._id,
18
+ email: user.email,
19
+ name: user.name,
20
+ locale: user.locale,
21
+ roles: user.roles,
22
+ profileErrors: user.profileErrors,
23
+ active: user.active
24
+ };
25
+ }
@@ -0,0 +1,88 @@
1
+ // {{headerComment}}
2
+
3
+ import { Router } from "express";
4
+ import passport, { PassportStatic, Profile } from "passport";
5
+ import * as oauth2 from "passport-oauth2";
6
+ // import responseGen from "../../_utils/response.gen";
7
+ // import { generateToken, verifyToken } from "../../_plugins/auth/jwt.gen";
8
+
9
+ export type { Profile };
10
+
11
+ export interface passportFactoryConfig {
12
+ strategyName: string,
13
+ strategy: oauth2.Strategy,
14
+ authenticateOptions?: any,
15
+ }
16
+
17
+ /** Provides a router and passport instance for Google OAuth */
18
+ export default class OAuthRouteFactory {
19
+
20
+ private config: passportFactoryConfig;
21
+ private router: Router = Router();
22
+ private passport: PassportStatic = passport;
23
+
24
+ constructor(config: passportFactoryConfig ) {
25
+
26
+ this.config = config;
27
+ this.config.authenticateOptions = this.config.authenticateOptions || {
28
+ session: false,
29
+ scope: ["profile", "email"],
30
+ failureRedirect: ""
31
+ };
32
+
33
+ this.initPassport(this.config.strategy);
34
+ this.initRoutes();
35
+
36
+ }
37
+
38
+ private initPassport(strategy: passport.Strategy){
39
+ this.passport.use(strategy);
40
+ this.passport.initialize();
41
+ }
42
+
43
+ private initRoutes(){
44
+ // redirect to login
45
+ this.router.get("/",
46
+ this.passport.authenticate(this.config.strategyName, this.config.authenticateOptions)
47
+ );
48
+
49
+ // back from login
50
+ this.router.get("/callback",
51
+ this.passport.authenticate(this.config.strategyName, this.config.authenticateOptions),
52
+ (req, res) => {
53
+ const user = req.user as any;
54
+ const tokenInfo = user.tokenInfo;
55
+ res.redirect(`/profile?accessToken=${tokenInfo.token}&tokenIndex=${tokenInfo.clientIndex}`);
56
+ }
57
+ );
58
+
59
+ // // refresh expired token
60
+ // this.router.get("/refresh",
61
+ // this.passport.authenticate(this.config.strategyName, this.config.authenticateOptions),
62
+ // (req, res) => {
63
+ // const user = req.user as any;
64
+
65
+ // // create new token
66
+ // // 1. get user info from token
67
+ // const tokenData = verifyToken(user.tokenInfo.token, user.tokenInfo.clientIndex);
68
+
69
+ // // 2. create new token if token is valid
70
+ // if (tokenData) {
71
+ // responseGen.send(
72
+ // res,
73
+ // 200,
74
+ // undefined,
75
+ // generateToken(tokenData)
76
+ // );
77
+ // }
78
+ // else{
79
+ // responseGen.send(res, 401);
80
+ // }
81
+ // }
82
+ // );
83
+ }
84
+
85
+ public getRouter() {
86
+ return this.router;
87
+ }
88
+ }
@@ -64,7 +64,9 @@ export default class VexDbConnector {
64
64
  **/
65
65
  middleware(req: Request, res: Response, next: NextFunction) {
66
66
  if (mongoose.connection.readyState !== 1) {
67
- vex.response.send(res, 503, "Database Connection Down");
67
+ vex.response.send(res, 503, {
68
+ message: "Database connection error",
69
+ });
68
70
  }
69
71
  else if (this.recordAccessLog){
70
72
  mongoose.connection.collection("accessLogs").insertOne({
@@ -0,0 +1,10 @@
1
+ export { responseMsg } from "./responseMsg.gen";
2
+ export { responseCode, ResponseCode } from "./responseCode.gen";
3
+ export { responseStatusToCode } from "./responseStatusToCode.gen";
4
+
5
+ export interface responseObject<T>{
6
+ ret_code : number,
7
+ ret_msg : string,
8
+ ret_time?: number,
9
+ result: T,
10
+ }
@@ -0,0 +1,13 @@
1
+ import { responseMsg } from "./responseMsg.gen";
2
+
3
+ /** custom response code **/
4
+ export type ResponseCode = keyof typeof responseMsg;
5
+
6
+ /** custom response code **/
7
+ export const responseCode = Object.keys(responseMsg).reduce((acc, key) => {
8
+ acc[key] = key as ResponseCode;
9
+ return acc;
10
+ }, {} as Record<string, ResponseCode>);
11
+
12
+
13
+ export default responseCode;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * default response message of each return code
3
+ **/
4
+ export const responseMsg = {
5
+ success: "Success",
6
+
7
+ err_perm: "Permission Denied",
8
+
9
+ err_payload: "Invalid Request Payload",
10
+ err_query: "Invalid Request Query",
11
+ err_body: "Invalid Request Body",
12
+
13
+ err_validation: "Validation Error",
14
+ err_query_validation: "Query Validation Error",
15
+ err_body_validation: "Body Validation Error",
16
+
17
+ err_create: "Falied to Insert Data",
18
+ err_read: "Falied to Read Data",
19
+ err_update: "Falied to Edit Data",
20
+ err_delete: "Falied to Delete Data",
21
+ };
22
+
23
+ export default responseMsg;
@@ -0,0 +1,70 @@
1
+ import responseCode from "./responseCode.gen";
2
+
3
+ /**
4
+ * response status default message.
5
+ * if set value as response code, response handler will set status, code & message.
6
+ **/
7
+ export const responseStatusToCode = new Map<number, string>();
8
+ // responseStatusToCode.set(100, "Continue");
9
+ // responseStatusToCode.set(101, "Switching Protocols");
10
+ // responseStatusToCode.set(102, "Processing");
11
+ // responseStatusToCode.set(103, "Early Hints");
12
+ responseStatusToCode.set(200, responseCode.success);
13
+ responseStatusToCode.set(201, responseCode.success);
14
+ responseStatusToCode.set(202, responseCode.success);
15
+ // responseStatusToCode.set(203, "Non-Authoritative Information");
16
+ // responseStatusToCode.set(204, "No Content");
17
+ // responseStatusToCode.set(205, "Reset Content");
18
+ // responseStatusToCode.set(206, "Partial Content");
19
+ // responseStatusToCode.set(207, "Multi-Status");
20
+ // responseStatusToCode.set(208, "Already Reported");
21
+ // responseStatusToCode.set(226, "IM Used");
22
+ // responseStatusToCode.set(300, "Multiple Choices");
23
+ // responseStatusToCode.set(301, "Moved Permanently");
24
+ // responseStatusToCode.set(302, "Found");
25
+ // responseStatusToCode.set(303, "See Other");
26
+ // responseStatusToCode.set(304, "Not Modified");
27
+ // responseStatusToCode.set(307, "Temporary Redirect");
28
+ // responseStatusToCode.set(308, "Permanent Redirect");
29
+ responseStatusToCode.set(400, responseCode.err_payload);
30
+ // responseStatusToCode.set(401, responseCode.err_perm);
31
+ // responseStatusToCode.set(402, "Payment Required");
32
+ // responseStatusToCode.set(403, "Forbidden");
33
+ // responseStatusToCode.set(404, "Not Found");
34
+ // responseStatusToCode.set(405, "Method Not Allowed");
35
+ // responseStatusToCode.set(406, "Not Acceptable");
36
+ // responseStatusToCode.set(407, "Proxy Authentication Required");
37
+ // responseStatusToCode.set(408, "Request Timeout");
38
+ // responseStatusToCode.set(409, "Conflict");
39
+ // responseStatusToCode.set(410, "Gone");
40
+ // responseStatusToCode.set(411, "Length Required");
41
+ // responseStatusToCode.set(412, "Precondition Failed");
42
+ // responseStatusToCode.set(413, "Content Too Large");
43
+ // responseStatusToCode.set(414, "URI Too Long");
44
+ // responseStatusToCode.set(415, "Unsupported Media Type");
45
+ // responseStatusToCode.set(416, "Range Not Satisfiable");
46
+ // responseStatusToCode.set(417, "Expectation Failed");
47
+ // responseStatusToCode.set(418, "I'm a teapot");
48
+ // responseStatusToCode.set(421, "Misdirected Request");
49
+ // responseStatusToCode.set(422, "Unprocessable Content");
50
+ // responseStatusToCode.set(423, "Locked");
51
+ // responseStatusToCode.set(424, "Failed Dependency");
52
+ // responseStatusToCode.set(425, "Too Early");
53
+ // responseStatusToCode.set(426, "Upgrade Required");
54
+ // responseStatusToCode.set(428, "Precondition Required");
55
+ // responseStatusToCode.set(429, "Too Many Requests");
56
+ // responseStatusToCode.set(431, "Request Header Fields Too Large");
57
+ // responseStatusToCode.set(451, "Unavailable For Legal Reasons");
58
+ // responseStatusToCode.set(500, "Internal Server Error");
59
+ // responseStatusToCode.set(501, "Not Implemented");
60
+ // responseStatusToCode.set(502, "Bad Gateway");
61
+ // responseStatusToCode.set(503, "Service Unavailable");
62
+ // responseStatusToCode.set(504, "Gateway Timeout");
63
+ // responseStatusToCode.set(505, "HTTP Version Not Supported");
64
+ // responseStatusToCode.set(506, "Variant Also Negotiates");
65
+ // responseStatusToCode.set(507, "Insufficient Storage");
66
+ // responseStatusToCode.set(508, "Loop Detected");
67
+ // responseStatusToCode.set(510, "Not Extended");
68
+ // responseStatusToCode.set(511, "Network Authentication Required");
69
+
70
+ export default responseStatusToCode;
@@ -1,13 +1,17 @@
1
+
2
+
1
3
  import logger from "./logger.gen";
2
4
  import response from "./response.gen";
3
5
  import validator from "./validator.gen";
4
- import { responseMsg } from "./../_types/responseMsg.gen";
6
+ import { responseMsg, responseCode, responseStatusToCode } from "./../_types/response/index.gen";
5
7
  import common from "./common.gen";
6
8
 
7
9
  export default {
8
10
  log : logger,
9
11
  response,
10
12
  validator,
11
- responseMsg : responseMsg ,
13
+ responseMsg,
14
+ responseCode,
15
+ responseStatusToCode,
12
16
  common
13
17
  };
@@ -1,17 +1,17 @@
1
1
  export function processing(msg: any, ...optionalParams: any[]): void {
2
- console.log("\x1b[34m%s\x1b[0m", "[PROCESSING]", msg, optionalParams.length > 0 ? optionalParams : "");
2
+ console.log("\x1b[34m%s\x1b[0m", "[PROCESSING]" , new Date().toLocaleString() +" -", msg, optionalParams.length > 0 ? optionalParams : "");
3
3
  }
4
4
 
5
5
  export function ok(msg: any, ...optionalParams: any[]): void {
6
- console.log("\x1b[32m%s\x1b[0m", "[OK]", msg, optionalParams.length > 0 ? optionalParams : "");
6
+ console.log("\x1b[32m%s\x1b[0m", "[OK]" , new Date().toLocaleString() +" -", msg, optionalParams.length > 0 ? optionalParams : "");
7
7
  }
8
8
 
9
9
  export function info(msg: any, ...optionalParams: any[]): void {
10
- console.log("\x1b[36m%s\x1b[0m", "[INFO]", msg, optionalParams.length > 0 ? optionalParams : "");
10
+ console.log("\x1b[36m%s\x1b[0m", "[INFO]" , new Date().toLocaleString() +" -", msg, optionalParams.length > 0 ? optionalParams : "");
11
11
  }
12
12
 
13
13
  export function warn(msg: any, ...optionalParams: any[]): void {
14
- console.log("\x1b[33m%s\x1b[0m", "[WARN]", msg, optionalParams.length > 0 ? optionalParams : "");
14
+ console.log("\x1b[33m%s\x1b[0m", "[WARN]" , new Date().toLocaleString() +" -", msg, optionalParams.length > 0 ? optionalParams : "");
15
15
  }
16
16
 
17
17
  export function error(msg: any, ...optionalParams: any[]): never {
@@ -20,7 +20,7 @@ export function error(msg: any, ...optionalParams: any[]): never {
20
20
  }
21
21
 
22
22
  export function errorNoExit(msg: any, ...optionalParams: any[]): void {
23
- console.log("\x1b[41m%s\x1b[0m", "[ERROR]", msg, optionalParams.length > 0 ? optionalParams : "");
23
+ console.log("\x1b[41m%s\x1b[0m", "[ERROR]" , new Date().toLocaleString() +" -", msg, optionalParams.length > 0 ? optionalParams : "");
24
24
  }
25
25
 
26
26
  // wrapper
@@ -0,0 +1,6 @@
1
+ import { Request, Response, NextFunction } from "express";
2
+
3
+ export default function processTimer(req: Request, res: Response, next: NextFunction) {
4
+ res.locals.startAt = Date.now();
5
+ next();
6
+ }