mock-config-server 1.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 (70) hide show
  1. package/README.md +213 -0
  2. package/dist/bin/mock-config-server.d.ts +2 -0
  3. package/dist/bin/mock-config-server.js +65 -0
  4. package/dist/bin/resolveExportsFromSourceCode.d.ts +1 -0
  5. package/dist/bin/resolveExportsFromSourceCode.js +11 -0
  6. package/dist/index.d.ts +1 -0
  7. package/dist/index.js +17 -0
  8. package/dist/jest.config.d.ts +3 -0
  9. package/dist/jest.config.js +7 -0
  10. package/dist/src/configs/isEntitiesEqual/isEntityValuesEqual.d.ts +2 -0
  11. package/dist/src/configs/isEntitiesEqual/isEntityValuesEqual.js +29 -0
  12. package/dist/src/configs/isEntitiesEqual/isEntityValuesEqual.test.d.ts +1 -0
  13. package/dist/src/configs/isEntitiesEqual/isEntityValuesEqual.test.js +25 -0
  14. package/dist/src/configs/prepareRequestConfigs/prepareRequestConfigs.d.ts +2 -0
  15. package/dist/src/configs/prepareRequestConfigs/prepareRequestConfigs.js +30 -0
  16. package/dist/src/configs/prepareRequestConfigs/prepareRequestConfigs.test.d.ts +1 -0
  17. package/dist/src/configs/prepareRequestConfigs/prepareRequestConfigs.test.js +151 -0
  18. package/dist/src/cors/corsMiddleware/corsMiddleware.d.ts +3 -0
  19. package/dist/src/cors/corsMiddleware/corsMiddleware.js +32 -0
  20. package/dist/src/cors/corsMiddleware/corsMiddleware.test.d.ts +1 -0
  21. package/dist/src/cors/corsMiddleware/corsMiddleware.test.js +86 -0
  22. package/dist/src/cors/getOrigins/getAllowedOrigins.d.ts +2 -0
  23. package/dist/src/cors/getOrigins/getAllowedOrigins.js +16 -0
  24. package/dist/src/cors/getOrigins/getAllowedOrigins.test.d.ts +1 -0
  25. package/dist/src/cors/getOrigins/getAllowedOrigins.test.js +24 -0
  26. package/dist/src/cors/noCorsMiddleware/noCorsMiddleware.d.ts +2 -0
  27. package/dist/src/cors/noCorsMiddleware/noCorsMiddleware.js +15 -0
  28. package/dist/src/cors/noCorsMiddleware/noCorsMiddleware.test.d.ts +1 -0
  29. package/dist/src/cors/noCorsMiddleware/noCorsMiddleware.test.js +22 -0
  30. package/dist/src/index.d.ts +3 -0
  31. package/dist/src/index.js +19 -0
  32. package/dist/src/routes/callRequestInterceptors/callRequestInterceptors.d.ts +12 -0
  33. package/dist/src/routes/callRequestInterceptors/callRequestInterceptors.js +13 -0
  34. package/dist/src/routes/callRequestInterceptors/callRequestInterceptors.test.d.ts +1 -0
  35. package/dist/src/routes/callRequestInterceptors/callRequestInterceptors.test.js +28 -0
  36. package/dist/src/routes/callResponseInterceptors/callResponseInterceptors.d.ts +14 -0
  37. package/dist/src/routes/callResponseInterceptors/callResponseInterceptors.js +31 -0
  38. package/dist/src/routes/callResponseInterceptors/callResponseInterceptors.test.d.ts +1 -0
  39. package/dist/src/routes/callResponseInterceptors/callResponseInterceptors.test.js +36 -0
  40. package/dist/src/routes/createRoutes/createRoutes.d.ts +3 -0
  41. package/dist/src/routes/createRoutes/createRoutes.js +43 -0
  42. package/dist/src/routes/createRoutes/createRoutes.test.d.ts +1 -0
  43. package/dist/src/routes/createRoutes/createRoutes.test.js +276 -0
  44. package/dist/src/server/createMockServer/createMockServer.d.ts +3 -0
  45. package/dist/src/server/createMockServer/createMockServer.js +35 -0
  46. package/dist/src/server/startMockServer/startMockServer.d.ts +2 -0
  47. package/dist/src/server/startMockServer/startMockServer.js +13 -0
  48. package/dist/src/static/staticMiddleware/staticMiddleware.d.ts +3 -0
  49. package/dist/src/static/staticMiddleware/staticMiddleware.js +29 -0
  50. package/dist/src/utils/constants/appPath.d.ts +1 -0
  51. package/dist/src/utils/constants/appPath.js +4 -0
  52. package/dist/src/utils/constants/default.d.ts +10 -0
  53. package/dist/src/utils/constants/default.js +13 -0
  54. package/dist/src/utils/constants/index.d.ts +2 -0
  55. package/dist/src/utils/constants/index.js +18 -0
  56. package/dist/src/utils/helpers/index.d.ts +2 -0
  57. package/dist/src/utils/helpers/index.js +18 -0
  58. package/dist/src/utils/helpers/isPlainObject.d.ts +1 -0
  59. package/dist/src/utils/helpers/isPlainObject.js +5 -0
  60. package/dist/src/utils/helpers/sleep.d.ts +1 -0
  61. package/dist/src/utils/helpers/sleep.js +7 -0
  62. package/dist/src/utils/types/configs.d.ts +34 -0
  63. package/dist/src/utils/types/configs.js +2 -0
  64. package/dist/src/utils/types/index.d.ts +3 -0
  65. package/dist/src/utils/types/index.js +19 -0
  66. package/dist/src/utils/types/interceptors.d.ts +15 -0
  67. package/dist/src/utils/types/interceptors.js +2 -0
  68. package/dist/src/utils/types/server.d.ts +24 -0
  69. package/dist/src/utils/types/server.js +2 -0
  70. package/package.json +99 -0
package/README.md ADDED
@@ -0,0 +1,213 @@
1
+ # 🎉 Mock Config Server
2
+
3
+ tool that easily and quickly imitates server operation, create full fake api in few steps
4
+
5
+ ## Install
6
+
7
+ Install with [npm](https://www.npmjs.com/) or [yarn](https://yarnpkg.com/)
8
+
9
+ ```bash
10
+ $ npm i mock-config-server --save --dev
11
+ # or
12
+ $ yarn add mock-config-server --dev
13
+ ```
14
+
15
+ ## 🦉 Philosophy
16
+
17
+ **🎉 Mock Config Server** it is a tool that, easily, quickly simulates the work of a server. The main difference from solutions such as [json-server](https://www.npmjs.com/package/json-server) and [mock-service-worker](https://mswjs.io/) is the ease of filling in data and flexible emulation of any and usual cases. Our goal is to create a simple and flexible system for users, with the help of which they can create, test, and support their products.
18
+
19
+ ## Features
20
+
21
+ - **TypeScript support out of the box** - full typed package
22
+ - **Full Rest Api support** - using simple configs of a certain format, you can easily simulate the operation of servers
23
+ - **CORS setup** - turn on and off CORS, fully customizable when CORS is turned on
24
+ - **Support for any kind of static** - server can return any type of static file if needed. Images, HTML, CSS, JSON, etc
25
+
26
+ ## Usage
27
+
28
+ Install **🎉 Mock Config Server** with [npm](https://www.npmjs.com/) or [yarn](https://yarnpkg.com/)
29
+
30
+ ```bash
31
+ $ npm i mock-config-server --save --dev
32
+ # or
33
+ $ yarn add mock-config-server --dev
34
+ ```
35
+
36
+ Create a `mock-server.config.js` file with server configuration
37
+
38
+ ```javascript
39
+ /** @type {import('mock-config-server').Mock.ServerConfig} */
40
+ const mockServerConfig: Mock.ServerConfig = {
41
+ configs: [
42
+ {
43
+ path: '/user',
44
+ method: 'get',
45
+ routes: [{ data: { emoji: '🦁', name: 'Nursultan' } }]
46
+ }
47
+ ]
48
+ };
49
+
50
+ module.exports = mockServerConfig;
51
+ ```
52
+
53
+ Start **🎉 Mock Config Server**
54
+
55
+ ```bash
56
+ $ mock-config-server
57
+
58
+ # 🎉 Mock Config Server is running at http://localhost:31299
59
+ ```
60
+
61
+ ## 🎭 Parameters for mock-server.config.(js|ts)
62
+
63
+ - `configs` {Array<RequestConfig>} configs for mock requests, [read](#configs)
64
+ - `staticPath?` {StaticPath} entity for working with static files, [read](#static-path)
65
+ - `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)
66
+ - `cors?` {Cors} CORS settings object (default: `CORS is turn off`), [read](#cors)
67
+ - `port?` {number} server port (default: `31299`)
68
+ - `baseUrl?` {string} part of the url that will be substituted at the beginning of the request url (default: `'/'`)
69
+
70
+ ### Configs
71
+
72
+ Configs are the fundamental part of the mock server. These configs are easy to fill and maintain. Config entities is an object with which you can emulate various application behaviors. You can specify `headers` | `query` | `params` | `body` to define what contract data you need to get. Using this mechanism, you can easily simulate the operation of the server and emulate various cases
73
+
74
+ ##### request config
75
+
76
+ - `path` {string | RegExp} request path
77
+ - `method` {GET | POST | DELETE | PUT | PATCH} rest api method
78
+ - `routes` {RouteConfig} request routes
79
+ - `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)
80
+
81
+ ##### route config
82
+
83
+ - `data` {any} mock data of request
84
+ - `entities?` Object<headers | query | params | body> object that helps in data retrieval
85
+ - `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)
86
+
87
+ ##### entities
88
+
89
+ ```typescript
90
+ interface Entities {
91
+ headers?: { [string]: string | number };
92
+ query?: { [string]: string | number };
93
+ params?: { [string]: string | number };
94
+ body?: any;
95
+ }
96
+ ```
97
+
98
+ ##### Example
99
+
100
+ ```javascript
101
+ /** @type {import('mock-config-server').MockServerConfig} */
102
+ const mockServerConfig = {
103
+ configs: [
104
+ {
105
+ path: '/user',
106
+ method: 'get',
107
+ routes: [
108
+ {
109
+ entities: {
110
+ headers: { 'name-header': 'Nursultan' }
111
+ },
112
+ data: { emoji: '🦁', name: 'Nursultan' }
113
+ },
114
+ {
115
+ entities: {
116
+ headers: { 'name-header': 'Dmitriy' }
117
+ },
118
+ data: { emoji: '☄', name: 'Dmitriy' }
119
+ }
120
+ ]
121
+ }
122
+ ]
123
+ };
124
+
125
+ module.exports = mockServerConfig;
126
+ ```
127
+
128
+ Now you can make a request with an additional header and get the desired result
129
+
130
+ ```javascript
131
+ fetch('http://localhost:31299/user', {
132
+ headers: { 'name-header': 'Nursultan' }
133
+ })
134
+ .then((response) => response.json())
135
+ .then((data) => console.log(data)); // { emoji: '🦁', name: 'Nursultan' }
136
+ ```
137
+
138
+ #### Static Path
139
+
140
+ Entity for connecting statics to the server, like HTML, JSON, PNG, etc.
141
+
142
+ - `string` path to your static files
143
+ - `Object<{prefix, path}`
144
+ - `prefix` {string} path prefix for request
145
+ - `path` {string} path to your static files
146
+ - `Array<string | Object<{prefix, path}>>`
147
+
148
+ #### Cors
149
+
150
+ Object with settings for [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). You can flexibly configure the required origin, methods, headers, credentials, maxAge for the entire server. If you do not specify `CORS` settings, then it will be disabled.
151
+
152
+ - `origin` {string | RegExp | Array<string | RegExp> | Function | Promise } available origins from which requests can be made
153
+ - `methods?` {Array<GET | POST | DELETE | PUT | PATCH>} available methods (default: `*`)
154
+ - `headers?` {Array<string>} available methods (default: `*`)
155
+ - `credentials?` {boolean} param tells browsers whether to expose the response to the frontend JavaScript code (default: `true`)
156
+ - `maxAge?` {number} how long the results can be cached (default: `3600`)
157
+
158
+ #### Interceptors
159
+
160
+ Functions to change request or response parameters
161
+
162
+ - `request?` (params) => void
163
+ - `response?` (data, params) => any
164
+
165
+ ##### Request
166
+
167
+ - `params`
168
+ - `request` request object
169
+
170
+ ##### Response
171
+
172
+ - `data` {any} mock data of request
173
+ - `params`
174
+ - `request` request object
175
+ - `response` response object
176
+ - `setDelay` (delay) => Promise<void>
177
+ - `delay` {number} seconds of delay time
178
+ - `setStatusCode` (statusCode) => void
179
+ - `statusCode` {number} status code for response
180
+
181
+ ## ✨ Contributors
182
+
183
+ <table>
184
+ <tr>
185
+ <td align="center" style="word-wrap: break-word; width: 100.0; height: 100.0">
186
+ <a href="https://github.com/debabin">
187
+ <img src="https://avatars.githubusercontent.com/u/45297354?v=4"
188
+ width="100;"
189
+ alt="debabin" />
190
+ <br />
191
+ <sub style="font-size:13px"><b>☄️ debabin</b></sub>
192
+ </a>
193
+ </td>
194
+ <td align="center" style="word-wrap: break-word; width: 100.0; height: 100.0">
195
+ <a href="https://github.com/MiaInturi">
196
+ <img src="https://avatars.githubusercontent.com/u/39031929?v=4"
197
+ width="100;"
198
+ alt="MiaInturi" />
199
+ <br />
200
+ <sub style="font-size:13px"><b>👹 MiaInturi</b></sub>
201
+ </a>
202
+ </td>
203
+ <td align="center" style="word-wrap: break-word; width: 100.0; height: 100.0">
204
+ <a href="https://github.com/RiceWithMeat">
205
+ <img src="https://avatars.githubusercontent.com/u/47690223?v=4"
206
+ width="100;"
207
+ alt="RiceWithMeat" />
208
+ <br />
209
+ <sub style="font-size:13px"><b>🐘 RiceWithMeat</b></sub>
210
+ </a>
211
+ </td>
212
+ </tr>
213
+ </table>
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,65 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k;
5
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
+ }
9
+ Object.defineProperty(o, k2, desc);
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
16
+ }) : function(o, v) {
17
+ o["default"] = v;
18
+ });
19
+ var __importStar = (this && this.__importStar) || function (mod) {
20
+ if (mod && mod.__esModule) return mod;
21
+ var result = {};
22
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
23
+ __setModuleDefault(result, mod);
24
+ return result;
25
+ };
26
+ Object.defineProperty(exports, "__esModule", { value: true });
27
+ const esbuild_1 = require("esbuild");
28
+ const fs = __importStar(require("fs"));
29
+ const src_1 = require("../src");
30
+ const resolveExportsFromSourceCode_1 = require("./resolveExportsFromSourceCode");
31
+ const start = async () => {
32
+ try {
33
+ const appPath = process.cwd();
34
+ const mockServerConfigFileRegex = /mock-server.config.(?:ts|js)/;
35
+ const mockServerConfigFile = fs
36
+ .readdirSync(appPath)
37
+ .find((file) => mockServerConfigFileRegex.test(file));
38
+ if (!mockServerConfigFile) {
39
+ throw new Error('Cannot find config file mock-server.config.(ts|js)');
40
+ }
41
+ const { outputFiles } = await (0, esbuild_1.build)({
42
+ entryPoints: [mockServerConfigFile],
43
+ bundle: true,
44
+ platform: 'node',
45
+ target: 'esnext',
46
+ minifySyntax: true,
47
+ minify: true,
48
+ write: false,
49
+ metafile: false
50
+ });
51
+ const mockServerConfigSourceCode = outputFiles[0]?.text;
52
+ if (!mockServerConfigSourceCode) {
53
+ throw new Error('Cannot handle source code of mock-server.config.(ts|js)');
54
+ }
55
+ const mockServerConfigExports = (0, resolveExportsFromSourceCode_1.resolveExportsFromSourceCode)(mockServerConfigSourceCode);
56
+ if (!mockServerConfigExports?.default) {
57
+ throw new Error('Cannot handle exports of mock-server.config.(ts|js)');
58
+ }
59
+ (0, src_1.startMockServer)(mockServerConfigExports.default);
60
+ }
61
+ catch (e) {
62
+ console.error(e.message);
63
+ }
64
+ };
65
+ start();
@@ -0,0 +1 @@
1
+ export declare const resolveExportsFromSourceCode: (sourceCode: string) => any;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveExportsFromSourceCode = void 0;
4
+ const resolveExportsFromSourceCode = (sourceCode) => {
5
+ // @ts-ignore
6
+ const moduleInstance = new module.constructor();
7
+ // eslint-disable-next-line no-underscore-dangle
8
+ moduleInstance._compile(sourceCode, '');
9
+ return moduleInstance.exports;
10
+ };
11
+ exports.resolveExportsFromSourceCode = resolveExportsFromSourceCode;
@@ -0,0 +1 @@
1
+ export * from './src';
package/dist/index.js ADDED
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./src"), exports);
@@ -0,0 +1,3 @@
1
+ export = jestConfig;
2
+ /** @type {import('ts-jest').JestConfigWithTsJest} */
3
+ declare const jestConfig: import('ts-jest').JestConfigWithTsJest;
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ /** @type {import('ts-jest').JestConfigWithTsJest} */
3
+ const jestConfig = {
4
+ preset: 'ts-jest',
5
+ testEnvironment: 'node'
6
+ };
7
+ module.exports = jestConfig;
@@ -0,0 +1,2 @@
1
+ import type { Entities, EntitiesValues } from '../../utils/types';
2
+ export declare const isEntityValuesEqual: <Entity extends Entities>(firstEntityValue: EntitiesValues[Entity], secondEntityValue: EntitiesValues[Entity]) => boolean;
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isEntityValuesEqual = void 0;
4
+ const flat_1 = require("flat");
5
+ const helpers_1 = require("../../utils/helpers");
6
+ const isEntityValuesEqual = (firstEntityValue, secondEntityValue) => {
7
+ const isValuesArePlainObjects = (0, helpers_1.isPlainObject)(firstEntityValue) && (0, helpers_1.isPlainObject)(secondEntityValue);
8
+ if (isValuesArePlainObjects) {
9
+ const flattenFirstEntityValue = (0, flat_1.flatten)(firstEntityValue);
10
+ const flattenSecondEntityValue = (0, flat_1.flatten)(secondEntityValue);
11
+ return Object.keys(flattenFirstEntityValue).every((key) =>
12
+ // ✅ important:
13
+ // call 'toString' for ignore types of values
14
+ flattenFirstEntityValue[key].toString() === flattenSecondEntityValue[key]?.toString());
15
+ }
16
+ const isValuesAreArrays = Array.isArray(firstEntityValue) && Array.isArray(secondEntityValue);
17
+ if (isValuesAreArrays) {
18
+ const flattenFirstEntityValue = (0, flat_1.flatten)(firstEntityValue);
19
+ const flattenSecondEntityValue = (0, flat_1.flatten)(secondEntityValue);
20
+ return (Object.keys(flattenFirstEntityValue).length ===
21
+ Object.keys(flattenSecondEntityValue).length &&
22
+ Object.keys(flattenFirstEntityValue).every((key) =>
23
+ // ✅ important:
24
+ // call 'toString' for ignore types of values
25
+ flattenFirstEntityValue[key].toString() === flattenSecondEntityValue[key].toString()));
26
+ }
27
+ return firstEntityValue.toString() === secondEntityValue.toString();
28
+ };
29
+ exports.isEntityValuesEqual = isEntityValuesEqual;
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const isEntityValuesEqual_1 = require("./isEntityValuesEqual");
4
+ describe('isEntityValuesEqual', () => {
5
+ test('Primitive values should compare independent of their types', () => {
6
+ expect((0, isEntityValuesEqual_1.isEntityValuesEqual)(13, '13')).toBe(true);
7
+ expect((0, isEntityValuesEqual_1.isEntityValuesEqual)(true, 'true')).toBe(true);
8
+ });
9
+ test('Arrays should be full equal with nested objects (independent of primitive values types)', () => {
10
+ expect((0, isEntityValuesEqual_1.isEntityValuesEqual)([1, 2, 3], ['1', '2', '3'])).toBe(true);
11
+ expect((0, isEntityValuesEqual_1.isEntityValuesEqual)([{ key1: 'value1', key2: 'value2' }], [{ key2: 'value2', key1: 'value1' }])).toBe(true);
12
+ expect((0, isEntityValuesEqual_1.isEntityValuesEqual)([{ key1: 'value1', key2: 'value2' }], [{ key1: 'value1', key2: 'value2', key3: 'value3' }])).toBe(false);
13
+ expect((0, isEntityValuesEqual_1.isEntityValuesEqual)([{ key1: 'value1', key2: { nestedKey1: 'nestedValue1' } }], [{ key1: 'value1', key2: { nestedKey1: 'nestedValue1' } }])).toBe(true);
14
+ expect((0, isEntityValuesEqual_1.isEntityValuesEqual)([{ key1: 'value1', key2: { nestedKey1: 'nestedValue1' } }], [{ key1: 'value1', key2: { nestedKey1: 'nestedValue1', nestedKey2: 'nestedValue2' } }])).toBe(false);
15
+ });
16
+ test('Plain objects should compare by "second includes first" with nested objects', () => {
17
+ expect((0, isEntityValuesEqual_1.isEntityValuesEqual)({ key1: 'value1', key2: 'value2' }, { key1: 'value1', key2: 'value2', key3: 'value3' })).toBe(true);
18
+ expect((0, isEntityValuesEqual_1.isEntityValuesEqual)({ key1: 'value1', key2: 'value2', key3: 'value3' }, { key1: 'value1', key2: 'value2' })).toBe(false);
19
+ expect((0, isEntityValuesEqual_1.isEntityValuesEqual)({ key1: 'value1', key2: { nestedKey1: 'nestedValue1' } }, {
20
+ key1: 'value1',
21
+ key2: { nestedKey1: 'nestedValue1', nestedKey2: 'nestedValue2' },
22
+ key3: 'value3'
23
+ })).toBe(true);
24
+ });
25
+ });
@@ -0,0 +1,2 @@
1
+ import type { RequestConfig } from '../../utils/types';
2
+ export declare const prepareRequestConfigs: (requestConfigs: RequestConfig[]) => RequestConfig[];
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.prepareRequestConfigs = void 0;
4
+ const helpers_1 = require("../../utils/helpers");
5
+ const calculateRouteConfigWeight = (routeConfig) => {
6
+ const { entities } = routeConfig;
7
+ if (!entities)
8
+ return 0;
9
+ let routeConfigWeight = 0;
10
+ const { headers, query, params, body } = entities;
11
+ if (headers)
12
+ routeConfigWeight += Object.keys(headers).length;
13
+ if (query)
14
+ routeConfigWeight += Object.keys(query).length;
15
+ if (params)
16
+ routeConfigWeight += Object.keys(params).length;
17
+ if (body)
18
+ routeConfigWeight += (0, helpers_1.isPlainObject)(body) ? Object.keys(body).length : 1;
19
+ return routeConfigWeight;
20
+ };
21
+ const prepareRequestConfigs = (requestConfigs) => {
22
+ requestConfigs.forEach((requestConfig) => {
23
+ requestConfig.routes.sort((first, second) =>
24
+ // ✅ important:
25
+ // Lift more specific configs for correct working of routes
26
+ calculateRouteConfigWeight(second) - calculateRouteConfigWeight(first));
27
+ });
28
+ return requestConfigs;
29
+ };
30
+ exports.prepareRequestConfigs = prepareRequestConfigs;
@@ -0,0 +1,151 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const prepareRequestConfigs_1 = require("./prepareRequestConfigs");
4
+ describe('prepareRequestConfigs', () => {
5
+ test('Should not sort routes if they does not contain entities', () => {
6
+ const requestConfigs = [
7
+ {
8
+ path: '/user',
9
+ method: 'get',
10
+ routes: [
11
+ {
12
+ data: { name: 'John', surname: 'Doe' }
13
+ },
14
+ {
15
+ data: { name: 'John', surname: 'Smith' }
16
+ },
17
+ {
18
+ data: { name: 'John', surname: 'John' }
19
+ }
20
+ ]
21
+ }
22
+ ];
23
+ expect((0, prepareRequestConfigs_1.prepareRequestConfigs)(requestConfigs)).toStrictEqual(requestConfigs);
24
+ });
25
+ test('Should sort routes by their specificity of entities', () => {
26
+ const requestConfigs = [
27
+ {
28
+ path: '/user',
29
+ method: 'get',
30
+ routes: [
31
+ {
32
+ entities: {
33
+ headers: {
34
+ header1: 'value'
35
+ }
36
+ },
37
+ data: { name: 'John', surname: 'Doe' }
38
+ },
39
+ {
40
+ entities: {
41
+ headers: {
42
+ header1: 'value',
43
+ header2: 'value'
44
+ }
45
+ },
46
+ data: { name: 'John', surname: 'Doe' }
47
+ },
48
+ {
49
+ entities: {
50
+ headers: {
51
+ header1: 'value'
52
+ },
53
+ query: {
54
+ query1: 'value',
55
+ query2: 'value'
56
+ }
57
+ },
58
+ data: { name: 'John', surname: 'Doe' }
59
+ }
60
+ ]
61
+ }
62
+ ];
63
+ const expectedRequestConfigs = [
64
+ {
65
+ path: '/user',
66
+ method: 'get',
67
+ routes: [
68
+ {
69
+ entities: {
70
+ headers: {
71
+ header1: 'value'
72
+ },
73
+ query: {
74
+ query1: 'value',
75
+ query2: 'value'
76
+ }
77
+ },
78
+ data: { name: 'John', surname: 'Doe' }
79
+ },
80
+ {
81
+ entities: {
82
+ headers: {
83
+ header1: 'value',
84
+ header2: 'value'
85
+ }
86
+ },
87
+ data: { name: 'John', surname: 'Doe' }
88
+ },
89
+ {
90
+ entities: {
91
+ headers: {
92
+ header1: 'value'
93
+ }
94
+ },
95
+ data: { name: 'John', surname: 'Doe' }
96
+ }
97
+ ]
98
+ }
99
+ ];
100
+ expect((0, prepareRequestConfigs_1.prepareRequestConfigs)(requestConfigs)).toStrictEqual(expectedRequestConfigs);
101
+ });
102
+ test('Should set not object body weight equals to one', () => {
103
+ const requestConfigs = [
104
+ {
105
+ path: '/user',
106
+ method: 'post',
107
+ routes: [
108
+ {
109
+ entities: {
110
+ body: ['value', 'value', 'value']
111
+ },
112
+ data: { name: 'John', surname: 'Doe' }
113
+ },
114
+ {
115
+ entities: {
116
+ headers: {
117
+ header1: 'value',
118
+ header2: 'value'
119
+ }
120
+ },
121
+ data: { name: 'John', surname: 'Doe' }
122
+ }
123
+ ]
124
+ }
125
+ ];
126
+ const expectedRequestConfigs = [
127
+ {
128
+ path: '/user',
129
+ method: 'post',
130
+ routes: [
131
+ {
132
+ entities: {
133
+ headers: {
134
+ header1: 'value',
135
+ header2: 'value'
136
+ }
137
+ },
138
+ data: { name: 'John', surname: 'Doe' }
139
+ },
140
+ {
141
+ entities: {
142
+ body: ['value', 'value', 'value']
143
+ },
144
+ data: { name: 'John', surname: 'Doe' }
145
+ }
146
+ ]
147
+ }
148
+ ];
149
+ expect((0, prepareRequestConfigs_1.prepareRequestConfigs)(requestConfigs)).toStrictEqual(expectedRequestConfigs);
150
+ });
151
+ });
@@ -0,0 +1,3 @@
1
+ import type { Express } from 'express';
2
+ import type { Cors } from '../../utils/types';
3
+ export declare const corsMiddleware: (server: Express, cors: Cors) => Promise<void>;
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.corsMiddleware = void 0;
4
+ const constants_1 = require("../../utils/constants");
5
+ const getAllowedOrigins_1 = require("../getOrigins/getAllowedOrigins");
6
+ const corsMiddleware = async (server, cors) => {
7
+ server.use(async (req, res, next) => {
8
+ if (Array.isArray(cors.origin) && !cors.origin.length) {
9
+ return next();
10
+ }
11
+ const allowedOrigins = await (0, getAllowedOrigins_1.getAllowedOrigins)(cors.origin);
12
+ const { origin } = req.headers;
13
+ if (!allowedOrigins?.length || !origin) {
14
+ return next();
15
+ }
16
+ const isAllowedOrigin = allowedOrigins.some((allowedOrigin) => {
17
+ if (typeof allowedOrigin === 'string') {
18
+ return allowedOrigin.includes(origin);
19
+ }
20
+ return allowedOrigin.test(origin);
21
+ });
22
+ if (isAllowedOrigin) {
23
+ res.setHeader('Access-Control-Allow-Origin', origin);
24
+ res.setHeader('Access-Control-Allow-Methods', cors.methods ?? constants_1.DEFAULT.CORS.METHODS);
25
+ res.setHeader('Access-Control-Allow-Headers', cors.headers ?? constants_1.DEFAULT.CORS.HEADERS);
26
+ res.setHeader('Access-Control-Allow-Credentials', `${cors.credentials ?? constants_1.DEFAULT.CORS.CREDENTIALS}`);
27
+ res.setHeader('Access-Control-Max-Age', cors.maxAge ?? constants_1.DEFAULT.CORS.MAX_AGE);
28
+ }
29
+ next();
30
+ });
31
+ };
32
+ exports.corsMiddleware = corsMiddleware;