very-express 0.5.2 → 0.5.4
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.
- package/.eslintrc.json +37 -37
- package/.gitattributes +2 -2
- package/.github/workflows/npm-start.yml +23 -23
- package/LICENSE +21 -21
- package/README.md +62 -61
- package/dist/index.js +415 -403
- package/dist/templates/_middlewares/Authentication.ts +22 -19
- package/dist/templates/_plugins/auth/JWTKeyStore.ts +27 -1
- package/dist/templates/_plugins/auth/jwt.ts +50 -24
- package/dist/templates/_plugins/auth/oauthVerify.ts +6 -2
- package/dist/templates/_plugins/auth/token.ts +5 -5
- package/dist/templates/_routes/oauth/OAuthRouteFactory.ts +39 -7
- package/dist/templates/_services/VexDbConnector.ts +2 -2
- package/dist/templates/_services/VexSystem.ts +37 -0
- package/dist/templates/_types/response/index.ts +1 -1
- package/dist/templates/_types/response/responseCode.ts +3 -1
- package/dist/templates/_types/response/responseMsg.ts +9 -2
- package/dist/templates/_types/response/responseStatusCodeMap.ts +70 -0
- package/dist/templates/_utils/index.ts +0 -6
- package/dist/templates/_utils/response.ts +40 -8
- package/dist/templates/jsonSchema/User.json +82 -82
- package/dist/templates/jsonSchema/session.json +32 -0
- package/dist/templates/root/.env +19 -13
- package/dist/templates/root/Dockerfile +19 -19
- package/dist/templates/root/README.md +38 -38
- package/dist/templates/root/package.json +48 -48
- package/dist/templates/root/public/css/style.css +8 -0
- package/dist/templates/root/public/js/logincallback.js +19 -0
- package/dist/templates/root/public/js/mytokens.js +11 -0
- package/dist/templates/root/public/js/refreshtokens.js +23 -0
- package/dist/templates/root/scripts/build.js +38 -38
- package/dist/templates/root/tsconfig.json +21 -21
- package/docs/ForeignKey.md +43 -40
- package/docs/appGenerated/auth.md +23 -0
- package/docs/developmentNote.md +22 -22
- package/docs/releaseNote/v0-5-0.md +17 -17
- package/docs/roadMap/released.md +49 -0
- package/docs/roadMap/v0-6-0.md +15 -15
- package/docs/roadMap/v0-7-0.md +5 -5
- package/docs/vexJsonSchema.md +55 -55
- package/package.json +50 -49
- package/scripts/build.js +13 -13
- package/scripts/copyTsTemplates.js +30 -30
- package/scripts/merge.js +125 -0
- package/tsconfig.json +121 -121
- package/vex.config.json +29 -29
- package/dist/templates/_types/response/responseStatusToCode.ts +0 -70
- package/docs/roadMap/RoadMap.md +0 -30
|
@@ -1,34 +1,34 @@
|
|
|
1
1
|
// {{headerComment}}
|
|
2
2
|
|
|
3
|
+
|
|
3
4
|
import { Request, Response, NextFunction } from "express";
|
|
5
|
+
import { JsonWebTokenError } from "jsonwebtoken";
|
|
4
6
|
import * as jwt from "../_plugins/auth/jwt.gen";
|
|
5
|
-
import
|
|
7
|
+
import log from "../_utils/logger.gen";
|
|
6
8
|
import responseGen from "../_utils/response.gen";
|
|
7
9
|
|
|
8
10
|
export default class Authentication {
|
|
9
11
|
|
|
10
12
|
public middleware = (req: Request, res: Response, next: NextFunction) => {
|
|
11
13
|
try {
|
|
12
|
-
|
|
14
|
+
// gate keeper
|
|
15
|
+
log.info("Authentication.middleware", req.headers["x-auth-index"], req.headers.authorization);
|
|
16
|
+
const token = req.headers.authorization?.split(" ")[1];
|
|
17
|
+
const accessTokenIndex = req.headers["x-auth-index"]?.toString();
|
|
13
18
|
|
|
14
|
-
if (!
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
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);
|
|
19
|
+
if (!token || !accessTokenIndex) {
|
|
20
|
+
log.warn("invalid header", {
|
|
21
|
+
"X-Auth-Index": req.headers["x-auth-index"],
|
|
22
|
+
"Authorization": req.headers.authorization
|
|
23
|
+
});
|
|
27
24
|
throw 401;
|
|
28
25
|
}
|
|
29
26
|
|
|
30
|
-
//
|
|
31
|
-
|
|
27
|
+
// verify token
|
|
28
|
+
const tokenData = jwt.verifyToken(token, accessTokenIndex);
|
|
29
|
+
|
|
30
|
+
// set req.user to the decoded token
|
|
31
|
+
log.info("tokenValid", tokenData);
|
|
32
32
|
req.user = tokenData;
|
|
33
33
|
next();
|
|
34
34
|
}
|
|
@@ -36,9 +36,12 @@ export default class Authentication {
|
|
|
36
36
|
if (typeof e === "number") {
|
|
37
37
|
responseGen.send(res, e);
|
|
38
38
|
}
|
|
39
|
+
else if (e instanceof JsonWebTokenError) {
|
|
40
|
+
responseGen.send(res, 400, { message: e?.message});
|
|
41
|
+
}
|
|
39
42
|
else {
|
|
40
|
-
|
|
41
|
-
responseGen.send(res, 500, e?.message);
|
|
43
|
+
log.errorNoExit(e);
|
|
44
|
+
responseGen.send(res, 500, { message: e?.message});
|
|
42
45
|
}
|
|
43
46
|
}
|
|
44
47
|
};
|
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
// {{headerComment}}
|
|
2
2
|
|
|
3
3
|
import dotenv from "dotenv";
|
|
4
|
+
import { Algorithm } from "jsonwebtoken";
|
|
5
|
+
|
|
4
6
|
dotenv.config();
|
|
7
|
+
|
|
5
8
|
export interface keyObj {
|
|
6
9
|
key: string,
|
|
7
10
|
index?: number,
|
|
@@ -9,7 +12,8 @@ export interface keyObj {
|
|
|
9
12
|
}
|
|
10
13
|
|
|
11
14
|
export class JWTKeyStore{
|
|
12
|
-
readonly
|
|
15
|
+
readonly algorithm: Algorithm = this.getAlgorithm(process.env.JWT_ALGORITHM);
|
|
16
|
+
readonly expireTime: string | undefined = process.env.JWT_EXPIRE_TIME || "1h";
|
|
13
17
|
private keys: string[] = [];
|
|
14
18
|
|
|
15
19
|
constructor(){
|
|
@@ -84,6 +88,28 @@ export class JWTKeyStore{
|
|
|
84
88
|
}
|
|
85
89
|
return result;
|
|
86
90
|
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Type guard to check if a string is a valid Algorithm.
|
|
94
|
+
* @param str - The string to check.
|
|
95
|
+
* @returns True if the string is a valid Algorithm, false otherwise.
|
|
96
|
+
*/
|
|
97
|
+
private getAlgorithm(str: string | undefined): Algorithm {
|
|
98
|
+
const algorithms: Algorithm[] = [
|
|
99
|
+
"HS256", "HS384", "HS512",
|
|
100
|
+
"RS256", "RS384", "RS512",
|
|
101
|
+
"ES256", "ES384", "ES512",
|
|
102
|
+
"PS256", "PS384", "PS512",
|
|
103
|
+
"none"
|
|
104
|
+
];
|
|
105
|
+
|
|
106
|
+
if ( algorithms.includes(str as Algorithm) ) {
|
|
107
|
+
return str as Algorithm;
|
|
108
|
+
}
|
|
109
|
+
else {
|
|
110
|
+
return "HS256";
|
|
111
|
+
}
|
|
112
|
+
}
|
|
87
113
|
}
|
|
88
114
|
|
|
89
115
|
export default JWTKeyStore;
|
|
@@ -2,25 +2,32 @@
|
|
|
2
2
|
|
|
3
3
|
import jwt from "jsonwebtoken";
|
|
4
4
|
import JWTKeyStore from "./JWTKeyStore.gen";
|
|
5
|
+
import responseCode from "../../_types/response/responseCode.gen";
|
|
6
|
+
import { UserModel } from "../../_models/UserModel.gen";
|
|
7
|
+
import { sanitizeUser } from "../../_plugins/auth/token.gen";
|
|
8
|
+
import { VexResponseError } from "../../_utils/response.gen";
|
|
9
|
+
|
|
10
|
+
interface tokenObj {
|
|
11
|
+
token: string,
|
|
12
|
+
index?: number,
|
|
13
|
+
clientIndex?: string
|
|
14
|
+
}
|
|
5
15
|
|
|
6
16
|
const keys = new JWTKeyStore();
|
|
7
17
|
|
|
8
18
|
export function generateToken(
|
|
9
19
|
data: any,
|
|
10
|
-
|
|
20
|
+
index?: number,
|
|
11
21
|
expiresIn?: string
|
|
12
|
-
): {
|
|
13
|
-
|
|
14
|
-
index
|
|
15
|
-
clientIndex?: string
|
|
16
|
-
} {
|
|
17
|
-
const keyInfo = typeof keyIndex == "number" ? keys.getKeyObj(keyIndex) : keys.getRandomKey();
|
|
18
|
-
|
|
22
|
+
): tokenObj {
|
|
23
|
+
data = JSON.parse(JSON.stringify(data));
|
|
24
|
+
const keyInfo = typeof index == "number" ? keys.getKeyObj(index) : keys.getRandomKey();
|
|
19
25
|
const token = jwt.sign(
|
|
20
26
|
data,
|
|
21
27
|
keyInfo.key,
|
|
22
28
|
{
|
|
23
29
|
expiresIn: expiresIn || keys.expireTime || "1h",
|
|
30
|
+
algorithm: keys.algorithm
|
|
24
31
|
}
|
|
25
32
|
);
|
|
26
33
|
|
|
@@ -31,29 +38,48 @@ export function generateToken(
|
|
|
31
38
|
};
|
|
32
39
|
}
|
|
33
40
|
|
|
41
|
+
export async function generateAccessToken(userId: string, index?: number): Promise<tokenObj> {
|
|
42
|
+
|
|
43
|
+
const userDoc = await UserModel.findById(userId).exec();
|
|
44
|
+
if (!userDoc) {
|
|
45
|
+
throw new VexResponseError(404, responseCode.err_payload, "Invalid User Id");
|
|
46
|
+
}
|
|
47
|
+
const userInfo = sanitizeUser(userDoc);
|
|
48
|
+
|
|
49
|
+
return generateToken(userInfo, index, process.env.ACCESS_TOKEN_EXPIRE_TIME);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function generateRefreshToken(data: any, index?: number): tokenObj {
|
|
53
|
+
return generateToken(data, index, process.env.REFRESH_TOKEN_EXPIRE_TIME);
|
|
54
|
+
}
|
|
55
|
+
|
|
34
56
|
/**
|
|
35
57
|
* Verifies a JSON Web Token (JWT) using the provided token and key index.
|
|
36
58
|
*
|
|
37
59
|
* @param {string} token - The JSON Web Token to be verified.
|
|
38
60
|
* @param {number} index - The index of the key used to verify the token.
|
|
39
|
-
* @return {jwt.JwtPayload
|
|
61
|
+
* @return {jwt.JwtPayload } The decoded token payload, an error message, or false if verification fails.
|
|
40
62
|
*/
|
|
41
|
-
export function verifyToken(token: string, index?: number|string): jwt.JwtPayload
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
63
|
+
export function verifyToken(token: string, index?: number|string): jwt.JwtPayload {
|
|
64
|
+
|
|
65
|
+
if(token.startsWith("Bearer ")) {
|
|
66
|
+
token = token.split("Bearer ")[1];
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const key = keys.getKey(index || 0);
|
|
70
|
+
|
|
71
|
+
try{
|
|
72
|
+
return jwt.verify(token, key) as jwt.JwtPayload;
|
|
73
|
+
}
|
|
74
|
+
catch (error){
|
|
75
|
+
if(error instanceof jwt.TokenExpiredError) {
|
|
76
|
+
throw new VexResponseError(401, responseCode.err_payload, "Token expired");
|
|
51
77
|
}
|
|
52
|
-
else if
|
|
53
|
-
throw
|
|
78
|
+
else if(error instanceof jwt.JsonWebTokenError) {
|
|
79
|
+
throw new VexResponseError(401, responseCode.err_payload, "jwt malformed");
|
|
54
80
|
}
|
|
55
|
-
else
|
|
56
|
-
|
|
81
|
+
else{
|
|
82
|
+
throw error;
|
|
57
83
|
}
|
|
58
84
|
}
|
|
59
|
-
}
|
|
85
|
+
}
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
import { UserModel, UserDocument } from "./../../_models/UserModel.gen";
|
|
4
4
|
import { User } from "./../../_types/User.gen";
|
|
5
5
|
import profileMapping, { IProfile } from "./profileMapping.gen";
|
|
6
|
-
import
|
|
6
|
+
import { sanitizeUser } from "./token.gen";
|
|
7
7
|
import vex from "../../_utils/index.gen";
|
|
8
8
|
|
|
9
9
|
export default async function oauthVerify(accessToken: string, refreshToken: string, profile: IProfile, done: (error: any, user?: any) => void) : Promise<void> {
|
|
@@ -30,7 +30,11 @@ export default async function oauthVerify(accessToken: string, refreshToken: str
|
|
|
30
30
|
user = await processExistingUser(authUser, existingUser);
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
-
|
|
33
|
+
// set req.user
|
|
34
|
+
done(null, {
|
|
35
|
+
provider: profile.provider,
|
|
36
|
+
profile: sanitizeUser(user),
|
|
37
|
+
});
|
|
34
38
|
}
|
|
35
39
|
catch(err) {
|
|
36
40
|
return done(err);
|
|
@@ -5,19 +5,19 @@ import { UserDocument } from "./../../_models/UserModel.gen";
|
|
|
5
5
|
|
|
6
6
|
export default function returnToken(userProfile: UserDocument){
|
|
7
7
|
const sanitizedProfile = sanitizeUser(userProfile);
|
|
8
|
-
const accessToken = generateToken(sanitizedProfile);
|
|
9
|
-
const refreshToken = generateToken({_id: userProfile._id }, 0);
|
|
8
|
+
const accessToken = generateToken(sanitizedProfile, undefined, process.env.ACCESS_TOKEN_EXPIRE_TIME);
|
|
9
|
+
const refreshToken = generateToken({_id: userProfile._id }, 0, process.env.REFRESH_TOKEN_EXPIRE_TIME);
|
|
10
10
|
|
|
11
11
|
return {
|
|
12
12
|
profile: sanitizedProfile,
|
|
13
13
|
accessToken: accessToken.token,
|
|
14
|
-
|
|
14
|
+
accessTokenIndex: accessToken.index,
|
|
15
15
|
clientIndex: accessToken.clientIndex,
|
|
16
|
-
refreshToken: refreshToken
|
|
16
|
+
refreshToken: refreshToken.token
|
|
17
17
|
};
|
|
18
18
|
}
|
|
19
19
|
|
|
20
|
-
function sanitizeUser(user: UserDocument){
|
|
20
|
+
export function sanitizeUser(user: UserDocument){
|
|
21
21
|
return {
|
|
22
22
|
_id: user._id,
|
|
23
23
|
email: user.email,
|
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
import { Router } from "express";
|
|
4
4
|
import passport, { PassportStatic, Profile } from "passport";
|
|
5
5
|
import * as oauth2 from "passport-oauth2";
|
|
6
|
-
|
|
7
|
-
|
|
6
|
+
import { SessionModel } from "../../_models/SessionModel.gen";
|
|
7
|
+
import path from "path";
|
|
8
8
|
|
|
9
9
|
export type { Profile };
|
|
10
10
|
|
|
@@ -21,6 +21,9 @@ export default class OAuthRouteFactory {
|
|
|
21
21
|
private router: Router = Router();
|
|
22
22
|
private passport: PassportStatic = passport;
|
|
23
23
|
|
|
24
|
+
private loginSuccessRedirectPath = "";
|
|
25
|
+
private loginFailedRedirectPath = "";
|
|
26
|
+
|
|
24
27
|
constructor(config: passportFactoryConfig ) {
|
|
25
28
|
|
|
26
29
|
this.config = config;
|
|
@@ -30,6 +33,9 @@ export default class OAuthRouteFactory {
|
|
|
30
33
|
failureRedirect: ""
|
|
31
34
|
};
|
|
32
35
|
|
|
36
|
+
this.loginSuccessRedirectPath = path.posix.join("/", process.env.LOGIN_SUCCESS_REDIRECT_PATH || "/logincallback");
|
|
37
|
+
this.loginFailedRedirectPath = path.posix.join("/", process.env.LOGIN_FAILED_REDIRECT_PATH || "/logincallback");
|
|
38
|
+
|
|
33
39
|
this.initPassport(this.config.strategy);
|
|
34
40
|
this.initRoutes();
|
|
35
41
|
|
|
@@ -40,23 +46,49 @@ export default class OAuthRouteFactory {
|
|
|
40
46
|
this.passport.initialize();
|
|
41
47
|
}
|
|
42
48
|
|
|
49
|
+
|
|
43
50
|
private initRoutes(){
|
|
44
|
-
// redirect to login
|
|
51
|
+
// redirect to provider's login page
|
|
45
52
|
this.router.get("/",
|
|
46
53
|
this.passport.authenticate(this.config.strategyName, this.config.authenticateOptions)
|
|
47
54
|
);
|
|
48
55
|
|
|
49
|
-
// back from login
|
|
56
|
+
// back from provider's login page
|
|
57
|
+
// insert temporary sessionCode to database
|
|
50
58
|
this.router.get("/callback",
|
|
51
59
|
this.passport.authenticate(this.config.strategyName, this.config.authenticateOptions),
|
|
52
60
|
(req, res) => {
|
|
53
|
-
const
|
|
54
|
-
|
|
61
|
+
const { state, error } = req.query;
|
|
62
|
+
|
|
63
|
+
if(error){
|
|
64
|
+
return res.redirect(`${this.loginFailedRedirectPath}?error=${error}`);
|
|
65
|
+
}
|
|
66
|
+
else if(state){
|
|
67
|
+
return res.redirect(`${this.loginFailedRedirectPath}?state=${state}`);
|
|
68
|
+
}
|
|
69
|
+
else if(!req.user){
|
|
70
|
+
return res.redirect(`${this.loginFailedRedirectPath}?error=invalid user`);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const sessionCode = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
|
|
74
|
+
|
|
75
|
+
SessionModel.create({
|
|
76
|
+
sessionCode: sessionCode,
|
|
77
|
+
// @ts-expect-error custom var
|
|
78
|
+
userId: req.user.profile._id,
|
|
79
|
+
// @ts-expect-error custom var
|
|
80
|
+
provider: req.user.provider || "",
|
|
81
|
+
expired: Date.now() + 5000
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
// dummy code, need client side key's encoding
|
|
85
|
+
|
|
86
|
+
// return appAuthCode to client
|
|
87
|
+
res.redirect(`${this.loginSuccessRedirectPath}?code=${sessionCode}`);
|
|
55
88
|
}
|
|
56
89
|
);
|
|
57
90
|
|
|
58
91
|
}
|
|
59
|
-
|
|
60
92
|
public getRouter() {
|
|
61
93
|
return this.router;
|
|
62
94
|
}
|
|
@@ -8,7 +8,7 @@ export default class VexDbConnector {
|
|
|
8
8
|
private mongoUrl: string;
|
|
9
9
|
private sqlUrl: string;
|
|
10
10
|
|
|
11
|
-
private recordAccessLog: boolean =
|
|
11
|
+
private recordAccessLog: boolean = false;
|
|
12
12
|
|
|
13
13
|
constructor(options:{
|
|
14
14
|
mongoUrl?: string;
|
|
@@ -65,7 +65,7 @@ export default class VexDbConnector {
|
|
|
65
65
|
middleware(req: Request, res: Response, next: NextFunction) {
|
|
66
66
|
if (mongoose.connection.readyState !== 1) {
|
|
67
67
|
vex.response.send(res, 503, {
|
|
68
|
-
|
|
68
|
+
code: vex.response.code.DB_CONN_ERR,
|
|
69
69
|
});
|
|
70
70
|
}
|
|
71
71
|
else if (this.recordAccessLog){
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// {{headerComment}}
|
|
2
|
+
|
|
3
|
+
import { Request, Response } from "express";
|
|
4
|
+
import vex from "./../_utils/index.gen";
|
|
5
|
+
import { VexResponseError } from "../_utils/response.gen";
|
|
6
|
+
import responseCode from "../_types/response/responseCode.gen";
|
|
7
|
+
|
|
8
|
+
export default class VexSystem {
|
|
9
|
+
|
|
10
|
+
constructor() {
|
|
11
|
+
// Bind the middleware method to the instance
|
|
12
|
+
this.RouteHandler = this.RouteHandler.bind(this);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* System Middleware
|
|
17
|
+
* Feature:
|
|
18
|
+
* - error handling
|
|
19
|
+
**/
|
|
20
|
+
public RouteHandler(req: Request, res: Response, handler: (req: Request, res: Response) => any) {
|
|
21
|
+
return handler(req, res).catch((err: any) => {
|
|
22
|
+
|
|
23
|
+
if ( err instanceof VexResponseError ) {
|
|
24
|
+
return vex.response.send(res, err.status, {
|
|
25
|
+
code: err.ret_code,
|
|
26
|
+
message: err.message
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
return vex.response.send(res, 500, {
|
|
31
|
+
code: responseCode.SERVER_ERROR,
|
|
32
|
+
message: err.message || "Internal Server Error"
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { responseMsg } from "./responseMsg.gen";
|
|
2
2
|
export { responseCode, ResponseCode } from "./responseCode.gen";
|
|
3
|
-
export {
|
|
3
|
+
export { responseStatusCodeMap } from "./responseStatusCodeMap.gen";
|
|
4
4
|
|
|
5
5
|
export interface responseObject<T>{
|
|
6
6
|
ret_code : number,
|
|
@@ -3,7 +3,9 @@ import { responseMsg } from "./responseMsg.gen";
|
|
|
3
3
|
/** custom response code **/
|
|
4
4
|
export type ResponseCode = keyof typeof responseMsg;
|
|
5
5
|
|
|
6
|
-
/**
|
|
6
|
+
/**
|
|
7
|
+
* response code of response message
|
|
8
|
+
**/
|
|
7
9
|
export const responseCode = Object.keys(responseMsg).reduce((acc, key) => {
|
|
8
10
|
acc[key] = key as ResponseCode;
|
|
9
11
|
return acc;
|
|
@@ -1,8 +1,15 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* default response message
|
|
2
|
+
* default response message by response code
|
|
3
|
+
* { code: message }
|
|
3
4
|
**/
|
|
4
5
|
export const responseMsg = {
|
|
5
|
-
|
|
6
|
+
|
|
7
|
+
DB_CONN_ERR: "Database connection error",
|
|
8
|
+
SERVER_ERROR: "Unknown Server Error",
|
|
9
|
+
|
|
10
|
+
success: "Success",
|
|
11
|
+
|
|
12
|
+
err_permission: "Permission Denied",
|
|
6
13
|
|
|
7
14
|
err_payload: "Invalid Request Payload",
|
|
8
15
|
err_query: "Invalid Request Query",
|
|
@@ -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 responseStatusCodeMap = new Map<number, string>();
|
|
8
|
+
// responseStatusCodeMap.set(100, "Continue");
|
|
9
|
+
// responseStatusCodeMap.set(101, "Switching Protocols");
|
|
10
|
+
// responseStatusCodeMap.set(102, "Processing");
|
|
11
|
+
// responseStatusCodeMap.set(103, "Early Hints");
|
|
12
|
+
responseStatusCodeMap.set(200, responseCode.success);
|
|
13
|
+
responseStatusCodeMap.set(201, responseCode.success);
|
|
14
|
+
responseStatusCodeMap.set(202, responseCode.success);
|
|
15
|
+
// responseStatusCodeMap.set(203, "Non-Authoritative Information");
|
|
16
|
+
// responseStatusCodeMap.set(204, "No Content");
|
|
17
|
+
// responseStatusCodeMap.set(205, "Reset Content");
|
|
18
|
+
// responseStatusCodeMap.set(206, "Partial Content");
|
|
19
|
+
// responseStatusCodeMap.set(207, "Multi-Status");
|
|
20
|
+
// responseStatusCodeMap.set(208, "Already Reported");
|
|
21
|
+
// responseStatusCodeMap.set(226, "IM Used");
|
|
22
|
+
// responseStatusCodeMap.set(300, "Multiple Choices");
|
|
23
|
+
// responseStatusCodeMap.set(301, "Moved Permanently");
|
|
24
|
+
// responseStatusCodeMap.set(302, "Found");
|
|
25
|
+
// responseStatusCodeMap.set(303, "See Other");
|
|
26
|
+
// responseStatusCodeMap.set(304, "Not Modified");
|
|
27
|
+
// responseStatusCodeMap.set(307, "Temporary Redirect");
|
|
28
|
+
// responseStatusCodeMap.set(308, "Permanent Redirect");
|
|
29
|
+
responseStatusCodeMap.set(400, responseCode.err_payload);
|
|
30
|
+
// responseStatusCodeMap.set(401, responseCode.err_permission);
|
|
31
|
+
// responseStatusCodeMap.set(402, "Payment Required");
|
|
32
|
+
// responseStatusCodeMap.set(403, "Forbidden");
|
|
33
|
+
// responseStatusCodeMap.set(404, "Not Found");
|
|
34
|
+
// responseStatusCodeMap.set(405, "Method Not Allowed");
|
|
35
|
+
// responseStatusCodeMap.set(406, "Not Acceptable");
|
|
36
|
+
// responseStatusCodeMap.set(407, "Proxy Authentication Required");
|
|
37
|
+
// responseStatusCodeMap.set(408, "Request Timeout");
|
|
38
|
+
// responseStatusCodeMap.set(409, "Conflict");
|
|
39
|
+
// responseStatusCodeMap.set(410, "Gone");
|
|
40
|
+
// responseStatusCodeMap.set(411, "Length Required");
|
|
41
|
+
// responseStatusCodeMap.set(412, "Precondition Failed");
|
|
42
|
+
// responseStatusCodeMap.set(413, "Content Too Large");
|
|
43
|
+
// responseStatusCodeMap.set(414, "URI Too Long");
|
|
44
|
+
// responseStatusCodeMap.set(415, "Unsupported Media Type");
|
|
45
|
+
// responseStatusCodeMap.set(416, "Range Not Satisfiable");
|
|
46
|
+
// responseStatusCodeMap.set(417, "Expectation Failed");
|
|
47
|
+
// responseStatusCodeMap.set(418, "I'm a teapot");
|
|
48
|
+
// responseStatusCodeMap.set(421, "Misdirected Request");
|
|
49
|
+
// responseStatusCodeMap.set(422, "Unprocessable Content");
|
|
50
|
+
// responseStatusCodeMap.set(423, "Locked");
|
|
51
|
+
// responseStatusCodeMap.set(424, "Failed Dependency");
|
|
52
|
+
// responseStatusCodeMap.set(425, "Too Early");
|
|
53
|
+
// responseStatusCodeMap.set(426, "Upgrade Required");
|
|
54
|
+
// responseStatusCodeMap.set(428, "Precondition Required");
|
|
55
|
+
// responseStatusCodeMap.set(429, "Too Many Requests");
|
|
56
|
+
// responseStatusCodeMap.set(431, "Request Header Fields Too Large");
|
|
57
|
+
// responseStatusCodeMap.set(451, "Unavailable For Legal Reasons");
|
|
58
|
+
// responseStatusCodeMap.set(500, "Internal Server Error");
|
|
59
|
+
// responseStatusCodeMap.set(501, "Not Implemented");
|
|
60
|
+
// responseStatusCodeMap.set(502, "Bad Gateway");
|
|
61
|
+
// responseStatusCodeMap.set(503, "Service Unavailable");
|
|
62
|
+
// responseStatusCodeMap.set(504, "Gateway Timeout");
|
|
63
|
+
// responseStatusCodeMap.set(505, "HTTP Version Not Supported");
|
|
64
|
+
// responseStatusCodeMap.set(506, "Variant Also Negotiates");
|
|
65
|
+
// responseStatusCodeMap.set(507, "Insufficient Storage");
|
|
66
|
+
// responseStatusCodeMap.set(508, "Loop Detected");
|
|
67
|
+
// responseStatusCodeMap.set(510, "Not Extended");
|
|
68
|
+
// responseStatusCodeMap.set(511, "Network Authentication Required");
|
|
69
|
+
|
|
70
|
+
export default responseStatusCodeMap;
|
|
@@ -1,17 +1,11 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
1
|
import logger from "./logger.gen";
|
|
4
2
|
import response from "./response.gen";
|
|
5
3
|
import validator from "./validator.gen";
|
|
6
|
-
import { responseMsg, responseCode, responseStatusToCode } from "./../_types/response/index.gen";
|
|
7
4
|
import common from "./common.gen";
|
|
8
5
|
|
|
9
6
|
export default {
|
|
10
7
|
log : logger,
|
|
11
8
|
response,
|
|
12
9
|
validator,
|
|
13
|
-
responseMsg,
|
|
14
|
-
responseCode,
|
|
15
|
-
responseStatusToCode,
|
|
16
10
|
common
|
|
17
11
|
};
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { Response } from "express";
|
|
2
|
-
import {
|
|
2
|
+
import { responseMsg, responseCode, responseStatusCodeMap, type ResponseCode } from "./../_types/response/index.gen";
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* @param res express response object
|
|
6
6
|
* @param status http response code
|
|
7
|
-
* @param code
|
|
8
|
-
* @param message response
|
|
9
|
-
* @param result response data
|
|
7
|
+
* @param code response code
|
|
8
|
+
* @param message response message, default is response message by response code
|
|
9
|
+
* @param result response data
|
|
10
10
|
* @returns express response object
|
|
11
11
|
*/
|
|
12
12
|
export function send<T = undefined>(
|
|
@@ -18,15 +18,19 @@ export function send<T = undefined>(
|
|
|
18
18
|
result?: T,
|
|
19
19
|
}
|
|
20
20
|
): Response<any, Record<string, any>> {
|
|
21
|
-
const
|
|
22
|
-
const msg :string | undefined = body?.message || (code ? responseMsg[code] : undefined);
|
|
23
|
-
const noBody = !code && !msg && !body?.result;
|
|
21
|
+
const noBody = !body || (body.code === undefined && body.message === undefined && body.result === undefined);
|
|
24
22
|
|
|
25
23
|
if(noBody){
|
|
26
24
|
return res.status(status).send();
|
|
27
25
|
}
|
|
28
26
|
else{
|
|
27
|
+
const code :ResponseCode | undefined = body?.code ?? responseStatusCodeMap.get(status) as ResponseCode | undefined;
|
|
28
|
+
const msg :string | undefined = body?.message ?? (code ? responseMsg[code] : undefined);
|
|
29
|
+
|
|
29
30
|
return res.status(status)
|
|
31
|
+
.header({
|
|
32
|
+
"Content-Type": "application/json",
|
|
33
|
+
})
|
|
30
34
|
.json({
|
|
31
35
|
ret_code: code,
|
|
32
36
|
ret_msg: msg,
|
|
@@ -36,6 +40,34 @@ export function send<T = undefined>(
|
|
|
36
40
|
}
|
|
37
41
|
}
|
|
38
42
|
|
|
43
|
+
export interface responseObject<T>{
|
|
44
|
+
ret_code : number,
|
|
45
|
+
ret_msg : string,
|
|
46
|
+
ret_time?: number,
|
|
47
|
+
result: T,
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export class VexResponseError extends Error {
|
|
51
|
+
public status: number;
|
|
52
|
+
public ret_code: ResponseCode;
|
|
53
|
+
public ret_msg: any;
|
|
54
|
+
|
|
55
|
+
constructor(
|
|
56
|
+
status: number = 200,
|
|
57
|
+
code?: ResponseCode,
|
|
58
|
+
message?: string,
|
|
59
|
+
) {
|
|
60
|
+
super(message);
|
|
61
|
+
this.name = "VexResponseError";
|
|
62
|
+
this.status = status;
|
|
63
|
+
this.ret_code = code || responseCode.SERVER_ERROR;
|
|
64
|
+
this.ret_msg = message || responseMsg.SERVER_ERROR;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
39
68
|
export default {
|
|
40
|
-
send
|
|
69
|
+
send,
|
|
70
|
+
msg: responseMsg,
|
|
71
|
+
code: responseCode,
|
|
72
|
+
statusCodeMap: responseStatusCodeMap,
|
|
41
73
|
};
|