@asapjs/router 0.0.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 (40) hide show
  1. package/.prettierrc +8 -0
  2. package/dist/assets/default-swagger.json +60 -0
  3. package/dist/express/router.d.ts +38 -0
  4. package/dist/express/router.d.ts.map +1 -0
  5. package/dist/express/router.js +138 -0
  6. package/dist/express/router.js.map +1 -0
  7. package/dist/index.d.ts +1 -0
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +1 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/middleware/errorHandler.d.ts +9 -0
  12. package/dist/middleware/errorHandler.d.ts.map +1 -0
  13. package/dist/middleware/errorHandler.js +17 -0
  14. package/dist/middleware/errorHandler.js.map +1 -0
  15. package/dist/middleware/jwtVerification.d.ts +11 -0
  16. package/dist/middleware/jwtVerification.d.ts.map +1 -0
  17. package/dist/middleware/jwtVerification.js +38 -0
  18. package/dist/middleware/jwtVerification.js.map +1 -0
  19. package/dist/router/index.d.ts +9 -0
  20. package/dist/router/index.d.ts.map +1 -0
  21. package/dist/router/index.js +62 -0
  22. package/dist/router/index.js.map +1 -0
  23. package/dist/swagger/index.d.ts +4 -0
  24. package/dist/swagger/index.d.ts.map +1 -0
  25. package/dist/swagger/index.js +64 -0
  26. package/dist/swagger/index.js.map +1 -0
  27. package/dist/utils/wrapper.d.ts +5 -0
  28. package/dist/utils/wrapper.d.ts.map +1 -0
  29. package/dist/utils/wrapper.js +40 -0
  30. package/dist/utils/wrapper.js.map +1 -0
  31. package/package.json +35 -0
  32. package/src/assets/default-swagger.json +60 -0
  33. package/src/express/router.ts +188 -0
  34. package/src/index.ts +0 -0
  35. package/src/middleware/errorHandler.ts +20 -0
  36. package/src/middleware/jwtVerification.ts +46 -0
  37. package/src/router/index.ts +62 -0
  38. package/src/swagger/index.ts +52 -0
  39. package/src/utils/wrapper.ts +28 -0
  40. package/tsconfig.json +21 -0
package/.prettierrc ADDED
@@ -0,0 +1,8 @@
1
+ {
2
+ "singleQuote": true,
3
+ "semi": true,
4
+ "useTabs": false,
5
+ "tabWidth": 2,
6
+ "trailingComma": "all",
7
+ "printWidth": 120
8
+ }
@@ -0,0 +1,60 @@
1
+ {
2
+ "openapi": "3.0.0",
3
+ "servers": [
4
+ {
5
+ "url": "https://ms.dev.pangaiacreators.com/shop",
6
+ "description": "pangaia-b4c-ms-shop-dev",
7
+ "variables": {}
8
+ },
9
+ {
10
+ "url": "https://ms.stg.pangaiacreators.com/shop",
11
+ "description": "pangaia-b4c-ms-shop-stg",
12
+ "variables": {}
13
+ },
14
+ {
15
+ "url": "http://localhost:3000/shop",
16
+ "description": "localhost",
17
+ "variables": {}
18
+ }
19
+ ],
20
+ "info": {
21
+ "version": "0.0.1",
22
+ "title": "pangaia-b4c-ms-shop",
23
+ "description": "",
24
+ "termsOfService": "",
25
+ "contact": {},
26
+ "license": {
27
+ "name": ""
28
+ }
29
+ },
30
+ "paths": {},
31
+ "components": {
32
+ "schemas": {},
33
+ "securitySchemes": {
34
+ "bearerAuth": {
35
+ "type": "http",
36
+ "scheme": "bearer",
37
+ "bearerFormat": "JWT"
38
+ },
39
+ "OAuthLogin": {
40
+ "type": "oauth2",
41
+ "flows": {
42
+ "password": {
43
+ "tokenUrl": "https://ms.dev.pangaiacreators.com/auth/signin",
44
+ "scopes": {}
45
+ }
46
+ }
47
+ }
48
+ }
49
+ },
50
+ "security": [
51
+ {
52
+ "OAuthLogin": []
53
+ }
54
+ ],
55
+ "tags": [],
56
+ "externalDocs": {
57
+ "url": "",
58
+ "description": ""
59
+ }
60
+ }
@@ -0,0 +1,38 @@
1
+ interface IPreference {
2
+ path: string;
3
+ title?: string;
4
+ auth?: boolean;
5
+ request?: returnTypeFunc;
6
+ response?: returnTypeFunc;
7
+ query?: () => any;
8
+ middleware?: any[];
9
+ excute: any;
10
+ }
11
+ export default class RouterController {
12
+ basePath: string;
13
+ expressRouter: import("express-serve-static-core").Router;
14
+ private generateRequestBody;
15
+ private generateFileRequestBody;
16
+ private generateResponseBody;
17
+ private generateSwaggerDefaultsSet;
18
+ excute: (method: 'get' | 'post' | 'put' | 'delete') => (options: IPreference) => void;
19
+ router: {
20
+ get: (options: IPreference) => void;
21
+ post: (options: IPreference) => void;
22
+ put: (options: IPreference) => void;
23
+ delete: (options: IPreference) => void;
24
+ };
25
+ }
26
+ interface AsConstructor<T> {
27
+ new (): T;
28
+ }
29
+ declare type returnTypeBodyOrQuery = 'body' | 'query';
30
+ declare type returnTypeFuncReturn = {
31
+ type: returnTypeBodyOrQuery;
32
+ data: any;
33
+ } | undefined | true;
34
+ declare type returnTypeFunc = () => returnTypeFuncReturn;
35
+ export declare const requestType: (Dto: AsConstructor<any> | true, innerType?: returnTypeBodyOrQuery | undefined, isArray?: boolean | undefined) => returnTypeFunc;
36
+ export declare const responseType: (Dto: AsConstructor<any> | true, innerType?: returnTypeBodyOrQuery | undefined, isArray?: boolean | undefined) => returnTypeFunc;
37
+ export {};
38
+ //# sourceMappingURL=router.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../../src/express/router.ts"],"names":[],"mappings":"AAKA,UAAU,WAAW;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,OAAO,CAAC,EAAE,cAAc,CAAC;IACzB,QAAQ,CAAC,EAAE,cAAc,CAAC;IAC1B,KAAK,CAAC,EAAE,MAAM,GAAG,CAAC;IAClB,UAAU,CAAC,EAAE,GAAG,EAAE,CAAC;IACnB,MAAM,EAAE,GAAG,CAAC;CACb;AASD,MAAM,CAAC,OAAO,OAAO,gBAAgB;IAC5B,QAAQ,SAAO;IAEf,aAAa,6CAAmB;IAEvC,OAAO,CAAC,mBAAmB,CAUxB;IAEH,OAAO,CAAC,uBAAuB,CAc5B;IAEH,OAAO,CAAC,oBAAoB,CAezB;IAEH,OAAO,CAAC,0BAA0B,CAgEhC;IAEK,MAAM,WAAY,KAAK,GAAG,MAAM,GAAG,KAAK,GAAG,QAAQ,eAAe,WAAW,UAOlF;IAEK,MAAM;uBAT4D,WAAW;wBAAX,WAAW;uBAAX,WAAW;0BAAX,WAAW;MAclF;CACH;AAED,UAAU,aAAa,CAAC,CAAC;IACvB,QAAQ,CAAC,CAAC;CACX;AAED,aAAK,qBAAqB,GAAG,MAAM,GAAG,OAAO,CAAC;AAE9C,aAAK,oBAAoB,GACrB;IACE,IAAI,EAAE,qBAAqB,CAAC;IAC5B,IAAI,EAAE,GAAG,CAAC;CACX,GACD,SAAS,GACT,IAAI,CAAC;AAET,aAAK,cAAc,GAAG,MAAM,oBAAoB,CAAC;AAgBjD,eAAO,MAAM,WAAW,QAZb,cAAc,GAAG,CAAC,GAAG,IAAI,mFAA2D,cAY/C,CAAC;AACjD,eAAO,MAAM,YAAY,QAbd,cAAc,GAAG,CAAC,GAAG,IAAI,mFAA2D,cAa7C,CAAC"}
@@ -0,0 +1,138 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.responseType = exports.requestType = void 0;
7
+ const express_1 = require("express");
8
+ const swagger_1 = require("../swagger");
9
+ const jwtVerification_1 = __importDefault(require("../middleware/jwtVerification"));
10
+ class RouterController {
11
+ constructor() {
12
+ this.basePath = '/';
13
+ this.expressRouter = (0, express_1.Router)();
14
+ this.generateRequestBody = (req) => ({
15
+ required: true,
16
+ content: {
17
+ 'application/json': {
18
+ schema: {
19
+ type: 'string',
20
+ example: req,
21
+ },
22
+ },
23
+ },
24
+ });
25
+ this.generateFileRequestBody = () => ({
26
+ content: {
27
+ 'multipart/form-data': {
28
+ schema: {
29
+ type: 'object',
30
+ properties: {
31
+ file: {
32
+ type: 'string',
33
+ format: 'binary',
34
+ },
35
+ },
36
+ },
37
+ },
38
+ },
39
+ });
40
+ this.generateResponseBody = (res) => ({
41
+ '200': {
42
+ description: '',
43
+ headers: {},
44
+ content: {
45
+ 'application/json': {
46
+ schema: {
47
+ type: 'string',
48
+ example: {
49
+ result: res,
50
+ },
51
+ },
52
+ },
53
+ },
54
+ },
55
+ });
56
+ this.generateSwaggerDefaultsSet = (target, title, path, method, req, res) => {
57
+ var _a, _b, _c, _d;
58
+ const swaggerPath = path === '/' ? target.basePath : target.basePath + path;
59
+ const realPath = swaggerPath.includes(':')
60
+ ? swaggerPath
61
+ .split('/')
62
+ .map((v) => (v.includes(':') ? `{${v.replace(':', '')}}` : v))
63
+ .join('/')
64
+ : swaggerPath;
65
+ const parameters = [];
66
+ swaggerPath
67
+ .split('/')
68
+ .forEach((v) => v.includes(':') &&
69
+ parameters.push({ in: 'path', name: v.replace(':', ''), required: true, schema: { type: 'string' } }));
70
+ const result = {
71
+ operationId: `${method}:${realPath}`,
72
+ path: realPath,
73
+ method,
74
+ tags: [target.tag],
75
+ summary: title,
76
+ description: '',
77
+ };
78
+ if (req === undefined) {
79
+ }
80
+ else if (req === true) {
81
+ result.requestBody = this.generateRequestBody(req);
82
+ }
83
+ else if (req.type === 'query') {
84
+ Object.keys(req.data).forEach((key) => {
85
+ parameters.push({
86
+ in: 'query',
87
+ name: key,
88
+ schema: {
89
+ type: 'string',
90
+ },
91
+ });
92
+ });
93
+ }
94
+ else if (((_d = (_a = req === null || req === void 0 ? void 0 : req.data) === null || _a === void 0 ? void 0 : _a[(_c = (_b = Object === null || Object === void 0 ? void 0 : Object.keys) === null || _b === void 0 ? void 0 : _b.call(Object, req === null || req === void 0 ? void 0 : req.data)) === null || _c === void 0 ? void 0 : _c[0]]) === null || _d === void 0 ? void 0 : _d.format) === 'binary') {
95
+ result.requestBody = this.generateFileRequestBody();
96
+ }
97
+ else if (req) {
98
+ result.requestBody = this.generateRequestBody(req.data);
99
+ }
100
+ if (res === undefined) {
101
+ }
102
+ else if (res) {
103
+ result.responses = this.generateResponseBody(res === true ? true : res.data);
104
+ }
105
+ if (parameters.length > 0) {
106
+ result.parameters = parameters;
107
+ }
108
+ return result;
109
+ };
110
+ this.excute = (method) => (options) => {
111
+ const { path, middleware = [], auth = false, excute, title, request, response } = options;
112
+ const requestType = request === null || request === void 0 ? void 0 : request();
113
+ const responseType = response === null || response === void 0 ? void 0 : response();
114
+ const swaggerPathInfo = this.generateSwaggerDefaultsSet(this, title || '', path, method, requestType, responseType);
115
+ (0, swagger_1.addPaths)(swaggerPathInfo);
116
+ this.expressRouter[method](path, (0, jwtVerification_1.default)(auth), ...middleware, excute);
117
+ };
118
+ this.router = {
119
+ get: this.excute('get'),
120
+ post: this.excute('post'),
121
+ put: this.excute('put'),
122
+ delete: this.excute('delete'),
123
+ };
124
+ }
125
+ }
126
+ exports.default = RouterController;
127
+ const returnType = (type) => (Dto, innerType = 'body', isArray = false) => () => {
128
+ if (Dto === undefined)
129
+ return undefined;
130
+ if (Dto === true)
131
+ return true;
132
+ const dto = new Dto().swagger();
133
+ const data = isArray ? [dto] : dto;
134
+ return { type: innerType, data };
135
+ };
136
+ exports.requestType = returnType('request');
137
+ exports.responseType = returnType('response');
138
+ //# sourceMappingURL=router.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"router.js","sourceRoot":"","sources":["../../src/express/router.ts"],"names":[],"mappings":";;;;;;AAAA,qCAAkD;AAElD,wCAAsC;AACtC,oFAA4D;AAoB5D,MAAqB,gBAAgB;IAArC;QACS,aAAQ,GAAG,GAAG,CAAC;QAEf,kBAAa,GAAG,IAAA,gBAAa,GAAE,CAAC;QAE/B,wBAAmB,GAAG,CAAC,GAAQ,EAAE,EAAE,CAAC,CAAC;YAC3C,QAAQ,EAAE,IAAI;YACd,OAAO,EAAE;gBACP,kBAAkB,EAAE;oBAClB,MAAM,EAAE;wBACN,IAAI,EAAE,QAAQ;wBACd,OAAO,EAAE,GAAG;qBACb;iBACF;aACF;SACF,CAAC,CAAC;QAEK,4BAAuB,GAAG,GAA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,GAAG,UAAU,EAAE,MAAM,CAAC,CAAC;QACjF,CAAC,CAAC;QAEK,WAAM,GAAG;YACd,GAAG,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC;YACvB,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC;YACzB,GAAG,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC;YACvB,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC;SAC9B,CAAC;IACJ,CAAC;CAAA;AAnID,mCAmIC;AAsBD,MAAM,UAAU,GACd,CAAC,IAAI,EAAE,EAAE,CACT,CAAC,GAAG,EAAE,SAAS,GAAG,MAAM,EAAE,OAAO,GAAG,KAAK,EAAE,EAAE,CAC7C,GAAG,EAAE;IACH,IAAI,GAAG,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IACxC,IAAI,GAAG,KAAK,IAAI;QAAE,OAAO,IAAI,CAAC;IAC9B,MAAM,GAAG,GAAG,IAAI,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC;IAChC,MAAM,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;IACnC,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;AACnC,CAAC,CAAC;AACS,QAAA,WAAW,GAAG,UAAU,CAAC,SAAS,CAAC,CAAC;AACpC,QAAA,YAAY,GAAG,UAAU,CAAC,UAAU,CAAC,CAAC"}
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":""}
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":""}
@@ -0,0 +1,9 @@
1
+ import { NextFunction, Request, Response } from 'express';
2
+ export declare class HttpException extends Error {
3
+ status: number;
4
+ message: string;
5
+ constructor(status?: number, message?: string);
6
+ }
7
+ declare const errorHandler: (error: HttpException, req: Request, res: Response, next: NextFunction) => void;
8
+ export default errorHandler;
9
+ //# sourceMappingURL=errorHandler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errorHandler.d.ts","sourceRoot":"","sources":["../../src/middleware/errorHandler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAE1D,qBAAa,aAAc,SAAQ,KAAK;IAC/B,MAAM,EAAE,MAAM,CAAC;IAEf,OAAO,EAAE,MAAM,CAAC;gBAEX,MAAM,GAAE,MAAY,EAAE,OAAO,GAAE,MAAgC;CAK5E;AAED,QAAA,MAAM,YAAY,UAAW,aAAa,OAAO,OAAO,OAAO,QAAQ,QAAQ,YAAY,SAG1F,CAAC;AAEF,eAAe,YAAY,CAAC"}
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HttpException = void 0;
4
+ class HttpException extends Error {
5
+ constructor(status = 500, message = '알 수 없는 서버 오류가 발생했습니다.') {
6
+ super(message);
7
+ this.status = status;
8
+ this.message = message;
9
+ }
10
+ }
11
+ exports.HttpException = HttpException;
12
+ const errorHandler = (error, req, res, next) => {
13
+ const { status = 500, message } = error;
14
+ res.status(status).json({ status, message });
15
+ };
16
+ exports.default = errorHandler;
17
+ //# sourceMappingURL=errorHandler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errorHandler.js","sourceRoot":"","sources":["../../src/middleware/errorHandler.ts"],"names":[],"mappings":";;;AAEA,MAAa,aAAc,SAAQ,KAAK;IAKtC,YAAY,SAAiB,GAAG,EAAE,UAAkB,uBAAuB;QACzE,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;CACF;AAVD,sCAUC;AAED,MAAM,YAAY,GAAG,CAAC,KAAoB,EAAE,GAAY,EAAE,GAAa,EAAE,IAAkB,EAAE,EAAE;IAC7F,MAAM,EAAE,MAAM,GAAG,GAAG,EAAE,OAAO,EAAE,GAAG,KAAK,CAAC;IACxC,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,CAAC;AAC/C,CAAC,CAAC;AAEF,kBAAe,YAAY,CAAC"}
@@ -0,0 +1,11 @@
1
+ import { Request, Response, NextFunction } from 'express';
2
+ declare global {
3
+ namespace Express {
4
+ interface Request {
5
+ decoded: any;
6
+ }
7
+ }
8
+ }
9
+ declare const jwtVerification: (auth?: boolean) => (req: Request, res: Response, next: NextFunction) => void;
10
+ export default jwtVerification;
11
+ //# sourceMappingURL=jwtVerification.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jwtVerification.d.ts","sourceRoot":"","sources":["../../src/middleware/jwtVerification.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAK1D,OAAO,CAAC,MAAM,CAAC;IACb,UAAU,OAAO,CAAC;QAChB,UAAU,OAAO;YACf,OAAO,EAAE,GAAG,CAAC;SACd;KACF;CACF;AAED,QAAA,MAAM,eAAe,UACZ,OAAO,WACR,OAAO,OAAO,QAAQ,QAAQ,YAAY,SA0B/C,CAAC;AAEJ,eAAe,eAAe,CAAC"}
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const core_1 = require("@asapjs/core");
7
+ const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
8
+ const errorHandler_1 = require("./errorHandler");
9
+ const jwtVerification = (auth = false) => (req, res, next) => {
10
+ const { authorization } = req.headers;
11
+ if (!authorization) {
12
+ if (auth === true) {
13
+ throw new errorHandler_1.HttpException(403, 'NO Token Provided');
14
+ }
15
+ next();
16
+ }
17
+ else {
18
+ const token = authorization.split(' ')[1];
19
+ jsonwebtoken_1.default.verify(token, (0, core_1.getConfig)().JWT_SECRET, (err, decoded) => {
20
+ if (err && auth === true) {
21
+ if (err.message === 'invalid signature') {
22
+ return res.status(403).json({
23
+ error: true,
24
+ message: 'invaild signature. please use vaild endpoint',
25
+ });
26
+ }
27
+ return res.status(401).json({
28
+ error: true,
29
+ message: 'Unauthorized access. Please Refresh Token',
30
+ });
31
+ }
32
+ req.decoded = decoded;
33
+ next();
34
+ });
35
+ }
36
+ };
37
+ exports.default = jwtVerification;
38
+ //# sourceMappingURL=jwtVerification.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jwtVerification.js","sourceRoot":"","sources":["../../src/middleware/jwtVerification.ts"],"names":[],"mappings":";;;;;AAAA,uCAAyC;AAGzC,gEAA+B;AAE/B,iDAA+C;AAU/C,MAAM,eAAe,GACnB,CAAC,OAAgB,KAAK,EAAE,EAAE,CAC1B,CAAC,GAAY,EAAE,GAAa,EAAE,IAAkB,EAAE,EAAE;IAClD,MAAM,EAAE,aAAa,EAAE,GAAG,GAAG,CAAC,OAAO,CAAC;IACtC,IAAI,CAAC,aAAa,EAAE;QAClB,IAAI,IAAI,KAAK,IAAI,EAAE;YACjB,MAAM,IAAI,4BAAa,CAAC,GAAG,EAAE,mBAAmB,CAAC,CAAC;SACnD;QACD,IAAI,EAAE,CAAC;KACR;SAAM;QACL,MAAM,KAAK,GAAG,aAAa,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;QAC1C,sBAAG,CAAC,MAAM,CAAC,KAAK,EAAG,IAAA,gBAAS,GAAU,CAAC,UAAU,EAAE,CAAC,GAAQ,EAAE,OAAY,EAAE,EAAE;YAC5E,IAAI,GAAG,IAAI,IAAI,KAAK,IAAI,EAAE;gBACxB,IAAI,GAAG,CAAC,OAAO,KAAK,mBAAmB,EAAE;oBACvC,OAAO,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;wBAC1B,KAAK,EAAE,IAAI;wBACX,OAAO,EAAE,8CAA8C;qBACxD,CAAC,CAAC;iBACJ;gBACD,OAAO,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;oBAC1B,KAAK,EAAE,IAAI;oBACX,OAAO,EAAE,2CAA2C;iBACrD,CAAC,CAAC;aACJ;YACK,GAAI,CAAC,OAAO,GAAG,OAAO,CAAC;YAC7B,IAAI,EAAE,CAAC;QACT,CAAC,CAAC,CAAC;KACJ;AACH,CAAC,CAAC;AAEJ,kBAAe,eAAe,CAAC"}
@@ -0,0 +1,9 @@
1
+ import express from 'express';
2
+ export default class RouterModule {
3
+ private config;
4
+ app: express.Application;
5
+ constructor(dirname: string);
6
+ private initRouter;
7
+ private initMiddlewares;
8
+ }
9
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/router/index.ts"],"names":[],"mappings":"AAEA,OAAO,OAA8B,MAAM,SAAS,CAAC;AASrD,MAAM,CAAC,OAAO,OAAO,YAAY;IAC/B,OAAO,CAAC,MAAM,CAAM;IAEb,GAAG,EAAE,OAAO,CAAC,WAAW,CAAC;gBAEpB,OAAO,EAAE,MAAM;IAQ3B,OAAO,CAAC,UAAU;IAgClB,OAAO,CAAC,eAAe;CAKxB"}
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const core_1 = require("@asapjs/core");
16
+ const express_1 = __importDefault(require("express"));
17
+ const body_parser_1 = __importDefault(require("body-parser"));
18
+ const cors_1 = __importDefault(require("cors"));
19
+ const swagger_ui_express_1 = __importDefault(require("swagger-ui-express"));
20
+ const errorHandler_1 = __importDefault(require("../middleware/errorHandler"));
21
+ const wrapper_1 = __importDefault(require("../utils/wrapper"));
22
+ const swagger_1 = require("../swagger");
23
+ class RouterModule {
24
+ constructor(dirname) {
25
+ this.config = (0, core_1.getConfig)();
26
+ this.app = (0, express_1.default)();
27
+ this.initMiddlewares();
28
+ this.initRouter(dirname);
29
+ this.app.use(errorHandler_1.default);
30
+ }
31
+ initRouter(dirname) {
32
+ const router = express_1.default.Router();
33
+ const routes = require(`${dirname}/route`).default;
34
+ routes.forEach((route) => {
35
+ this.app.use(`/${this.config.basePath}${route.basePath}`, route.expressRouter || route.router);
36
+ });
37
+ this.app.use(router);
38
+ this.app.get(`/${this.config.basePath}`, (req, res) => {
39
+ res.send(`${this.config.name} server is working`);
40
+ });
41
+ this.app.get('/health-check', (req, res) => {
42
+ res.send(`${this.config.name} server is working`);
43
+ });
44
+ const options = {
45
+ swaggerOptions: {
46
+ url: `/${this.config.basePath}/docs/swagger.json`,
47
+ },
48
+ };
49
+ this.app.use(`/${this.config.basePath}/docs/swagger-ui.html`, swagger_ui_express_1.default.serveFiles(undefined, options), swagger_ui_express_1.default.setup(undefined, options));
50
+ this.app.get(`/${this.config.basePath}/docs/swagger.json`, (0, wrapper_1.default)((req, res) => __awaiter(this, void 0, void 0, function* () {
51
+ const swaggerData = (0, swagger_1.getSwaggerData)();
52
+ res.json(swaggerData);
53
+ })));
54
+ }
55
+ initMiddlewares() {
56
+ this.app.use((0, cors_1.default)());
57
+ this.app.use(body_parser_1.default.json());
58
+ this.app.use(body_parser_1.default.urlencoded({ extended: true }));
59
+ }
60
+ }
61
+ exports.default = RouterModule;
62
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/router/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,uCAAyC;AAEzC,sDAAqD;AACrD,8DAAqC;AACrC,gDAAwB;AACxB,4EAA2C;AAE3C,8EAAsD;AACtD,+DAAuC;AACvC,wCAA4C;AAE5C,MAAqB,YAAY;IAK/B,YAAY,OAAe;QACzB,IAAI,CAAC,MAAM,GAAG,IAAA,gBAAS,GAAE,CAAC;QAC1B,IAAI,CAAC,GAAG,GAAG,IAAA,iBAAO,GAAE,CAAC;QACrB,IAAI,CAAC,eAAe,EAAE,CAAC;QACvB,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;QACzB,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,sBAAY,CAAC,CAAC;IAC7B,CAAC;IAEO,UAAU,CAAC,OAAe;QAChC,MAAM,MAAM,GAAmB,iBAAO,CAAC,MAAM,EAAE,CAAC;QAChD,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,OAAO,QAAQ,CAAC,CAAC,OAAO,CAAC;QACnD,MAAM,CAAC,OAAO,CAAC,CAAC,KAAU,EAAE,EAAE;YAC5B,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,MAAM,CAAC,QAAQ,GAAG,KAAK,CAAC,QAAQ,EAAE,EAAE,KAAK,CAAC,aAAa,IAAI,KAAK,CAAC,MAAM,CAAC,CAAC;QACjG,CAAC,CAAC,CAAC;QACH,IAAI,CAAC,GAAG,CAAC,GAAG,CA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I,EAAE,CAAC,CAAC;QAChC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,qBAAU,CAAC,UAAU,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IAC1D,CAAC;CACF;AAlDD,+BAkDC"}
@@ -0,0 +1,4 @@
1
+ export declare const addPaths: (data: any) => Promise<void>, getSwaggerData: () => {
2
+ [key: string]: any;
3
+ } | null;
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/swagger/index.ts"],"names":[],"mappings":"AAmDA,eAAO,MAAQ,QAAQ,SAvCU,GAAG,oBAuCX,cAAc;;QAA0B,CAAC"}
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ var _a;
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.getSwaggerData = exports.addPaths = void 0;
17
+ /* eslint-disable no-nested-ternary */
18
+ const default_swagger_json_1 = __importDefault(require("../assets/default-swagger.json"));
19
+ const methods = ["get", "post", "put", "delete"];
20
+ class DocsApplication {
21
+ constructor() {
22
+ this.swaggerData = Object.assign({}, default_swagger_json_1.default);
23
+ this.swaggerPath = [];
24
+ this.generatedSwaggerData = null;
25
+ this.addPaths = (data) => __awaiter(this, void 0, void 0, function* () {
26
+ this.swaggerPath.push(data);
27
+ });
28
+ this.generateSwaggerData = () => {
29
+ this.swaggerPath.sort((a, b) => {
30
+ var _a, _b, _c, _d;
31
+ const ix1 = methods.indexOf(a.method.toLowerCase());
32
+ const ix2 = methods.indexOf(b.method.toLowerCase());
33
+ return (((_a = a.tags) === null || _a === void 0 ? void 0 : _a[0]) || 0) > (((_b = b.tags) === null || _b === void 0 ? void 0 : _b[0]) || 0)
34
+ ? 1
35
+ : (((_c = a.tags) === null || _c === void 0 ? void 0 : _c[0]) || 0) < (((_d = b.tags) === null || _d === void 0 ? void 0 : _d[0]) || 0)
36
+ ? -1
37
+ : a.path > b.path
38
+ ? 1
39
+ : a.path < b.path
40
+ ? -1
41
+ : ix1 > ix2
42
+ ? 1
43
+ : ix1 < ix2
44
+ ? -1
45
+ : 0;
46
+ });
47
+ this.swaggerPath.forEach((v) => {
48
+ var _a;
49
+ if (!this.swaggerData.paths[v.path])
50
+ this.swaggerData.paths[v.path] = {};
51
+ this.swaggerData.paths[v.path][(_a = v.method) === null || _a === void 0 ? void 0 : _a.toLowerCase()] = v;
52
+ });
53
+ this.generatedSwaggerData = Object.assign({}, this.swaggerData);
54
+ };
55
+ this.getSwaggerData = () => {
56
+ if (this.generatedSwaggerData === null) {
57
+ this.generateSwaggerData();
58
+ }
59
+ return this.generatedSwaggerData;
60
+ };
61
+ }
62
+ }
63
+ _a = new DocsApplication(), exports.addPaths = _a.addPaths, exports.getSwaggerData = _a.getSwaggerData;
64
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/swagger/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,sCAAsC;AACtC,0FAA4D;AAE5D,MAAM,OAAO,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC;AAEjD,MAAM,eAAe;IAArB;QACS,gBAAW,qBAAgC,8BAAc,EAAG;QAE3D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,CAAC,CAAC,CAAC;YAEH,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,CAAM,EAAE,EAAE;;gBAClC,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;oBAAE,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC;gBACzE,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,MAAA,CAAC,CAAC,MAAM,0CAAE,WAAW,EAAE,CAAC,GAAG,CAAC,CAAC;YAC9D,CAAC,CAAC,CAAC;YAEH,IAAI,CAAC,oBAAoB,qBAAQ,IAAI,CAAC,WAAW,CAAE,CAAC;QACtD,CAAC,CAAC;QAEK,mBAAc,GAAG,GAAG,EAAE;YAC3B,IAAI,IAAI,CAAC,oBAAoB,KAAK,IAAI,EAAE;gBACtC,IAAI,CAAC,mBAAmB,EAAE,CAAC;aAC5B;YACD,OAAO,IAAI,CAAC,oBAAoB,CAAC;QACnC,CAAC,CAAC;IACJ,CAAC;CAAA;AAEY,KAA+B,IAAI,eAAe,EAAE,EAAlD,gBAAQ,gBAAE,sBAAc,qBAA2B"}
@@ -0,0 +1,5 @@
1
+ import { NextFunction, Request, Response } from 'express';
2
+ declare type Callback = (request: Request<any, any, any, any>, response: Response, next: NextFunction) => Promise<unknown>;
3
+ export default function Wrapper(cb: Callback): Callback;
4
+ export {};
5
+ //# sourceMappingURL=wrapper.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wrapper.d.ts","sourceRoot":"","sources":["../../src/utils/wrapper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAG1D,aAAK,QAAQ,GAAG,CAAC,OAAO,EAAE,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,YAAY,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;AAEnH,MAAM,CAAC,OAAO,UAAU,OAAO,CAAC,EAAE,EAAE,QAAQ,GAAG,QAAQ,CAsBtD"}
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ const core_1 = require("@asapjs/core");
13
+ function Wrapper(cb) {
14
+ return function _Wrapper(req, res, next) {
15
+ return __awaiter(this, void 0, void 0, function* () {
16
+ try {
17
+ const result = yield cb(req, res, next);
18
+ return result;
19
+ }
20
+ catch (err) {
21
+ console.log(err);
22
+ core_1.logger.error('[SERVER ERROR]', err);
23
+ if (err.status === 500 || err.status === undefined) {
24
+ const status = 500;
25
+ const message = '알 수 없는 오류가 발생했습니다.';
26
+ return res.status(status).json({
27
+ status,
28
+ message,
29
+ });
30
+ }
31
+ return res.status(err.status).json({
32
+ status: err.status,
33
+ message: err.message,
34
+ });
35
+ }
36
+ });
37
+ };
38
+ }
39
+ exports.default = Wrapper;
40
+ //# sourceMappingURL=wrapper.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wrapper.js","sourceRoot":"","sources":["../../src/utils/wrapper.ts"],"names":[],"mappings":";;;;;;;;;;;AACA,uCAAsC;AAItC,SAAwB,OAAO,CAAC,EAAY;IAC1C,OAAO,SAAe,QAAQ,CAAC,GAAY,EAAE,GAAa,EAAE,IAAkB;;YAC5E,IAAI;gBACF,MAAM,MAAM,GAAG,MAAM,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;gBACxC,OAAO,MAAM,CAAC;aACf;YAAC,OAAO,GAAG,EAAE;gBACZ,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;gBACjB,aAAM,CAAC,KAAK,CAAC,gBAAgB,EAAE,GAAG,CAAC,CAAC;gBACpC,IAAI,GAAG,CAAC,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,MAAM,KAAK,SAAS,EAAE;oBAClD,MAAM,MAAM,GAAG,GAAG,CAAC;oBACnB,MAAM,OAAO,GAAG,oBAAoB,CAAC;oBACrC,OAAO,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC;wBAC7B,MAAM;wBACN,OAAO;qBACR,CAAC,CAAC;iBACJ;gBACD,OAAO,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC;oBACjC,MAAM,EAAE,GAAG,CAAC,MAAM;oBAClB,OAAO,EAAE,GAAG,CAAC,OAAO;iBACrB,CAAC,CAAC;aACJ;QACH,CAAC;KAAA,CAAC;AACJ,CAAC;AAtBD,0BAsBC"}
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "@asapjs/router",
3
+ "version": "0.0.1",
4
+ "description": "",
5
+ "main": "dist/index.js",
6
+ "scripts": {
7
+ "build": "./node_modules/typescript/bin/tsc",
8
+ "localinstall": "yarn build && cp -r ./dist /Users/seungmin/projects/pangaia/pangaia-b4c-ms-shop/node_modules/@asapjs/router/"
9
+ },
10
+ "author": "",
11
+ "license": "ISC",
12
+ "dependencies": {
13
+ "body-parser": "^1.19.2",
14
+ "cors": "^2.8.5",
15
+ "express": "^4.17.3",
16
+ "fs": "^0.0.1-security",
17
+ "jsonwebtoken": "^8.5.1",
18
+ "sequelize": "^6.17.0",
19
+ "sequelize-typescript": "^2.1.3",
20
+ "swagger-ui-express": "^4.3.0",
21
+ "winston": "^3.6.0"
22
+ },
23
+ "devDependencies": {
24
+ "@types/body-parser": "^1.19.2",
25
+ "@types/cors": "^2.8.12",
26
+ "@types/express": "^4.17.13",
27
+ "@types/jsonwebtoken": "^8.5.8",
28
+ "@types/node": "^17.0.21",
29
+ "@types/swagger-ui-express": "^4.1.3",
30
+ "typescript": "^4.6.2"
31
+ },
32
+ "peerDependencies": {
33
+ "@asapjs/core": "^0.0.6"
34
+ }
35
+ }
@@ -0,0 +1,60 @@
1
+ {
2
+ "openapi": "3.0.0",
3
+ "servers": [
4
+ {
5
+ "url": "https://ms.dev.pangaiacreators.com/shop",
6
+ "description": "pangaia-b4c-ms-shop-dev",
7
+ "variables": {}
8
+ },
9
+ {
10
+ "url": "https://ms.stg.pangaiacreators.com/shop",
11
+ "description": "pangaia-b4c-ms-shop-stg",
12
+ "variables": {}
13
+ },
14
+ {
15
+ "url": "http://localhost:3000/shop",
16
+ "description": "localhost",
17
+ "variables": {}
18
+ }
19
+ ],
20
+ "info": {
21
+ "version": "0.0.1",
22
+ "title": "pangaia-b4c-ms-shop",
23
+ "description": "",
24
+ "termsOfService": "",
25
+ "contact": {},
26
+ "license": {
27
+ "name": ""
28
+ }
29
+ },
30
+ "paths": {},
31
+ "components": {
32
+ "schemas": {},
33
+ "securitySchemes": {
34
+ "bearerAuth": {
35
+ "type": "http",
36
+ "scheme": "bearer",
37
+ "bearerFormat": "JWT"
38
+ },
39
+ "OAuthLogin": {
40
+ "type": "oauth2",
41
+ "flows": {
42
+ "password": {
43
+ "tokenUrl": "https://ms.dev.pangaiacreators.com/auth/signin",
44
+ "scopes": {}
45
+ }
46
+ }
47
+ }
48
+ }
49
+ },
50
+ "security": [
51
+ {
52
+ "OAuthLogin": []
53
+ }
54
+ ],
55
+ "tags": [],
56
+ "externalDocs": {
57
+ "url": "",
58
+ "description": ""
59
+ }
60
+ }
@@ -0,0 +1,188 @@
1
+ import { Router as ExpressRouter } from 'express';
2
+
3
+ import { addPaths } from '../swagger';
4
+ import jwtVerification from '../middleware/jwtVerification';
5
+
6
+ interface IPreference {
7
+ path: string;
8
+ title?: string;
9
+ auth?: boolean;
10
+ request?: returnTypeFunc;
11
+ response?: returnTypeFunc;
12
+ query?: () => any;
13
+ middleware?: any[];
14
+ excute: any;
15
+ }
16
+
17
+ interface ISwaggerParameter {
18
+ in: string;
19
+ name: string;
20
+ required?: boolean;
21
+ schema: { type: string };
22
+ }
23
+
24
+ export default class RouterController {
25
+ public basePath = '/';
26
+
27
+ public expressRouter = ExpressRouter();
28
+
29
+ private generateRequestBody = (req: any) => ({
30
+ required: true,
31
+ content: {
32
+ 'application/json': {
33
+ schema: {
34
+ type: 'string',
35
+ example: req,
36
+ },
37
+ },
38
+ },
39
+ });
40
+
41
+ private generateFileRequestBody = () => ({
42
+ content: {
43
+ 'multipart/form-data': {
44
+ schema: {
45
+ type: 'object',
46
+ properties: {
47
+ file: {
48
+ type: 'string',
49
+ format: 'binary',
50
+ },
51
+ },
52
+ },
53
+ },
54
+ },
55
+ });
56
+
57
+ private generateResponseBody = (res: any) => ({
58
+ '200': {
59
+ description: '',
60
+ headers: {},
61
+ content: {
62
+ 'application/json': {
63
+ schema: {
64
+ type: 'string',
65
+ example: {
66
+ result: res,
67
+ },
68
+ },
69
+ },
70
+ },
71
+ },
72
+ });
73
+
74
+ private generateSwaggerDefaultsSet = (
75
+ target: any,
76
+ title: string,
77
+ path: string,
78
+ method: string,
79
+ req: returnTypeFuncReturn,
80
+ res: returnTypeFuncReturn,
81
+ ) => {
82
+ const swaggerPath = path === '/' ? target.basePath : target.basePath + path;
83
+ const realPath = swaggerPath.includes(':')
84
+ ? swaggerPath
85
+ .split('/')
86
+ .map((v: string) => (v.includes(':') ? `{${v.replace(':', '')}}` : v))
87
+ .join('/')
88
+ : swaggerPath;
89
+
90
+ const parameters: ISwaggerParameter[] = [];
91
+
92
+ swaggerPath
93
+ .split('/')
94
+ .forEach(
95
+ (v: string) =>
96
+ v.includes(':') &&
97
+ parameters.push({ in: 'path', name: v.replace(':', ''), required: true, schema: { type: 'string' } }),
98
+ );
99
+
100
+ const result: { [key: string]: any } = {
101
+ operationId: `${method}:${realPath}`,
102
+ path: realPath,
103
+ method,
104
+ tags: [target.tag],
105
+ summary: title,
106
+ description: '',
107
+ };
108
+
109
+ if (req === undefined) {
110
+ } else if (req === true) {
111
+ result.requestBody = this.generateRequestBody(req);
112
+ } else if (req.type === 'query') {
113
+ Object.keys(req.data).forEach((key) => {
114
+ parameters.push({
115
+ in: 'query',
116
+ name: key,
117
+ schema: {
118
+ type: 'string',
119
+ },
120
+ });
121
+ });
122
+ } else if (req?.data?.[Object?.keys?.(req?.data)?.[0]]?.format === 'binary') {
123
+ result.requestBody = this.generateFileRequestBody();
124
+ } else if (req) {
125
+ result.requestBody = this.generateRequestBody(req.data);
126
+ }
127
+
128
+ if (res === undefined) {
129
+ } else if (res) {
130
+ result.responses = this.generateResponseBody(res === true ? true : res.data);
131
+ }
132
+
133
+ if (parameters.length > 0) {
134
+ result.parameters = parameters;
135
+ }
136
+
137
+ return result;
138
+ };
139
+
140
+ public excute = (method: 'get' | 'post' | 'put' | 'delete') => (options: IPreference) => {
141
+ const { path, middleware = [], auth = false, excute, title, request, response }: IPreference = options;
142
+ const requestType = request?.();
143
+ const responseType = response?.();
144
+ const swaggerPathInfo = this.generateSwaggerDefaultsSet(this, title || '', path, method, requestType, responseType);
145
+ addPaths(swaggerPathInfo);
146
+ this.expressRouter[method](path, jwtVerification(auth), ...middleware, excute);
147
+ };
148
+
149
+ public router = {
150
+ get: this.excute('get'),
151
+ post: this.excute('post'),
152
+ put: this.excute('put'),
153
+ delete: this.excute('delete'),
154
+ };
155
+ }
156
+
157
+ interface AsConstructor<T> {
158
+ new (): T;
159
+ }
160
+ type returnTypeReqOrRes = 'request' | 'response';
161
+ type returnTypeBodyOrQuery = 'body' | 'query';
162
+
163
+ type returnTypeFuncReturn =
164
+ | {
165
+ type: returnTypeBodyOrQuery;
166
+ data: any;
167
+ }
168
+ | undefined
169
+ | true;
170
+
171
+ type returnTypeFunc = () => returnTypeFuncReturn;
172
+
173
+ type returnTypeFuncPre = (
174
+ type: returnTypeReqOrRes,
175
+ ) => (Dto: AsConstructor<any> | true, innerType?: returnTypeBodyOrQuery, isArray?: boolean) => returnTypeFunc;
176
+
177
+ const returnType: returnTypeFuncPre =
178
+ (type) =>
179
+ (Dto, innerType = 'body', isArray = false) =>
180
+ () => {
181
+ if (Dto === undefined) return undefined;
182
+ if (Dto === true) return true;
183
+ const dto = new Dto().swagger();
184
+ const data = isArray ? [dto] : dto;
185
+ return { type: innerType, data };
186
+ };
187
+ export const requestType = returnType('request');
188
+ export const responseType = returnType('response');
package/src/index.ts ADDED
File without changes
@@ -0,0 +1,20 @@
1
+ import { NextFunction, Request, Response } from 'express';
2
+
3
+ export class HttpException extends Error {
4
+ public status: number;
5
+
6
+ public message: string;
7
+
8
+ constructor(status: number = 500, message: string = '알 수 없는 서버 오류가 발생했습니다.') {
9
+ super(message);
10
+ this.status = status;
11
+ this.message = message;
12
+ }
13
+ }
14
+
15
+ const errorHandler = (error: HttpException, req: Request, res: Response, next: NextFunction) => {
16
+ const { status = 500, message } = error;
17
+ res.status(status).json({ status, message });
18
+ };
19
+
20
+ export default errorHandler;
@@ -0,0 +1,46 @@
1
+ import { getConfig } from '@asapjs/core';
2
+
3
+ import { Request, Response, NextFunction } from 'express';
4
+ import jwt from 'jsonwebtoken';
5
+
6
+ import { HttpException } from './errorHandler';
7
+
8
+ declare global {
9
+ namespace Express {
10
+ interface Request {
11
+ decoded: any;
12
+ }
13
+ }
14
+ }
15
+
16
+ const jwtVerification =
17
+ (auth: boolean = false) =>
18
+ (req: Request, res: Response, next: NextFunction) => {
19
+ const { authorization } = req.headers;
20
+ if (!authorization) {
21
+ if (auth === true) {
22
+ throw new HttpException(403, 'NO Token Provided');
23
+ }
24
+ next();
25
+ } else {
26
+ const token = authorization.split(' ')[1];
27
+ jwt.verify(token, (getConfig() as any).JWT_SECRET, (err: any, decoded: any) => {
28
+ if (err && auth === true) {
29
+ if (err.message === 'invalid signature') {
30
+ return res.status(403).json({
31
+ error: true,
32
+ message: 'invaild signature. please use vaild endpoint',
33
+ });
34
+ }
35
+ return res.status(401).json({
36
+ error: true,
37
+ message: 'Unauthorized access. Please Refresh Token',
38
+ });
39
+ }
40
+ (<any>req).decoded = decoded;
41
+ next();
42
+ });
43
+ }
44
+ };
45
+
46
+ export default jwtVerification;
@@ -0,0 +1,62 @@
1
+ import { getConfig } from '@asapjs/core';
2
+
3
+ import express, { Request, Response } from 'express';
4
+ import bodyParser from 'body-parser';
5
+ import cors from 'cors';
6
+ import swaggerUi from 'swagger-ui-express';
7
+
8
+ import errorHandler from '../middleware/errorHandler';
9
+ import Wrapper from '../utils/wrapper';
10
+ import { getSwaggerData } from '../swagger';
11
+
12
+ export default class RouterModule {
13
+ private config: any;
14
+
15
+ public app: express.Application;
16
+
17
+ constructor(dirname: string) {
18
+ this.config = getConfig();
19
+ this.app = express();
20
+ this.initMiddlewares();
21
+ this.initRouter(dirname);
22
+ this.app.use(errorHandler);
23
+ }
24
+
25
+ private initRouter(dirname: string) {
26
+ const router: express.Router = express.Router();
27
+ const routes = require(`${dirname}/route`).default;
28
+ routes.forEach((route: any) => {
29
+ this.app.use(`/${this.config.basePath}${route.basePath}`, route.expressRouter || route.router);
30
+ });
31
+ this.app.use(router);
32
+ this.app.get(`/${this.config.basePath}`, (req: any, res: any) => {
33
+ res.send(`${this.config.name} server is working`);
34
+ });
35
+ this.app.get('/health-check', (req: any, res: any) => {
36
+ res.send(`${this.config.name} server is working`);
37
+ });
38
+ const options = {
39
+ swaggerOptions: {
40
+ url: `/${this.config.basePath}/docs/swagger.json`,
41
+ },
42
+ };
43
+ this.app.use(
44
+ `/${this.config.basePath}/docs/swagger-ui.html`,
45
+ swaggerUi.serveFiles(undefined, options),
46
+ swaggerUi.setup(undefined, options),
47
+ );
48
+ this.app.get(
49
+ `/${this.config.basePath}/docs/swagger.json`,
50
+ Wrapper(async (req: Request, res: Response) => {
51
+ const swaggerData = getSwaggerData();
52
+ res.json(swaggerData);
53
+ }),
54
+ );
55
+ }
56
+
57
+ private initMiddlewares() {
58
+ this.app.use(cors());
59
+ this.app.use(bodyParser.json());
60
+ this.app.use(bodyParser.urlencoded({ extended: true }));
61
+ }
62
+ }
@@ -0,0 +1,52 @@
1
+ /* eslint-disable no-nested-ternary */
2
+ import defaultSwagger from "../assets/default-swagger.json";
3
+
4
+ const methods = ["get", "post", "put", "delete"];
5
+
6
+ class DocsApplication {
7
+ public swaggerData: { [key: string]: any } = { ...defaultSwagger };
8
+
9
+ private swaggerPath = [];
10
+
11
+ private generatedSwaggerData: { [key: string]: any } | null = null;
12
+
13
+ public addPaths = async (data: any) => {
14
+ this.swaggerPath.push(data as never);
15
+ };
16
+
17
+ public generateSwaggerData = () => {
18
+ this.swaggerPath.sort((a: any, b: any) => {
19
+ const ix1 = methods.indexOf(a.method.toLowerCase());
20
+ const ix2 = methods.indexOf(b.method.toLowerCase());
21
+ return (a.tags?.[0] || 0) > (b.tags?.[0] || 0)
22
+ ? 1
23
+ : (a.tags?.[0] || 0) < (b.tags?.[0] || 0)
24
+ ? -1
25
+ : a.path > b.path
26
+ ? 1
27
+ : a.path < b.path
28
+ ? -1
29
+ : ix1 > ix2
30
+ ? 1
31
+ : ix1 < ix2
32
+ ? -1
33
+ : 0;
34
+ });
35
+
36
+ this.swaggerPath.forEach((v: any) => {
37
+ if (!this.swaggerData.paths[v.path]) this.swaggerData.paths[v.path] = {};
38
+ this.swaggerData.paths[v.path][v.method?.toLowerCase()] = v;
39
+ });
40
+
41
+ this.generatedSwaggerData = { ...this.swaggerData };
42
+ };
43
+
44
+ public getSwaggerData = () => {
45
+ if (this.generatedSwaggerData === null) {
46
+ this.generateSwaggerData();
47
+ }
48
+ return this.generatedSwaggerData;
49
+ };
50
+ }
51
+
52
+ export const { addPaths, getSwaggerData } = new DocsApplication();
@@ -0,0 +1,28 @@
1
+ import { NextFunction, Request, Response } from 'express';
2
+ import { logger } from '@asapjs/core';
3
+
4
+ type Callback = (request: Request<any, any, any, any>, response: Response, next: NextFunction) => Promise<unknown>;
5
+
6
+ export default function Wrapper(cb: Callback): Callback {
7
+ return async function _Wrapper(req: Request, res: Response, next: NextFunction) {
8
+ try {
9
+ const result = await cb(req, res, next);
10
+ return result;
11
+ } catch (err) {
12
+ console.log(err);
13
+ logger.error('[SERVER ERROR]', err);
14
+ if (err.status === 500 || err.status === undefined) {
15
+ const status = 500;
16
+ const message = '알 수 없는 오류가 발생했습니다.';
17
+ return res.status(status).json({
18
+ status,
19
+ message,
20
+ });
21
+ }
22
+ return res.status(err.status).json({
23
+ status: err.status,
24
+ message: err.message,
25
+ });
26
+ }
27
+ };
28
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "compilerOptions": {
3
+ "module": "commonjs",
4
+ "esModuleInterop": true,
5
+ "target": "es6",
6
+ "noImplicitAny": true,
7
+ "moduleResolution": "node",
8
+ "sourceMap": true,
9
+ "declaration": true,
10
+ "declarationMap": true,
11
+ "baseUrl": ".",
12
+ "outDir": "dist",
13
+ "lib": ["es2015", "es2019", "es2020"],
14
+ "skipLibCheck": true,
15
+ "strictNullChecks": true,
16
+ "experimentalDecorators": true,
17
+ "emitDecoratorMetadata": true,
18
+ "resolveJsonModule": true
19
+ },
20
+ "include": ["src/**/*"]
21
+ }