@trojs/openapi-server 2.1.1 → 3.1.2

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/package.json CHANGED
@@ -1,17 +1,17 @@
1
1
  {
2
2
  "name": "@trojs/openapi-server",
3
3
  "description": "OpenAPI Server",
4
- "version": "2.1.1",
4
+ "version": "3.1.2",
5
5
  "author": {
6
6
  "name": "Pieter Wigboldus",
7
7
  "url": "https://trojs.org/"
8
8
  },
9
9
  "license": "MIT",
10
10
  "scripts": {
11
- "lint": "eslint src/*.js --config .eslintrc",
12
- "lint:report": "eslint src/*.js --config .eslintrc -f json -o report.json",
13
- "lint:fix": "eslint src/*.js --config .eslintrc --fix",
14
- "test": "c8 node --test src/*.test.js",
11
+ "lint": "eslint",
12
+ "lint:report": "eslint src/*.js -f json -o report.json",
13
+ "lint:fix": "eslint --fix",
14
+ "test": "node --test --experimental-test-coverage --test-reporter=spec --test-reporter=lcov --test-reporter-destination=stdout --test-reporter-destination=./coverage/lcov.info",
15
15
  "cpd": "node_modules/jscpd/bin/jscpd src",
16
16
  "vulnerabilities": "npm audit --omit=dev"
17
17
  },
@@ -33,23 +33,12 @@
33
33
  ],
34
34
  "main": "src/server.js",
35
35
  "devDependencies": {
36
- "@hckrnews/eslint-code-quality": "^0.2.1",
37
- "@hckrnews/eslint-config": "^3.1.0",
38
- "@types/express-serve-static-core": "^4.17.41",
36
+ "@trojs/lint": "^0.2.9",
39
37
  "@types/node": "^22.0.0",
40
- "c8": "^10.0.0",
41
- "eslint": "^8.23.0",
42
- "eslint-config-airbnb-base": "^15.0.0",
43
- "eslint-config-prettier": "^9.1.0",
44
- "eslint-plugin-html": "^8.1.1",
45
- "eslint-plugin-import": "^2.26.0",
46
- "eslint-plugin-jsdoc": "^50.0.0",
47
- "eslint-plugin-jsx-a11y": "^6.9.0",
48
- "eslint-plugin-n": "^17.0.0",
49
- "eslint-plugin-prettier": "^5.1.3",
50
- "eslint-plugin-promise": "^7.0.0",
51
- "eslint-plugin-sonarjs": "^0.25.1",
52
- "jscpd": "^4.0.0",
38
+ "@types/express-serve-static-core": "^5.0.0",
39
+ "eslint": "^9.15.0",
40
+ "globals": "^16.0.0",
41
+ "jscpd": "^4.0.5",
53
42
  "prettier": "^3.3.3",
54
43
  "supertest": "^7.0.0"
55
44
  },
@@ -58,7 +47,7 @@
58
47
  "url": "https://github.com/trojs/openapi-server"
59
48
  },
60
49
  "engines": {
61
- "node": ">= 18.13 < 19 || >= 20 < 21 || >= 22 < 23"
50
+ "node": ">= 20 < 21 || >= 22 < 23"
62
51
  },
63
52
  "keywords": [
64
53
  "openapi",
@@ -66,12 +55,12 @@
66
55
  "express"
67
56
  ],
68
57
  "dependencies": {
69
- "@sentry/node": "^8.0.0",
58
+ "@sentry/node": "^9.0.0",
70
59
  "ajv-formats": "^3.0.0",
71
60
  "body-parser": "^2.0.0",
72
61
  "compression": "^1.7.4",
73
62
  "cors": "^2.8.5",
74
- "express": "^4.19.2",
63
+ "express": "^5.0.0",
75
64
  "helmet": "^8.0.0",
76
65
  "openapi-backend": "^5.9.2",
77
66
  "swagger-ui-express": "^5.0.0"
@@ -81,7 +70,7 @@
81
70
  "url": "https://github.com/sponsors/w3nl"
82
71
  },
83
72
  "overrides": {
84
- "semver": "^7.5.3",
73
+ "semver@<=7.5.3": "^7.5.3",
85
74
  "send@<=0.19.0": "^0.19.0",
86
75
  "cookie@<=0.7.0": "0.7.0"
87
76
  }
package/src/api.js CHANGED
@@ -1,6 +1,6 @@
1
- import express from 'express';
2
- import swaggerUi from 'swagger-ui-express';
3
- import { setupRouter } from './router.js';
1
+ import express from 'express'
2
+ import swaggerUi from 'swagger-ui-express'
3
+ import { setupRouter } from './router.js'
4
4
 
5
5
  /**
6
6
  * @typedef {import('openapi-backend').Handler} Handler
@@ -29,76 +29,77 @@ import { setupRouter } from './router.js';
29
29
  */
30
30
 
31
31
  /**
32
- * Setup the server for a specific API, so every server can run multiple instances of the API, like different versions, for e.g. different clients
32
+ * Setup the server for a specific API, so every server can run multiple instances of the API,
33
+ * like different versions, for e.g. different clients
33
34
  */
34
35
 
35
36
  export class Api {
36
- /**
37
- * Create a new instance of the API
38
- * @constructor
39
- * @param {ApiSchema} params
40
- */
41
- constructor({
42
- version,
43
- specification,
44
- controllers,
45
- apiRoot,
46
- strictSpecification,
47
- errorDetails,
48
- logger,
49
- meta,
50
- securityHandlers,
51
- swagger,
52
- apiDocs,
53
- ajvOptions,
54
- }) {
55
- this.version = version;
56
- this.specification = specification;
57
- this.controllers = controllers;
58
- this.apiRoot = apiRoot;
59
- this.strictSpecification = strictSpecification;
60
- this.errorDetails = errorDetails || false;
61
- this.logger = logger || console;
62
- this.meta = meta || {};
63
- this.securityHandlers = securityHandlers || [];
64
- this.swagger = swagger ?? true;
65
- this.apiDocs = apiDocs ?? true;
66
- this.ajvOptions = ajvOptions ?? { allErrors: false };
67
- }
37
+ /**
38
+ * Create a new instance of the API
39
+ * @class
40
+ * @param {ApiSchema} params
41
+ */
42
+ constructor ({
43
+ version,
44
+ specification,
45
+ controllers,
46
+ apiRoot,
47
+ strictSpecification,
48
+ errorDetails,
49
+ logger,
50
+ meta,
51
+ securityHandlers,
52
+ swagger,
53
+ apiDocs,
54
+ ajvOptions
55
+ }) {
56
+ this.version = version
57
+ this.specification = specification
58
+ this.controllers = controllers
59
+ this.apiRoot = apiRoot
60
+ this.strictSpecification = strictSpecification
61
+ this.errorDetails = errorDetails || false
62
+ this.logger = logger || console
63
+ this.meta = meta || {}
64
+ this.securityHandlers = securityHandlers || []
65
+ this.swagger = swagger ?? true
66
+ this.apiDocs = apiDocs ?? true
67
+ this.ajvOptions = ajvOptions ?? { allErrors: false }
68
+ }
68
69
 
69
- setup() {
70
- const router = express.Router();
70
+ setup () {
71
+ const router = express.Router()
71
72
 
72
- if (this.swagger) {
73
- router.use(
74
- '/swagger',
75
- swaggerUi.serveFiles(this.specification, {}),
76
- swaggerUi.setup(this.specification)
77
- );
78
- }
79
- if (this.apiDocs) {
80
- router.get('/api-docs', (_request, response) =>
81
- response.json(this.specification)
82
- );
83
- }
73
+ if (this.swagger) {
74
+ router.use(
75
+ '/swagger',
76
+ swaggerUi.serveFiles(this.specification, {}),
77
+ swaggerUi.setup(this.specification)
78
+ )
79
+ }
80
+ if (this.apiDocs) {
81
+ router.get('/api-docs', (_request, response) =>
82
+ response.json(this.specification)
83
+ )
84
+ }
84
85
 
85
- const { api } = setupRouter({
86
- openAPISpecification: this.specification,
87
- controllers: this.controllers,
88
- apiRoot: this.apiRoot,
89
- strictSpecification: this.strictSpecification,
90
- errorDetails: this.errorDetails,
91
- logger: this.logger,
92
- meta: this.meta,
93
- securityHandlers: this.securityHandlers,
94
- ajvOptions: this.ajvOptions,
95
- });
96
- api.init();
86
+ const { api } = setupRouter({
87
+ openAPISpecification: this.specification,
88
+ controllers: this.controllers,
89
+ apiRoot: this.apiRoot,
90
+ strictSpecification: this.strictSpecification,
91
+ errorDetails: this.errorDetails,
92
+ logger: this.logger,
93
+ meta: this.meta,
94
+ securityHandlers: this.securityHandlers,
95
+ ajvOptions: this.ajvOptions
96
+ })
97
+ api.init()
97
98
 
98
- router.use((request, response) =>
99
- api.handleRequest(request, request, response)
100
- );
99
+ router.use((request, response) =>
100
+ api.handleRequest(request, request, response)
101
+ )
101
102
 
102
- return router;
103
- }
103
+ return router
104
+ }
104
105
  }
@@ -1,17 +1,17 @@
1
1
  const errorCodesStatus = [
2
- {
3
- type: TypeError,
4
- status: 422,
5
- },
6
- {
7
- type: RangeError,
8
- status: 404,
9
- },
10
- {
11
- type: Error,
12
- status: 500,
13
- },
14
- ];
2
+ {
3
+ type: TypeError,
4
+ status: 422
5
+ },
6
+ {
7
+ type: RangeError,
8
+ status: 404
9
+ },
10
+ {
11
+ type: Error,
12
+ status: 500
13
+ }
14
+ ]
15
15
 
16
16
  /**
17
17
  * Get a http status when you send an error.
@@ -20,5 +20,5 @@ const errorCodesStatus = [
20
20
  * @returns {number}
21
21
  */
22
22
  export default (error) =>
23
- errorCodesStatus.find((errorCode) => error instanceof errorCode.type)
24
- .status;
23
+ errorCodesStatus.find((errorCode) => error instanceof errorCode.type)
24
+ .status
@@ -1,5 +1,5 @@
1
- import getStatusByError from './error-status.js';
2
- import { parseParams } from './params.js';
1
+ import getStatusByError from './error-status.js'
2
+ import { parseParams } from './params.js'
3
3
 
4
4
  /**
5
5
  * @typedef {import('express-serve-static-core').Request} Request
@@ -19,8 +19,8 @@ import { parseParams } from './params.js';
19
19
  * @param {boolean=} params.mock
20
20
  * @returns {Function}
21
21
  */
22
- export const makeExpressCallback =
23
- ({ controller, specification, errorDetails, logger, meta, mock }) =>
22
+ export const makeExpressCallback
23
+ = ({ controller, specification, errorDetails, logger, meta, mock }) =>
24
24
  /**
25
25
  * Handle controller
26
26
  * @async
@@ -29,68 +29,68 @@ export const makeExpressCallback =
29
29
  * @param {Response} response
30
30
  * @returns {Promise<any>}
31
31
  */
32
- async (context, request, response) => {
32
+ async (context, request, response) => {
33
33
  try {
34
- const allParameters = {
35
- ...(context.request?.params || {}),
36
- ...(context.request?.query || {}),
37
- };
38
- const parameters = parseParams({
39
- query: allParameters,
40
- spec: context.operation.parameters,
41
- mock,
42
- });
43
- const url = `${request.protocol}://${request.get('Host')}${request.originalUrl}`;
34
+ const allParameters = {
35
+ ...(context.request?.params || {}),
36
+ ...(context.request?.query || {})
37
+ }
38
+ const parameters = parseParams({
39
+ query: allParameters,
40
+ spec: context.operation.parameters,
41
+ mock
42
+ })
43
+ const url = `${request.protocol}://${request.get('Host')}${request.originalUrl}`
44
44
 
45
- const responseBody = await controller({
46
- context,
47
- request,
48
- response,
49
- parameters,
50
- specification,
51
- post: request.body,
52
- url,
53
- logger,
54
- meta,
55
- });
56
- logger.debug({
57
- url,
58
- parameters,
59
- post: request.body,
60
- response: responseBody,
61
- });
45
+ const responseBody = await controller({
46
+ context,
47
+ request,
48
+ response,
49
+ parameters,
50
+ specification,
51
+ post: request.body,
52
+ url,
53
+ logger,
54
+ meta
55
+ })
56
+ logger.debug({
57
+ url,
58
+ parameters,
59
+ post: request.body,
60
+ response: responseBody
61
+ })
62
62
 
63
- return responseBody;
63
+ return responseBody
64
64
  } catch (error) {
65
- const errorCodeStatus = getStatusByError(error);
65
+ const errorCodeStatus = getStatusByError(error)
66
66
 
67
- if (errorCodeStatus >= 500) {
68
- logger.error(error);
69
- } else {
70
- logger.warn(error);
71
- }
67
+ if (errorCodeStatus >= 500) {
68
+ logger.error(error)
69
+ } else {
70
+ logger.warn(error)
71
+ }
72
72
 
73
- response.status(errorCodeStatus);
73
+ response.status(errorCodeStatus)
74
74
 
75
- if (errorDetails) {
76
- return {
77
- errors: [
78
- {
79
- message: error.message,
80
- value: error.valueOf(),
81
- type: error.constructor.name,
82
- },
83
- ],
84
- status: errorCodeStatus,
85
- timestamp: new Date(),
86
- message: error.message,
87
- };
75
+ if (errorDetails) {
76
+ return {
77
+ errors: [
78
+ {
79
+ message: error.message,
80
+ value: error.valueOf(),
81
+ type: error.constructor.name
82
+ }
83
+ ],
84
+ status: errorCodeStatus,
85
+ timestamp: new Date(),
86
+ message: error.message
88
87
  }
88
+ }
89
89
 
90
- return {
91
- status: errorCodeStatus,
92
- timestamp: new Date(),
93
- message: error.message,
94
- };
90
+ return {
91
+ status: errorCodeStatus,
92
+ timestamp: new Date(),
93
+ message: error.message
94
+ }
95
95
  }
96
- };
96
+ }
package/src/openapi.js CHANGED
@@ -1,4 +1,4 @@
1
- import { readFile } from 'node:fs/promises';
1
+ import { readFile } from 'node:fs/promises'
2
2
 
3
3
  /**
4
4
  * Get the OpenAPI specification from the file.
@@ -9,7 +9,7 @@ import { readFile } from 'node:fs/promises';
9
9
  * @returns {Promise<{ openAPISpecification: object; }>}
10
10
  */
11
11
  export const openAPI = async ({ file, base = import.meta.url }) => {
12
- const fileUrl = new URL(file, base);
13
- const openAPISpecification = JSON.parse(await readFile(fileUrl, 'utf8'));
14
- return { openAPISpecification };
15
- };
12
+ const fileUrl = new URL(file, base)
13
+ const openAPISpecification = JSON.parse(await readFile(fileUrl, 'utf8'))
14
+ return { openAPISpecification }
15
+ }
@@ -1,4 +1,4 @@
1
- const operations = ['get', 'put', 'patch', 'post', 'delete'];
1
+ const operations = ['get', 'put', 'patch', 'post', 'delete']
2
2
 
3
3
  /**
4
4
  * Get all operation ID's from the specification.
@@ -7,10 +7,10 @@ const operations = ['get', 'put', 'patch', 'post', 'delete'];
7
7
  * @returns {string[]}
8
8
  */
9
9
  export const operationIds = ({ specification }) =>
10
- Object.values(specification.paths)
11
- .map((path) =>
12
- Object.entries(path).map(([operation, data]) =>
13
- operations.includes(operation) ? data.operationId : null
14
- )
15
- )
16
- .flat();
10
+ Object.values(specification.paths)
11
+ .map((path) =>
12
+ Object.entries(path).map(([operation, data]) =>
13
+ operations.includes(operation) ? data.operationId : null
14
+ )
15
+ )
16
+ .flat()
package/src/params.js CHANGED
@@ -1,4 +1,4 @@
1
- import { types } from './types.js';
1
+ import { types } from './types.js'
2
2
 
3
3
  /**
4
4
  * Parse params to the types defined in the spec
@@ -9,41 +9,41 @@ import { types } from './types.js';
9
9
  * @returns {object}
10
10
  */
11
11
  export const parseParams = ({ query, spec, mock = false }) =>
12
- spec
13
- .map((parameter) => {
14
- const { name, schema } = parameter;
15
- const {
16
- type,
17
- default: defaultValue,
18
- example: exampleValue,
19
- } = schema;
20
- const Type = types[type];
21
- const paramName = query?.[name];
12
+ spec
13
+ .map((parameter) => {
14
+ const { name, schema } = parameter
15
+ const {
16
+ type,
17
+ default: defaultValue,
18
+ example: exampleValue
19
+ } = schema
20
+ const Type = types[type]
21
+ const paramName = query?.[name]
22
22
 
23
- if (!paramName && defaultValue !== undefined) {
24
- return { name, value: defaultValue };
25
- }
23
+ if (!paramName && defaultValue !== undefined) {
24
+ return { name, value: defaultValue }
25
+ }
26
26
 
27
- if (!paramName && mock && exampleValue !== undefined) {
28
- return { name, value: exampleValue };
29
- }
27
+ if (!paramName && mock && exampleValue !== undefined) {
28
+ return { name, value: exampleValue }
29
+ }
30
30
 
31
- if (!paramName) {
32
- return undefined;
33
- }
31
+ if (!paramName) {
32
+ return undefined
33
+ }
34
34
 
35
- if (Type === Boolean) {
36
- return {
37
- name,
38
- value: JSON.parse(paramName.toLowerCase()),
39
- };
40
- }
35
+ if (Type === Boolean) {
36
+ return {
37
+ name,
38
+ value: JSON.parse(paramName.toLowerCase())
39
+ }
40
+ }
41
41
 
42
- const value = new Type(paramName).valueOf();
43
- return { name, value };
44
- })
45
- .filter(Boolean)
46
- .reduce((acc, { name, value }) => {
47
- acc[name] = value;
48
- return acc;
49
- }, {});
42
+ const value = new Type(paramName).valueOf()
43
+ return { name, value }
44
+ })
45
+ .filter(Boolean)
46
+ .reduce((acc, { name, value }) => {
47
+ acc[name] = value
48
+ return acc
49
+ }, {})
package/src/router.js CHANGED
@@ -1,16 +1,17 @@
1
- import { OpenAPIBackend } from 'openapi-backend';
2
- import addFormats from 'ajv-formats';
3
- import { makeExpressCallback } from './express-callback.js';
4
- import { operationIds } from './operation-ids.js';
5
- import { notFound } from './handlers/not-found.js';
6
- import { requestValidation } from './handlers/request-validation.js';
7
- import { responseValidation } from './handlers/response-validation.js';
8
- import { unauthorized } from './handlers/unauthorized.js';
1
+ import { OpenAPIBackend } from 'openapi-backend'
2
+ import addFormats from 'ajv-formats'
3
+ import { makeExpressCallback } from './express-callback.js'
4
+ import { operationIds } from './operation-ids.js'
5
+ import { notFound } from './handlers/not-found.js'
6
+ import { requestValidation } from './handlers/request-validation.js'
7
+ import { responseValidation } from './handlers/response-validation.js'
8
+ import { unauthorized } from './handlers/unauthorized.js'
9
9
 
10
10
  /**
11
11
  * @typedef {import('./api.js').Logger} Logger
12
12
  * @typedef {import('./api.js').SecurityHandler} SecurityHandler
13
13
  * @typedef {import('ajv').Options} AjvOpts
14
+ * @typedef {import('openapi-backend').AjvCustomizer} AjvCustomizer
14
15
  */
15
16
 
16
17
  /**
@@ -25,70 +26,73 @@ import { unauthorized } from './handlers/unauthorized.js';
25
26
  * @param {object=} params.meta
26
27
  * @param {SecurityHandler[]=} params.securityHandlers
27
28
  * @param {AjvOpts=} params.ajvOptions
29
+ * @param {AjvCustomizer=} params.customizeAjv
28
30
  * @param {boolean=} params.mock
29
31
  * @returns {{ api: OpenAPIBackend<any>, openAPISpecification: object }}
30
32
  */
31
33
  export const setupRouter = ({
32
- openAPISpecification,
33
- controllers,
34
- apiRoot,
35
- strictSpecification,
36
- errorDetails,
37
- logger,
38
- meta,
39
- securityHandlers = [],
40
- ajvOptions = {},
41
- mock,
34
+ openAPISpecification,
35
+ controllers,
36
+ apiRoot,
37
+ strictSpecification,
38
+ errorDetails,
39
+ logger,
40
+ meta,
41
+ securityHandlers = [],
42
+ ajvOptions = {},
43
+ customizeAjv,
44
+ mock
42
45
  }) => {
43
- const api = new OpenAPIBackend({
44
- definition: openAPISpecification,
45
- apiRoot,
46
- strict: strictSpecification,
47
- ajvOpts: ajvOptions,
48
- customizeAjv: (originalAjv) => {
49
- addFormats(originalAjv);
50
- return originalAjv;
51
- },
52
- });
46
+ const ajvWithExtraFormats = (originalAjv) => {
47
+ addFormats(originalAjv)
48
+ return originalAjv
49
+ }
50
+ const api = new OpenAPIBackend({
51
+ definition: openAPISpecification,
52
+ apiRoot,
53
+ strict: strictSpecification,
54
+ ajvOpts: ajvOptions,
55
+ customizeAjv: customizeAjv || ajvWithExtraFormats
56
+ })
53
57
 
54
- api.register({
55
- unauthorizedHandler: unauthorized,
56
- validationFail: requestValidation,
57
- notFound,
58
- postResponseHandler: responseValidation,
59
- });
58
+ api.register({
59
+ unauthorizedHandler: unauthorized,
60
+ validationFail: requestValidation,
61
+ notFound,
62
+ postResponseHandler: responseValidation
63
+ })
60
64
 
61
- operationIds({ specification: openAPISpecification }).forEach(
62
- (operationId) => {
63
- if (!Object.hasOwn(controllers, operationId)) {
64
- return;
65
- }
66
- api.register(
67
- operationId,
68
- makeExpressCallback({
69
- controller: controllers[operationId],
70
- specification: openAPISpecification,
71
- errorDetails,
72
- logger,
73
- meta,
74
- mock,
75
- })
76
- );
77
- }
78
- );
65
+ operationIds({ specification: openAPISpecification }).forEach(
66
+ (operationId) => {
67
+ if (!Object.hasOwn(controllers, operationId)) {
68
+ return
69
+ }
70
+ api.register(
71
+ operationId,
72
+ makeExpressCallback({
73
+ controller: controllers[operationId],
74
+ specification: openAPISpecification,
75
+ errorDetails,
76
+ logger,
77
+ meta,
78
+ mock
79
+ })
80
+ )
81
+ }
82
+ )
79
83
 
80
- api.register('notImplemented', (context) => {
81
- const { mock: mockImplementation } =
82
- context.api.mockResponseForOperation(context.operation.operationId);
83
- return mockImplementation;
84
- });
84
+ api.register('notImplemented', (context) => {
85
+ const { mock: mockImplementation }
86
+ = context.api.mockResponseForOperation(context.operation.operationId)
87
+ return mockImplementation
88
+ })
85
89
 
86
- securityHandlers.forEach((securityHandler) => {
87
- api.registerSecurityHandler(
88
- securityHandler.name,
89
- securityHandler.handler
90
- );
91
- });
90
+ securityHandlers.forEach((securityHandler) => {
91
+ api.registerSecurityHandler(
92
+ securityHandler.name,
93
+ securityHandler.handler
94
+ )
95
+ })
92
96
 
93
- return { api, openAPISpecification };
94
- };
97
+ return { api, openAPISpecification }
98
+ }
package/src/server.js CHANGED
@@ -1,11 +1,13 @@
1
- import express from 'express';
2
- import cors from 'cors';
3
- import compression from 'compression';
4
- import helmet from 'helmet';
5
- import * as Sentry from '@sentry/node';
6
- import bodyParser from 'body-parser';
7
- import { openAPI } from './openapi.js';
8
- import { Api } from './api.js';
1
+ import express from 'express'
2
+ import cors from 'cors'
3
+ import compression from 'compression'
4
+ import helmet from 'helmet'
5
+ import * as Sentry from '@sentry/node'
6
+ import bodyParser from 'body-parser'
7
+ import { openAPI } from './openapi.js'
8
+ import { Api } from './api.js'
9
+
10
+ /* eslint-disable sonarjs/cors */
9
11
 
10
12
  /**
11
13
  * Get the origin resource policy
@@ -13,14 +15,14 @@ import { Api } from './api.js';
13
15
  * @returns {{ crossOriginResourcePolicy: { policy: string, directives: object } }}
14
16
  */
15
17
  const getOriginResourcePolicy = (origin) => ({
16
- crossOriginResourcePolicy: {
17
- policy: origin === '*' ? 'cross-origin' : 'same-origin',
18
- directives: {
19
- // ...
20
- 'require-trusted-types-for': ["'script'"],
21
- },
22
- },
23
- });
18
+ crossOriginResourcePolicy: {
19
+ policy: origin === '*' ? 'cross-origin' : 'same-origin',
20
+ directives: {
21
+ // ...
22
+ 'require-trusted-types-for': ['\'script\'']
23
+ }
24
+ }
25
+ })
24
26
 
25
27
  /**
26
28
  * @typedef {import('express-serve-static-core').Request} Request
@@ -70,58 +72,58 @@ const getOriginResourcePolicy = (origin) => ({
70
72
  * @returns {Promise<{ app: Express }>}
71
73
  */
72
74
  export const setupServer = async ({
73
- apis,
74
- origin = '*',
75
- staticFolder,
76
- sentry,
77
- poweredBy = 'TroJS',
78
- version = '1.0.0',
79
- middleware = [],
80
- maximumBodySize = undefined,
75
+ apis,
76
+ origin = '*',
77
+ staticFolder,
78
+ sentry,
79
+ poweredBy = 'TroJS',
80
+ version = '1.0.0',
81
+ middleware = [],
82
+ maximumBodySize = undefined
81
83
  }) => {
82
- const corsOptions = {
83
- origin,
84
- };
84
+ const corsOptions = {
85
+ origin
86
+ }
85
87
 
86
- const app = express();
88
+ const app = express()
87
89
 
88
- if (sentry) {
89
- Sentry.init({
90
- dsn: sentry.dsn,
91
- tracesSampleRate: sentry.tracesSampleRate || 1.0,
92
- profilesSampleRate: sentry.profilesSampleRate || 1.0,
93
- integrations: sentry.integrations || [],
94
- release: sentry.release,
95
- });
96
- }
90
+ if (sentry) {
91
+ Sentry.init({
92
+ dsn: sentry.dsn,
93
+ tracesSampleRate: sentry.tracesSampleRate || 1.0,
94
+ profilesSampleRate: sentry.profilesSampleRate || 1.0,
95
+ integrations: sentry.integrations || [],
96
+ release: sentry.release
97
+ })
98
+ }
97
99
 
98
- app.use(cors(corsOptions));
99
- app.use(compression());
100
- app.use(helmet(getOriginResourcePolicy(origin)));
101
- app.use(express.json({ limit: maximumBodySize }));
102
- middleware.forEach((fn) => app.use(fn));
103
- app.use(bodyParser.urlencoded({ extended: false, limit: maximumBodySize }));
104
- app.use((_request, response, next) => {
105
- response.setHeader('X-Powered-By', poweredBy);
106
- response.setHeader('X-Version', version);
107
- next();
108
- });
100
+ app.use(cors(corsOptions))
101
+ app.use(compression())
102
+ app.use(helmet(getOriginResourcePolicy(origin)))
103
+ app.use(express.json({ limit: maximumBodySize }))
104
+ middleware.forEach((fn) => app.use(fn))
105
+ app.use(bodyParser.urlencoded({ extended: false, limit: maximumBodySize }))
106
+ app.use((_request, response, next) => {
107
+ response.setHeader('X-Powered-By', poweredBy)
108
+ response.setHeader('X-Version', version)
109
+ next()
110
+ })
109
111
 
110
- if (staticFolder) {
111
- app.use(express.static(staticFolder));
112
- }
112
+ if (staticFolder) {
113
+ app.use(express.static(staticFolder))
114
+ }
113
115
 
114
- apis.forEach((api) => {
115
- const apiRoutes = new Api(api);
116
- const routes = apiRoutes.setup();
117
- app.use(`/${api.version}`, routes);
118
- });
116
+ apis.forEach((api) => {
117
+ const apiRoutes = new Api(api)
118
+ const routes = apiRoutes.setup()
119
+ app.use(`/${api.version}`, routes)
120
+ })
119
121
 
120
- if (sentry) {
121
- Sentry.setupExpressErrorHandler(app);
122
- }
122
+ if (sentry) {
123
+ Sentry.setupExpressErrorHandler(app)
124
+ }
123
125
 
124
- return { app };
125
- };
126
+ return { app }
127
+ }
126
128
 
127
- export { openAPI, Api };
129
+ export { openAPI, Api }
package/src/types.js CHANGED
@@ -1,12 +1,12 @@
1
1
  const types = {
2
- string: String,
3
- array: Array,
4
- object: Object,
5
- number: Number,
6
- integer: Number,
7
- boolean: Boolean,
8
- url: URL,
9
- date: Date,
10
- };
2
+ string: String,
3
+ array: Array,
4
+ object: Object,
5
+ number: Number,
6
+ integer: Number,
7
+ boolean: Boolean,
8
+ url: URL,
9
+ date: Date
10
+ }
11
11
 
12
- export { types };
12
+ export { types }