page2pdf_server 1.1.2 → 2.0.0

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 (70) hide show
  1. package/README.md +6 -5
  2. package/package.json +5 -70
  3. package/src/index.ts +10 -18
  4. package/src/types.d.ts +161 -97
  5. package/.github/ISSUE_TEMPLATE/bug_report.md +0 -28
  6. package/.github/ISSUE_TEMPLATE/feature_request.md +0 -15
  7. package/.github/ISSUE_TEMPLATE/refactoring.md +0 -15
  8. package/.github/PULL_REQUEST_TEMPLATE.md +0 -18
  9. package/.github/stale.yml +0 -17
  10. package/.github/workflows/cd.yml +0 -75
  11. package/.github/workflows/ci.yml +0 -36
  12. package/.prettierrc +0 -8
  13. package/.vscode/settings.json +0 -3
  14. package/config/default.json +0 -10
  15. package/config/development.json +0 -3
  16. package/config/production.json +0 -3
  17. package/config/test.json +0 -3
  18. package/ecosystem.config.js +0 -41
  19. package/jest.config.js +0 -35
  20. package/nodemon.json +0 -6
  21. package/src/CSS/345/205/274/345/256/271/346/200/247.txt +0 -125
  22. package/src/__tests__/UrltoPdf/generatePdf.test.d.ts +0 -1
  23. package/src/__tests__/UrltoPdf/generatePdf.test.ts +0 -207
  24. package/src/__tests__/UrltoPdf/pdfSplit.test.d.ts +0 -1
  25. package/src/__tests__/UrltoPdf/pdfSplit.test.ts +0 -69
  26. package/src/__tests__/helpers/index.d.ts +0 -2
  27. package/src/__tests__/helpers/index.ts +0 -21
  28. package/src/__tests__/home.test.d.ts +0 -1
  29. package/src/__tests__/home.test.ts +0 -77
  30. package/src/app.ts +0 -49
  31. package/src/components/home/controller.ts +0 -32
  32. package/src/components/home/index.ts +0 -4
  33. package/src/components/home/pdfController.ts +0 -118
  34. package/src/components/home/services.ts +0 -31
  35. package/src/components/home/splitController.ts +0 -134
  36. package/src/components/home/validators.ts +0 -12
  37. package/src/configEnv/index.ts +0 -62
  38. package/src/db/home.ts +0 -14
  39. package/src/helpers/apiResponse.ts +0 -10
  40. package/src/helpers/dataSanitizers.ts +0 -33
  41. package/src/helpers/error/ApiError.ts +0 -25
  42. package/src/helpers/error/ForbiddenError.ts +0 -15
  43. package/src/helpers/error/NotFoundException.ts +0 -15
  44. package/src/helpers/error/TimeOutError.ts +0 -20
  45. package/src/helpers/error/UnauthorizedError.ts +0 -15
  46. package/src/helpers/error/ValidationError.ts +0 -20
  47. package/src/helpers/error/index.ts +0 -15
  48. package/src/helpers/index.ts +0 -2
  49. package/src/helpers/loggers.ts +0 -75
  50. package/src/middlewares/errorHandler.ts +0 -52
  51. package/src/new_tab1.mhtml +0 -722
  52. package/src/routes/index.ts +0 -22
  53. package/src/server.ts +0 -30
  54. package/src/testCSS.html +0 -241
  55. package/src/types/global.d.ts +0 -13
  56. package/src/types/request/config.ts +0 -70
  57. package/src/types/request/home.ts +0 -3
  58. package/src/types/request/split.ts +0 -18
  59. package/src/types/response/AppInformation.ts +0 -9
  60. package/src/types/response/index.ts +0 -5
  61. package/src/utils/array.ts +0 -19
  62. package/src/utils/auth.ts +0 -12
  63. package/src/utils/crypt.ts +0 -25
  64. package/src/utils/filter.ts +0 -59
  65. package/src/utils/object.ts +0 -58
  66. package/src/utils/pdfgen.ts +0 -1045
  67. package/src/utils/url.ts +0 -54
  68. package/src//346/265/213/350/257/225.txt +0 -268
  69. package/test//346/211/223/345/215/260/346/234/215/345/212/241.http +0 -17
  70. package//346/226/207/344/271/246/346/211/223/345/215/260/350/275/254/346/215/242/345/231/250.bat +0 -2
@@ -1,77 +0,0 @@
1
- import { SuperAgentTest } from "supertest";
2
- import HttpStatus, { OK, BAD_REQUEST } from "http-status/lib";
3
- import { initAgent } from "./helpers/index";
4
- import CONFIG from "@/configEnv";
5
-
6
- //prettify真叼: 每个地方都给您报出 红色
7
- const TIMEOUT = 60000; //设置超时,避免单步歇菜
8
- let agent: SuperAgentTest;
9
-
10
- beforeAll(async () => {
11
- agent = await initAgent();
12
- });
13
-
14
- describe("[UNIT] => HOME", () => {
15
- describe("GET: '/'", () => {
16
- it(
17
- "Should return API app information",
18
- async () => {
19
- const response = await agent.get(`/api`);
20
- // const response = await agent.get(`/api/${CONFIG.APP.VER}`); 框架例子原始的 版本号;
21
- expect(response.status).toBe(OK);
22
- expect(Object.keys(response.body.data)).toEqual([
23
- "NAME",
24
- "VERSION",
25
- "VER",
26
- "DESCRIPTION",
27
- "AUTHORS",
28
- "HOST",
29
- "PORT",
30
- "ENV",
31
- "PATH",
32
- "MERGE",
33
- ]);
34
- },
35
- TIMEOUT,
36
- );
37
-
38
- it.each`
39
- query | field | expectedStatus
40
- ${"name"} | ${"NAME"} | ${OK}
41
- ${"version"} | ${"VERSION"} | ${OK}
42
- ${"description"} | ${"DESCRIPTION"} | ${OK}
43
- ${"authors"} | ${"AUTHORS"} | ${OK}
44
- ${"port"} | ${"PORT"} | ${OK}
45
- ${"env"} | ${"ENV"} | ${OK}
46
- `(
47
- "Should return CONFIG.APP[$field] value when query.key is `$query`",
48
- async ({
49
- query,
50
- field,
51
- expectedStatus,
52
- }: {
53
- query: string;
54
- field: keyof typeof CONFIG.APP;
55
- expectedStatus: string;
56
- }) => {
57
- const response = await agent.get(`/api`).query({ key: query });
58
-
59
- expect(response.body.status).toBe(expectedStatus);
60
- expect(response.body.data[field]).toBe(CONFIG.APP[field]);
61
- },
62
- TIMEOUT,
63
- );
64
-
65
- it(
66
- "Should return 400 status Validation Error",
67
- async () => {
68
- const invalidQuery = "invalid-field";
69
- const response = await agent.get(`/api`).query({ key: invalidQuery });
70
-
71
- expect(response.body.status).toBe(BAD_REQUEST);
72
- expect(response.body.message).toBe(HttpStatus[BAD_REQUEST]);
73
- },
74
- TIMEOUT,
75
- );
76
- });
77
- });
package/src/app.ts DELETED
@@ -1,49 +0,0 @@
1
- import { EventEmitter } from "events";
2
- import cors from "cors";
3
- import express from "express";
4
- import helmet from "helmet";
5
- import morgan from "morgan";
6
- import timeout from "connect-timeout";
7
- import CONFIG from "./configEnv";
8
- import { expressPinoLogger } from "./helpers";
9
- import * as errorHandler from "./middlewares/errorHandler";
10
- import routes from "./routes";
11
-
12
- /**打印不全,太多页数情形:
13
- * */
14
- EventEmitter.defaultMaxListeners = 100;
15
-
16
- export const createApp = (): express.Application => {
17
- const app = express();
18
-
19
- app.use(cors());
20
- app.use(helmet());
21
- app.use(express.json());
22
- app.use(
23
- express.urlencoded({
24
- extended: true,
25
- }),
26
- );
27
-
28
- if (CONFIG.APP.ENV !== "test") {
29
- app.use(morgan("dev"));
30
- app.use(expressPinoLogger());
31
- }
32
-
33
- // @ts-ignore
34
- app.use(timeout(CONFIG.SERVER.TIMEOUT));
35
-
36
- // API Routes
37
- // API Routes 如果代码非常简单,完全可以 app.get('/',....),如果路由比较复杂,需要路由的嵌套分层拆解模式:使用 express.Router() 更合适。
38
- app.use(`/api`, routes);
39
- //框架例子有:版本号的插入的。
40
- //app.use(`/api/${CONFIG.APP.VER}`, routes);
41
-
42
- // Error Middleware
43
- app.use(errorHandler.genericErrorHandler);
44
- app.use(errorHandler.notFoundError);
45
-
46
- return app;
47
- };
48
-
49
- //【CDP文档】 https://chromedevtools.github.io/devtools-protocol/tot/Target/
@@ -1,32 +0,0 @@
1
- import { OK } from "http-status/lib";
2
- import { Request, Response, NextFunction } from "express";
3
- import { getAppInfoQuery } from "../../types/request/home";
4
- import { apiResponse } from "../../helpers/apiResponse";
5
- import { HomeServices } from "./services";
6
-
7
- /**
8
- * 为何为了保证单步模式调试运行"test:watchAll": "cross-env NODE_ENV=development jest --watchAll --runInBand --detectOpenHandles",
9
- * 只能单独创建一个文件和类PdfController了,不能和HomeController合并在一个类class的俩个并行api处理函数啊?
10
- * */
11
- export class HomeController {
12
- /**
13
- * @description Gets the API information.
14
- * @param {Req} req
15
- * @param {Res} res
16
- */
17
- static getAppInfo = async (
18
- req: Request,
19
- res: Response,
20
- next: NextFunction,
21
- ) => {
22
- try {
23
- const appInfoKey = req.query.key as getAppInfoQuery;
24
- const homeServices = new HomeServices();
25
- const result = await homeServices.getAppInfo(appInfoKey);
26
-
27
- res.status(OK).json(apiResponse(result));
28
- } catch (error) {
29
- next(error);
30
- }
31
- };
32
- }
@@ -1,4 +0,0 @@
1
- export { HomeController } from "./controller";
2
- export { PdfController } from "./pdfController";
3
- export { appKeyValidator } from "./validators";
4
- export { SplitController } from "./splitController";
@@ -1,118 +0,0 @@
1
- import { OK } from "http-status/lib";
2
- import { NextFunction, Request, Response } from "express";
3
- import { HeadFooter } from "../../types/request/config";
4
- import { apiResponse } from "../../helpers/apiResponse";
5
- import { RenderPDF } from "../../utils/pdfgen";
6
- import CONFIG from "../../configEnv";
7
- import { ConfigRoot, FileTransform } from "../../types";
8
-
9
- export class PdfController {
10
- /** node.js对比前端App 太严格了,一点小毛病页不行啊。
11
- * @description 生成pdf.
12
- * @param {Req} req
13
- * @param {Res} res
14
- * 正常分解成两大步:task.files每一个文件生成,最后才是task.merge合并(包括页码生成)。
15
- * @param next
16
- */
17
- static postMakePdf = async (
18
- req: Request,
19
- res: Response,
20
- next: NextFunction,
21
- ) => {
22
- try {
23
- // const appInfoKey1 = req.query.key as getAppInfoQuery; 所有打印都走ConfigRoot配置包=task:可能有多个URL合并输出的。
24
- const task = req.body as ConfigRoot<FileTransform>;
25
- task.lay as HeadFooter;
26
- //预处理汇总输出的pdf页眉页脚, 转换页眉页脚的html存储
27
- if (task.lay) {
28
- const newfoot = "";
29
- const formfoot =
30
- task.lay.foot &&
31
- newfoot.concat(...task.lay.foot).replaceAll(`\\"`, '"');
32
- task.footerTemplate = formfoot ?? undefined;
33
- const formhead =
34
- task.lay.head &&
35
- newfoot.concat(...task.lay.head).replaceAll(`\\"`, '"');
36
- task.headerTemplate = formhead ?? undefined;
37
- const formfootL =
38
- task.lay.footL &&
39
- newfoot.concat(...task.lay.footL).replaceAll(`\\"`, '"');
40
- task.footerTemplateL = formfootL ?? undefined;
41
- const formheadL =
42
- task.lay.headL &&
43
- newfoot.concat(...task.lay.headL).replaceAll(`\\"`, '"');
44
- task.headerTemplateL = formheadL ?? undefined;
45
- }
46
- //const homeServices = new HomeServices();
47
- //let result = { ["文件名"]: "产生的.pdf" };
48
- let result;
49
- //若是用RenderPDF.generateSinglePdf(会导致没有等待该函数执行结果就会去执行下一步了,应答res,客户端立刻获得http回答,无等待=异步模式的。还是由客户端主动取消等待为佳。这里死等的;
50
- try {
51
- //const jobs = generateJobList(urls, pdfs); 分解成多个URL文件多个步骤的情况,可能还有个汇总步骤的:
52
- // generateSinglePdf mergePdfs pageNoForPdf yeMeiyeJiaoPdf
53
- if (
54
- (task.merge === undefined || task.merge) &&
55
- task.files === undefined &&
56
- !task.lay
57
- ) {
58
- await RenderPDF.mergeAllPdfto(); //特殊的特殊? 没有涉及到CDP()函数:
59
- result = `简易合并输出是: ${CONFIG.APP.MERGE}`;
60
- } else {
61
- //有涉及到CDP()函数:
62
- const renderer = new RenderPDF({}); //提升上来:复用全局的
63
- if (!task.files || task.files?.length <= 0) {
64
- console.error("没配置files输入");
65
- res.status(OK).json(apiResponse({ result: "没配置files输入" }));
66
- return;
67
- } else {
68
- for (const meta of task.files) {
69
- if (!meta.out) {
70
- if (meta.url.endsWith(".pdf") && !meta.url.startsWith("http"))
71
- continue;
72
- else {
73
- res
74
- .status(OK)
75
- .json(apiResponse({ result: meta.url + " 没配置out" }));
76
- return;
77
- }
78
- } else {
79
- //本地pdf情形实际会有webview/iframe的?跳转?,实际会看到pdf之外的浏览控件框框的。 避免再次转换pdf实际捕获窗口并非pdf自身内容;
80
- if (meta.url.endsWith(".pdf") && !meta.url.startsWith("http"))
81
- throw new Error(
82
- "url是本地的pdf文件,不应该设置out参数:" + meta.url,
83
- );
84
- }
85
- try {
86
- result = await renderer.generateSinglePdf(meta, task, {});
87
- } catch (e) {
88
- result = "算url失败:" + meta.url;
89
- console.error(e);
90
- }
91
- if (result) {
92
- result = "URL:" + meta.url + " > " + result;
93
- break; //说明有某种报错
94
- }
95
- }
96
- }
97
- //正常的合并阶段的事情: 前一阶段页眉页脚也不打印了。也要放这里了
98
- if (!result && (task.merge === undefined || task.merge))
99
- result = await RenderPDF.MergeAllPdfs(task, {});
100
- //关闭多余窗口
101
- if (task.closeTab)
102
- await renderer.closeAllTab(renderer.getCDPhostPort(), task);
103
- }
104
- } catch (e) {
105
- result = "算失败了" + e;
106
- console.error(e);
107
- }
108
-
109
- if (!result || result === "") {
110
- result = "成功!";
111
- console.log(result, "输出是:", task.name ?? CONFIG.APP.MERGE);
112
- }
113
- res.status(OK).json(apiResponse({ result: result }));
114
- } catch (error) {
115
- next(error);
116
- }
117
- };
118
- }
@@ -1,31 +0,0 @@
1
- import AppInformation from "../../types/response/AppInformation";
2
- import { HomeDAO } from "../../db/home";
3
- import { getAppInfoQuery } from "../../types/request/home";
4
-
5
- export class HomeServices {
6
- homeDAO!: HomeDAO;
7
- constructor() {
8
- this.homeDAO = new HomeDAO();
9
- }
10
- // NAME: pkg.name,
11
- // VERSION: pkg.version,
12
- // VER: `v${pkg.version[0]}`,
13
- // DESCRIPTION: pkg.description,
14
- // AUTHORS: pkg.authors,
15
- // HOST: process.env.APP_HOST,
16
- // BASE_URL: process.env.API_BASE_URL,
17
- // PORT: process.env.NODE_ENV === "test" ? 8888 : process.env.PORT || 8080,
18
- // ENV: process.env.NODE_ENV,
19
-
20
- /**
21
- * @description Get application information.
22
- * @returns AppInformation
23
- */
24
- getAppInfo = async (
25
- appInfoKey?: getAppInfoQuery,
26
- ): Promise<AppInformation> => {
27
- const result = await this.homeDAO.get(appInfoKey);
28
-
29
- return result;
30
- };
31
- }
@@ -1,134 +0,0 @@
1
- import fs from "fs";
2
- import { OK } from "http-status/lib";
3
- import { NextFunction, Request, Response } from "express";
4
- import { HeadFooter } from "../../types/request/config";
5
- import { apiResponse } from "../../helpers/apiResponse";
6
-
7
- import { RenderPDF } from "../../utils/pdfgen";
8
- import CONFIG from "../../configEnv";
9
- import { SplitConfig, SplitPdfFile } from "../../types/request/split";
10
- import { ConfigRoot, FileTransform } from "../../types";
11
- // import CONFIG from "@/configEnv";
12
- // eslint-disable-next-line @typescript-eslint/no-var-requires
13
- const { PDFDocument } = require("pdf-lib");
14
-
15
- /**只好拆分多个文件:就为了能够jest运行于单步调试模式啊。
16
- * __test__/./generatePdf.test.ts问题:jest用Run模式正常,可是若Debug模式单步调试的,.post(`/api/pdf`).send就会提前中止!原因xxxController容不下多个接口函数?
17
- * ?估计同一个.ts文件引入的包有动态编译的问题?非得拆分两个文件。
18
- * */
19
- export class SplitController {
20
- /** node.js对比前端App 太严格了,一点小毛病页不行啊。
21
- * @description 生成pdf.
22
- * @param {Req} req
23
- * @param {Res} res
24
- * 正常分解成两大步:task.files每一个文件生成,最后才是task.merge合并(包括页码生成)。
25
- * @param next
26
- */
27
- //仅仅测试的
28
- static postMakePdf = async (
29
- req: Request,
30
- res: Response,
31
- next: NextFunction,
32
- ) => {
33
- try {
34
- // const appInfoKey1 = req.query.key as getAppInfoQuery;
35
- const task = req.body as ConfigRoot<FileTransform>;
36
- task.lay as HeadFooter;
37
- //预处理汇总输出的pdf页眉页脚
38
- if (task.lay) {
39
- const newfoot = "";
40
- const formfoot =
41
- task.lay.foot &&
42
- newfoot.concat(...task.lay.foot).replaceAll(`\\"`, '"');
43
- task.footerTemplate = formfoot ?? undefined;
44
- const formhead =
45
- task.lay.head &&
46
- newfoot.concat(...task.lay.head).replaceAll(`\\"`, '"');
47
- task.headerTemplate = formhead ?? undefined;
48
- }
49
- //const homeServices = new HomeServices();
50
- //let result = { ["文件名"]: "产生的.pdf" };
51
- let result;
52
- //若是用RenderPDF.generateSinglePdf(会导致没有等待该函数执行结果就会去执行下一步了,应答res,客户端立刻获得http回答,无等待=异步模式的。还是由客户端主动取消等待为佳。这里死等的;
53
- try {
54
- //const jobs = generateJobList(urls, pdfs); 分解成多个URL文件多个步骤的情况,可能还有个汇总步骤的:
55
- // generateSinglePdf mergePdfs pageNoForPdf yeMeiyeJiaoPdf
56
- if (
57
- (task.merge === undefined || task.merge) &&
58
- task.files === undefined &&
59
- !task.lay
60
- ) {
61
- await RenderPDF.mergeAllPdfto(); //特殊的特殊?
62
- result = `简易合并输出是: ${CONFIG.APP.MERGE}`;
63
- } else {
64
- //正常的合并阶段的事情: 前一阶段页眉页脚也不打印了。也要放这里了
65
- //if(task.merge===undefined || task.merge)
66
- result = await RenderPDF.MergeAllPdfs(task, {});
67
- }
68
- } catch (e) {
69
- result = "算失败了" + e;
70
- console.error(e);
71
- }
72
-
73
- if (!result || result === "") result = "成功!";
74
- res.status(OK).json(apiResponse({ result: result }));
75
- } catch (error) {
76
- next(error);
77
- }
78
- };
79
-
80
- /**拆分需要:支持pdf源文件的,抽取部分纸张页生成新文件*/
81
- static postSplitPdf = async (
82
- req: Request,
83
- res: Response,
84
- next: NextFunction,
85
- ) => {
86
- try {
87
- //也可能?用CDP:printPDF()来进行部分打印的后保存,就等于拆分pdf;
88
- const task = req.body as SplitConfig;
89
- task.files as SplitPdfFile[];
90
- //输入文件 都是pdf了
91
- const srcDoc = await PDFDocument.load(
92
- fs.readFileSync(CONFIG.APP.PATH + "/" + task.input),
93
- );
94
- let result;
95
- const allpagesum = await srcDoc.getPages().length;
96
- //若是用RenderPDF.generateSinglePdf(会导致没有等待该函数执行结果就会去执行下一步了,应答res,客户端立刻获得http回答,无等待=异步模式的。还是由客户端主动取消等待为佳。这里死等的;
97
- try {
98
- for (const fileone of task.files) {
99
- const oneDoc = await PDFDocument.create();
100
- //可能出现例子是 '1-5, 8, 11-13' 类似打印机常见的选择页码范围。
101
- const ofstr = fileone.pageRanges;
102
- const ranges = ofstr.split(",");
103
- for (const range of ranges) {
104
- const bgend = range.split("-");
105
- const beginp = bgend[0];
106
- let endp = bgend[1];
107
- if (!endp) {
108
- endp = beginp;
109
- }
110
- //逗号分割开的某一区域 , , 被选定的: 页序数号是从开始的。
111
- let i = Number(beginp);
112
- const endpage = Number(endp);
113
- if (i < 1 || i > allpagesum || endpage < i || endpage > allpagesum)
114
- throw new Error("选定的页序号超范围:[" + i + "-" + endpage + "]");
115
- for (; i <= endpage; i++) {
116
- const [aPage] = await oneDoc.copyPages(srcDoc, [i - 1]);
117
- oneDoc.addPage(aPage);
118
- }
119
- }
120
- const name = CONFIG.APP.PATH + "/" + fileone.out + ".pdf";
121
- fs.writeFileSync(name, await oneDoc.save());
122
- }
123
- } catch (e) {
124
- result = "算失败了" + e;
125
- console.error(e); //这个在最终服务端cmd窗口可输出
126
- }
127
-
128
- if (!result || result === "") result = "成功!";
129
- res.status(OK).json(apiResponse({ result: result }));
130
- } catch (error) {
131
- next(error);
132
- }
133
- };
134
- }
@@ -1,12 +0,0 @@
1
- import { query } from "express-validator";
2
- import CONFIG from "../../configEnv";
3
-
4
- const appKeys = Object.keys(CONFIG.APP).map((key) => key.toLocaleLowerCase());
5
-
6
- export const appKeyValidator = [
7
- query("key")
8
- .optional()
9
- .isString()
10
- .isIn(appKeys)
11
- .withMessage("`name` should be string type"),
12
- ];
@@ -1,62 +0,0 @@
1
- import pkg from "../../package.json";
2
-
3
- // https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import
4
- // eslint-disable-next-line @typescript-eslint/no-var-requires
5
- require("dotenv").config();
6
-
7
- //提取独立的配置文件的设置参数:
8
- // eslint-disable-next-line @typescript-eslint/no-var-requires
9
- const config = require("config");
10
- const base_path = config.get("base_path");
11
- const default_file = config.get("default_file");
12
- console.log("默认合并输出文件: " + base_path + "/" + default_file + ".pdf");
13
-
14
- //pkg.是项目工程的配置;
15
- const CONFIG = {
16
- APP: {
17
- NAME: pkg.name,
18
- VERSION: pkg.version,
19
- VER: `v${pkg.version[0]}`,
20
- DESCRIPTION: pkg.description,
21
- AUTHORS: pkg.authors,
22
- HOST: process.env.APP_HOST,
23
- BASE_URL: process.env.API_BASE_URL,
24
- PORT: process.env.NODE_ENV === "test" ? 8888 : process.env.PORT || 8080,
25
- ENV: process.env.NODE_ENV,
26
- PATH: base_path,
27
- MERGE: default_file,
28
- },
29
- SERVER: {
30
- TIMEOUT: 60 * 60 * 1000, // 60 *60秒没结果的
31
- },
32
- LOG: {
33
- PATH: process.env.LOGGING_DIR || "logs",
34
- LEVEL: process.env.LOGGING_LEVEL || "info",
35
- MAX_FILES: process.env.LOGGING_MAX_FILES || 5,
36
- },
37
- AUTH: {
38
- SALT_ROUNDS: process.env.SALT_ROUNDS || "11",
39
- ACCESS_TOKEN_EXPIRE: process.env.ACCESS_TOKEN_DURATION || "300000",
40
- REFRESH_TOKEN_EXPIRE: process.env.REFRESH_TOKEN_DURATION || "86400000",
41
- ACCESS_TOKEN_SALT: process.env.ACCESS_TOKEN_SALT,
42
- REFRESH_TOKEN_SALT: process.env.REFRESH_TOKEN_SALT,
43
- },
44
- AWS: {
45
- ACCESS_KEY: process.env.AWS_ACCESS_KEY,
46
- SECRET_KEY: process.env.AWS_SECRET_KEY,
47
- REGION: process.env.AWS_REGION,
48
- S3: {
49
- PATH: process.env.S3_BUCKET_PATH,
50
- BUCKET_NAME: process.env.S3_BUCKET_NAME,
51
- },
52
- COGNITO: {
53
- USER_POOL_ID: process.env.COGNITO_USER_POOL_ID,
54
- CLIENT_ID: process.env.COGNITO_CLIENT_ID,
55
- },
56
- },
57
- EXTERNAL: {
58
- API_KEY: process.env.API_KEY,
59
- },
60
- } as const;
61
-
62
- export default CONFIG;
package/src/db/home.ts DELETED
@@ -1,14 +0,0 @@
1
- import AppInformation from "../types/response/AppInformation";
2
- import CONFIG from "../configEnv";
3
- import { getAppInfoQuery } from "../types/request/home";
4
-
5
- export class HomeDAO {
6
- get = (key?: getAppInfoQuery): Promise<AppInformation | any> => {
7
- if (!key) {
8
- return Promise.resolve(CONFIG.APP);
9
- }
10
- const upperKey = key.toUpperCase() as keyof typeof CONFIG.APP;
11
-
12
- return Promise.resolve({ [upperKey]: CONFIG.APP[upperKey] });
13
- };
14
- }
@@ -1,10 +0,0 @@
1
- import HttpStatus, { OK } from "http-status/lib";
2
- import { ApiSuccessResponse } from "../types/response";
3
-
4
- export const apiResponse = <T>(data?: T): ApiSuccessResponse<T> => {
5
- return {
6
- status: OK,
7
- message: HttpStatus[OK] as string,
8
- data,
9
- };
10
- };
@@ -1,33 +0,0 @@
1
- import { Result, ValidationChain, validationResult } from "express-validator";
2
- // @ts-ignore
3
- import { Middleware as ValidatorMiddleware } from "express-validator/src/base";
4
- import { NextFunction, Request, Response } from "express";
5
- import ValidationError from "./error/ValidationError";
6
-
7
- type MultiValidatorChain = ValidatorMiddleware & {
8
- run: (req: Request) => Promise<Result>;
9
- };
10
-
11
- const catchValidatorError = (req: Request, _: Response, next: NextFunction): void => {
12
- const errors = validationResult(req);
13
- if (!errors.isEmpty()) {
14
- const validationErrors = errors
15
- .array()
16
- .reduce(
17
- (
18
- obj: Record<string, string>,
19
- error: Record<string, any>,
20
- ): Record<string, any> => {
21
- obj[error.param] = error.msg;
22
- return obj;
23
- },
24
- {},
25
- );
26
- throw new ValidationError(validationErrors);
27
- }
28
- next();
29
- };
30
-
31
- export const sanitizer = (
32
- validator: (ValidationChain | MultiValidatorChain)[],
33
- ) => [...validator, catchValidatorError];
@@ -1,25 +0,0 @@
1
- import HttpStatus, { INTERNAL_SERVER_ERROR } from "http-status/lib";
2
-
3
- class APIError extends Error {
4
- readonly status: number;
5
- readonly message: string;
6
- readonly error: any | undefined;
7
-
8
- constructor(message: string | null, error?: any) {
9
- super();
10
- Object.setPrototypeOf(this, new.target.prototype);
11
- this.status = INTERNAL_SERVER_ERROR;
12
- this.message = message || (HttpStatus[INTERNAL_SERVER_ERROR] as string);
13
- if (error && error instanceof Error) {
14
- this.error = {
15
- type: error?.name,
16
- message: error?.message,
17
- stack: error?.stack,
18
- };
19
- }
20
-
21
- Error.captureStackTrace(this);
22
- }
23
- }
24
-
25
- export default APIError;
@@ -1,15 +0,0 @@
1
- import { FORBIDDEN } from "http-status/lib";
2
-
3
- class ForbiddenError {
4
- readonly status: number;
5
- readonly message: string;
6
-
7
- constructor(message: string) {
8
- Object.setPrototypeOf(this, new.target.prototype);
9
-
10
- this.status = FORBIDDEN;
11
- this.message = message;
12
- }
13
- }
14
-
15
- export default ForbiddenError;
@@ -1,15 +0,0 @@
1
- import HttpStatus, { NOT_FOUND } from "http-status/lib";
2
-
3
- class NotFoundException {
4
- readonly status: number;
5
- readonly message: string;
6
-
7
- constructor() {
8
- Object.setPrototypeOf(this, new.target.prototype);
9
-
10
- this.status = NOT_FOUND;
11
- this.message = HttpStatus[NOT_FOUND] as string;
12
- }
13
- }
14
-
15
- export default NotFoundException;
@@ -1,20 +0,0 @@
1
- import httpStatus, { REQUEST_TIMEOUT } from "http-status/lib";
2
- import CONFIG from "../../configEnv";
3
-
4
- class TimeOutError {
5
- readonly status: number;
6
- readonly message: string;
7
- readonly timeout: string | number;
8
- readonly path: string;
9
-
10
- constructor(path: string) {
11
- Object.setPrototypeOf(this, new.target.prototype);
12
-
13
- this.status = REQUEST_TIMEOUT;
14
- this.message = httpStatus[REQUEST_TIMEOUT] as string;
15
- this.timeout = CONFIG.SERVER.TIMEOUT;
16
- this.path = path;
17
- }
18
- }
19
-
20
- export default TimeOutError;