mock-config-server 2.4.0 → 3.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 (78) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +502 -326
  3. package/dist/bin/validateMockServerConfig/helpers/index.d.ts +2 -0
  4. package/dist/bin/validateMockServerConfig/helpers/index.js +18 -0
  5. package/dist/bin/validateMockServerConfig/helpers/isCheckModeValid/index.d.ts +1 -0
  6. package/dist/bin/validateMockServerConfig/helpers/isCheckModeValid/index.js +17 -0
  7. package/dist/bin/validateMockServerConfig/helpers/isCheckModeValid/isCheckModeValid.d.ts +1 -0
  8. package/dist/bin/validateMockServerConfig/helpers/isCheckModeValid/isCheckModeValid.js +10 -0
  9. package/dist/bin/validateMockServerConfig/helpers/isDescriptorValueValid/index.d.ts +1 -0
  10. package/dist/bin/validateMockServerConfig/helpers/isDescriptorValueValid/index.js +17 -0
  11. package/dist/bin/validateMockServerConfig/helpers/isDescriptorValueValid/isDescriptorValueValid.d.ts +1 -0
  12. package/dist/bin/validateMockServerConfig/helpers/isDescriptorValueValid/isDescriptorValueValid.js +23 -0
  13. package/dist/bin/validateMockServerConfig/validateGraphqlConfig/validateRoutes/validateRoutes.js +44 -18
  14. package/dist/bin/validateMockServerConfig/validateRestConfig/validateRoutes/validateRoutes.js +38 -42
  15. package/dist/src/core/graphql/createGraphQLRoutes/createGraphQLRoutes.js +17 -6
  16. package/dist/src/core/graphql/createGraphQLRoutes/helpers/prepareGraphQLRequestConfigs/prepareGraphQLRequestConfigs.js +7 -2
  17. package/dist/src/core/middlewares/corsMiddleware/corsMiddleware.js +6 -5
  18. package/dist/src/core/middlewares/errorMiddleware/errorMiddleware.d.ts +2 -0
  19. package/dist/src/core/middlewares/errorMiddleware/errorMiddleware.js +18 -0
  20. package/dist/src/core/middlewares/index.d.ts +1 -0
  21. package/dist/src/core/middlewares/index.js +1 -0
  22. package/dist/src/core/middlewares/notFoundMiddleware/notFoundMiddleware.d.ts +1 -6
  23. package/dist/src/core/middlewares/notFoundMiddleware/notFoundMiddleware.js +1 -1
  24. package/dist/src/core/middlewares/requestInterceptorMiddleware/requestInterceptorMiddleware.js +2 -2
  25. package/dist/src/core/rest/createRestRoutes/createRestRoutes.js +19 -3
  26. package/dist/src/core/rest/createRestRoutes/helpers/prepareRestRequestConfigs/prepareRestRequestConfigs.js +6 -1
  27. package/dist/src/server/createMockServer/createMockServer.js +2 -4
  28. package/dist/src/static/views/assets/icons/scheme-dark.svg +3 -3
  29. package/dist/src/static/views/assets/icons/scheme-light.svg +3 -3
  30. package/dist/src/static/views/assets/images/404.png +0 -0
  31. package/dist/src/static/views/assets/images/logo.png +0 -0
  32. package/dist/src/static/views/assets/styles/global.css +88 -88
  33. package/dist/src/static/views/components/header/index.css +55 -55
  34. package/dist/src/static/views/components/header/index.ejs +39 -39
  35. package/dist/src/static/views/features/scheme/dark.css +12 -12
  36. package/dist/src/static/views/features/scheme/index.ejs +3 -3
  37. package/dist/src/static/views/features/scheme/light.css +12 -12
  38. package/dist/src/static/views/features/tab/index.css +30 -30
  39. package/dist/src/static/views/features/tab/index.ejs +1 -1
  40. package/dist/src/static/views/pages/404/index.css +10 -10
  41. package/dist/src/static/views/pages/404/index.ejs +84 -84
  42. package/dist/src/utils/constants/checkModes.d.ts +9 -0
  43. package/dist/src/utils/constants/checkModes.js +31 -0
  44. package/dist/src/utils/constants/default.js +1 -1
  45. package/dist/src/utils/constants/index.d.ts +1 -0
  46. package/dist/src/utils/constants/index.js +1 -0
  47. package/dist/src/utils/helpers/asyncHandler.d.ts +2 -0
  48. package/dist/src/utils/helpers/asyncHandler.js +5 -0
  49. package/dist/src/utils/helpers/config/index.d.ts +1 -1
  50. package/dist/src/utils/helpers/config/index.js +1 -1
  51. package/dist/src/utils/helpers/config/resolveEntityValues/resolveEntityValues.d.ts +2 -0
  52. package/dist/src/utils/helpers/config/resolveEntityValues/resolveEntityValues.js +131 -0
  53. package/dist/src/utils/helpers/entities/convertToEntityDescriptor/convertToEntityDescriptor.d.ts +2 -0
  54. package/dist/src/utils/helpers/entities/convertToEntityDescriptor/convertToEntityDescriptor.js +8 -0
  55. package/dist/src/utils/helpers/entities/index.d.ts +2 -0
  56. package/dist/src/utils/helpers/entities/index.js +18 -0
  57. package/dist/src/utils/helpers/entities/isEntityDescriptor/isEntityDescriptor.d.ts +1 -0
  58. package/dist/src/utils/helpers/entities/isEntityDescriptor/isEntityDescriptor.js +6 -0
  59. package/dist/src/utils/helpers/index.d.ts +4 -0
  60. package/dist/src/utils/helpers/index.js +4 -0
  61. package/dist/src/utils/helpers/isPlainObject/isPlainObject.js +4 -1
  62. package/dist/src/utils/helpers/isPrimitive/isPrimitive.d.ts +2 -0
  63. package/dist/src/utils/helpers/isPrimitive/isPrimitive.js +5 -0
  64. package/dist/src/utils/helpers/isRegExp/isRegExp.d.ts +1 -0
  65. package/dist/src/utils/helpers/isRegExp/isRegExp.js +5 -0
  66. package/dist/src/utils/types/checkModes.d.ts +12 -0
  67. package/dist/src/utils/types/checkModes.js +2 -0
  68. package/dist/src/utils/types/graphql.d.ts +58 -18
  69. package/dist/src/utils/types/index.d.ts +1 -0
  70. package/dist/src/utils/types/index.js +1 -0
  71. package/dist/src/utils/types/interceptors.d.ts +4 -3
  72. package/dist/src/utils/types/rest.d.ts +61 -23
  73. package/dist/src/utils/types/server.d.ts +4 -3
  74. package/dist/src/utils/types/values.d.ts +1 -7
  75. package/package.json +113 -113
  76. package/dist/src/static/views/assets/images/success.png +0 -0
  77. package/dist/src/utils/helpers/config/isEntitiesEqual/isEntityValuesEqual.d.ts +0 -1
  78. package/dist/src/utils/helpers/config/isEntitiesEqual/isEntityValuesEqual.js +0 -29
package/README.md CHANGED
@@ -1,326 +1,502 @@
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 rest operation of servers
23
- - **GraphQL support** - using simple configs of a certain format, you can easily simulate graphlql operation of servers
24
- - **CORS setup** - turn on and off CORS, fully customizable when CORS is turned on
25
- - **Support for any kind of static** - server can return any type of static file if needed. Images, HTML, CSS, JSON, etc
26
-
27
- ## Usage
28
-
29
- Install **🎉 Mock Config Server** with [npm](https://www.npmjs.com/) or [yarn](https://yarnpkg.com/)
30
-
31
- ```bash
32
- $ npm i mock-config-server --save --dev
33
- # or
34
- $ yarn add mock-config-server --dev
35
- ```
36
-
37
- Create a `mock-server.config.js` file with server configuration
38
-
39
- ```javascript
40
- /** @type {import('mock-config-server').MockServerConfig} */
41
- const mockServerConfig = {
42
- rest: {
43
- baseUrl: '/api',
44
- configs: [
45
- {
46
- path: '/user',
47
- method: 'get',
48
- routes: [{ data: { emoji: '🦁', name: 'Nursultan' } }]
49
- }
50
- ]
51
- }
52
- };
53
-
54
- export default mockServerConfig;
55
- ```
56
-
57
- Start **🎉 Mock Config Server**
58
-
59
- ```bash
60
- $ npx mock-config-server
61
- ```
62
-
63
- > If the package is already installed you can use short command `mcs`
64
-
65
- ## 🎭 Parameters for mock-server.config.(js|ts)
66
-
67
- - `rest?` Rest configs for mock requests
68
- - `baseUrl?` {string} part of the url that will be substituted at the beginning of rest request url (default: `'/'`)
69
- - `configs` {Array<RestRequestConfig>} configs for mock requests, [read](#configs)
70
- - `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)
71
- - `graphql?` GraphQL configs for mock requests
72
- - `baseUrl?` {string} part of the url that will be substituted at the beginning of graphql request url (default: `'/'`)
73
- - `configs` {Array<GraphQLRequestConfig>} configs for mock requests, [read](#configs)
74
- - `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)
75
- - `staticPath?` {StaticPath} entity for working with static files, [read](#static-path)
76
- - `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)
77
- - `cors?` {Cors} CORS settings object (default: `CORS is turn off`), [read](#cors)
78
- - `port?` {number} server port (default: `31299`)
79
- - `baseUrl?` {string} part of the url that will be substituted at the beginning of the request url (default: `'/'`)
80
-
81
- ### Configs
82
-
83
- 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` | `cookies` | `query` | `params` | `body` for Rest request or `headers` | `cookies` | `query` | `variables` for GraphQL request 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
84
-
85
- ##### Rest request config
86
-
87
- - `path` {string | RegExp} request path
88
- - `method` {GET | POST | DELETE | PUT | PATCH} rest api method
89
- - `routes` {RestRouteConfig[]} request routes
90
- - `data` {any} mock data of request
91
- - `entities?` Object<headers | cookies | query | params | body> object that helps in data retrieval
92
- - `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)
93
- - `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)
94
-
95
- ##### GraphQL request config
96
-
97
- - `operationType` {query | mutation} graphql operation type
98
- - `operationName` {string} graphql operation name
99
- - `routes` {GraphQLRouteConfig[]} request routes
100
- - `data` {any} mock data of request
101
- - `entities?` Object<headers | cookies | query | variables> object that helps in data retrieval
102
- - `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)
103
- - `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)
104
-
105
- ##### Rest example
106
-
107
- ```javascript
108
- /** @type {import('mock-config-server').MockServerConfig} */
109
- const mockServerConfig = {
110
- rest: {
111
- baseUrl: '/api',
112
- configs: [
113
- {
114
- path: '/user',
115
- method: 'get',
116
- routes: [
117
- {
118
- entities: {
119
- headers: { 'name-header': 'Nursultan' }
120
- },
121
- data: { emoji: '🦁', name: 'Nursultan' }
122
- },
123
- {
124
- entities: {
125
- headers: { 'name-header': 'Dmitriy' }
126
- },
127
- data: { emoji: '☄', name: 'Dmitriy' }
128
- }
129
- ]
130
- }
131
- ]
132
- }
133
- };
134
-
135
- module.exports = mockServerConfig;
136
- ```
137
-
138
- Now you can make a request with an additional header and get the desired result
139
-
140
- ```javascript
141
- fetch('http://localhost:31299/api/user', {
142
- headers: {
143
- 'name-header': 'Nursultan',
144
- 'Content-Type': 'application/json'
145
- }
146
- })
147
- .then((response) => response.json())
148
- .then((data) => console.log(data)); // { emoji: '🦁', name: 'Nursultan' }
149
- ```
150
-
151
- ##### GraphQL example
152
-
153
- ```javascript
154
- /** @type {import('mock-config-server').MockServerConfig} */
155
- const mockServerConfig = {
156
- graphql: {
157
- baseUrl: '/graphql',
158
- configs: [
159
- {
160
- operationType: 'query',
161
- operationName: 'GetUser',
162
- routes: [
163
- {
164
- entities: {
165
- headers: { 'name-header': 'Nursultan' }
166
- },
167
- data: { emoji: '🦁', name: 'Nursultan' }
168
- },
169
- {
170
- entities: {
171
- headers: { 'name-header': 'Dmitriy' }
172
- },
173
- data: { emoji: '☄', name: 'Dmitriy' }
174
- }
175
- ]
176
- }
177
- ]
178
- }
179
- };
180
-
181
- module.exports = mockServerConfig;
182
- ```
183
-
184
- Now you can make a request with an additional header and get the desired result
185
-
186
- ```javascript
187
- const body = JSON.stringify({
188
- query: 'query GetUser { name }'
189
- });
190
-
191
- fetch('http://localhost:31299/graphql', {
192
- method: 'POST',
193
- headers: {
194
- 'name-header': 'Nursultan',
195
- 'Content-Type': 'application/json'
196
- },
197
- body
198
- })
199
- .then((response) => response.json())
200
- .then((data) => console.log(data)); // { emoji: '🦁', name: 'Nursultan' }
201
- ```
202
-
203
- #### Static Path
204
-
205
- Entity for connecting statics to the server, like HTML, JSON, PNG, etc.
206
-
207
- - `string` path to your static files
208
- - `Object<{prefix, path}`
209
- - `prefix` {string} path prefix for request
210
- - `path` {string} path to your static files
211
- - `Array<string | Object<{prefix, path}>>`
212
-
213
- #### Cors
214
-
215
- 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.
216
-
217
- - `origin` {string | RegExp | Array<string | RegExp> | Function | Promise } available origins from which requests can be made
218
- - `methods?` {Array<GET | POST | DELETE | PUT | PATCH>} available methods (default: `GET,OPTIONS,PUT,PATCH,POST,DELETE`)
219
- - `allowedHeaders?` {Array<string>} allowed headers (default: `*`)
220
- - `exposedHeaders?` {Array<string>} exposed headers (default: `*`)
221
- - `credentials?` {boolean} param tells browsers whether to expose the response to the frontend JavaScript code (default: `true`)
222
- - `maxAge?` {number} how long the results can be cached (default: `3600`)
223
-
224
- #### Interceptors
225
-
226
- Functions to change request or response parameters
227
-
228
- - `request?` (params) => void
229
- - `response?` (data, params) => any
230
-
231
- ##### Request
232
-
233
- - `params`
234
- - `request` request object
235
- - `setDelay` (delay) => Promise<void>
236
- - `delay` {number} milliseconds of delay time
237
- - `getHeader` (field) => string | number | string[] | undefined
238
- - `field` {string} name of response header
239
- - `getHeaders` () => Record<string | number | string[] | undefined>
240
- - `getCookie` (name) => string | undefined
241
- - `name` {string} name of cookie
242
-
243
- ##### Response
244
-
245
- - `data` {any} mock data of request
246
- - `params`
247
- - `request` request object
248
- - `response` response object
249
- - `setDelay` (delay) => Promise<void>
250
- - `delay` {number} milliseconds of delay time
251
- - `setStatusCode` (statusCode) => void
252
- - `statusCode` {number} status code for response
253
- - `setHeader` (field, value) => void
254
- - `field` {string} name of response header
255
- - `value` {string | string[] | undefined} value of response header
256
- - `appendHeader` (field, value) => void
257
- - `field` {string} name of response header
258
- - `value` {string | string[] | undefined} value of response header
259
- - `getHeader` (field) => string | number | string[] | undefined
260
- - `field` {string} name of response header
261
- - `getHeaders` () => Record<string | number | string[] | undefined>
262
- - `setCookie` (name, value, options) => void
263
- - `name` {string} name of cookie
264
- - `value` {string} value of cookie
265
- - `options` {[CookieOptions](https://expressjs.com/en/resources/middleware/cookie-session.html) | undefined} cookie options (like path, expires, etc.)
266
- - `getCookie` (name) => string | undefined
267
- - `name` {string} name of cookie
268
- - `clearCookie` (name, options) => void
269
- - `name` {string} name of cookie
270
- - `options` {[CookieOptions](https://expressjs.com/en/resources/middleware/cookie-session.html) | undefined} cookie options (like path, expires, etc.)
271
- - `attachment` (filename) => void
272
- - `filename` {string} name of file in 'Content-Disposition' header
273
-
274
- ## CLI usage
275
-
276
- ```
277
- mcs [options]
278
-
279
- Options:
280
- --baseUrl, -b Set base url (default: '/')
281
- --port, -p Set port (default: 31299)
282
- --staticPath, -s Set static path
283
- --config, -c Set path to config file (default: './mock-server.config.(?:ts|mts|cts|js|mjs|cjs)')
284
- --watch, -w Enables server restart after config file changes (default: false)
285
-
286
- --version, -v Show version number
287
- --help, -h Show help
288
-
289
- Examples:
290
- mcs --baseurl /base/url --port 3000 --config ./path/to/config.ts -w
291
- mcs --help
292
- ```
293
-
294
- ## ✨ Contributors
295
-
296
- <table>
297
- <tr>
298
- <td align="center" style="word-wrap: break-word; width: 100.0; height: 100.0">
299
- <a href="https://github.com/debabin">
300
- <img src="https://avatars.githubusercontent.com/u/45297354?v=4"
301
- width="100;"
302
- alt="debabin" />
303
- <br />
304
- <sub style="font-size:13px"><b>☄️ debabin</b></sub>
305
- </a>
306
- </td>
307
- <td align="center" style="word-wrap: break-word; width: 100.0; height: 100.0">
308
- <a href="https://github.com/MiaInturi">
309
- <img src="https://avatars.githubusercontent.com/u/39031929?v=4"
310
- width="100;"
311
- alt="MiaInturi" />
312
- <br />
313
- <sub style="font-size:13px"><b>👹 MiaInturi</b></sub>
314
- </a>
315
- </td>
316
- <td align="center" style="word-wrap: break-word; width: 100.0; height: 100.0">
317
- <a href="https://github.com/RiceWithMeat">
318
- <img src="https://avatars.githubusercontent.com/u/47690223?v=4"
319
- width="100;"
320
- alt="RiceWithMeat" />
321
- <br />
322
- <sub style="font-size:13px"><b>🐘 RiceWithMeat</b></sub>
323
- </a>
324
- </td>
325
- </tr>
326
- </table>
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 rest operation of servers
23
+ - **GraphQL support** - using simple configs of a certain format, you can easily simulate graphlql operation of servers
24
+ - **CORS setup** - turn on and off CORS, fully customizable when CORS is turned on
25
+ - **Support for any kind of static** - server can return any type of static file if needed. Images, HTML, CSS, JSON, etc
26
+
27
+ ## Usage
28
+
29
+ Install **🎉 Mock Config Server** with [npm](https://www.npmjs.com/) or [yarn](https://yarnpkg.com/)
30
+
31
+ ```bash
32
+ $ npm i mock-config-server --save --dev
33
+ # or
34
+ $ yarn add mock-config-server --dev
35
+ ```
36
+
37
+ Create a `mock-server.config.js` file with server configuration
38
+
39
+ ```javascript
40
+ /** @type {import('mock-config-server').MockServerConfig} */
41
+ const mockServerConfig = {
42
+ rest: {
43
+ baseUrl: '/api',
44
+ configs: [
45
+ {
46
+ path: '/user',
47
+ method: 'get',
48
+ routes: [{ data: { emoji: '🦁', name: 'Nursultan' } }]
49
+ }
50
+ ]
51
+ }
52
+ };
53
+
54
+ export default mockServerConfig;
55
+ ```
56
+
57
+ Start **🎉 Mock Config Server**
58
+
59
+ ```bash
60
+ $ npx mock-config-server
61
+ ```
62
+
63
+ > If the package is already installed you can use short command `mcs`
64
+
65
+ ## 🎭 Parameters for mock-server.config.(js|ts)
66
+
67
+ - `rest?` Rest configs for mock requests
68
+ - `baseUrl?` {string} part of the url that will be substituted at the beginning of rest request url (default: `'/'`)
69
+ - `configs` {Array<RestRequestConfig>} configs for mock requests, [read](#configs)
70
+ - `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)
71
+ - `graphql?` GraphQL configs for mock requests
72
+ - `baseUrl?` {string} part of the url that will be substituted at the beginning of graphql request url (default: `'/'`)
73
+ - `configs` {Array<GraphQLRequestConfig>} configs for mock requests, [read](#configs)
74
+ - `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)
75
+ - `staticPath?` {StaticPath} entity for working with static files, [read](#static-path)
76
+ - `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)
77
+ - `cors?` {Cors} CORS settings object (default: `CORS is turn off`), [read](#cors)
78
+ - `port?` {number} server port (default: `31299`)
79
+ - `baseUrl?` {string} part of the url that will be substituted at the beginning of the request url (default: `'/'`)
80
+
81
+ ### Configs
82
+
83
+ 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` | `cookies` | `query` | `params` | `body` for Rest request or `headers` | `cookies` | `query` | `variables` for GraphQL request 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
84
+
85
+ ##### Rest request config
86
+
87
+ - `path` {string | RegExp} request path
88
+ - `method` {GET | POST | DELETE | PUT | PATCH} rest api method
89
+ - `routes` {RestRouteConfig[]} request routes
90
+ - `data` {any} mock data of request
91
+ - `entities?` Object<headers | cookies | query | params | body> object that helps in data retrieval
92
+ - `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)
93
+ - `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)
94
+
95
+ ##### GraphQL request config
96
+
97
+ - `operationType` {query | mutation} graphql operation type
98
+ - `operationName` {string} graphql operation name
99
+ - `routes` {GraphQLRouteConfig[]} request routes
100
+ - `data` {any} mock data of request
101
+ - `entities?` Object<headers | cookies | query | variables> object that helps in data retrieval
102
+ - `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)
103
+ - `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)
104
+
105
+ ##### Rest example
106
+
107
+ ```javascript
108
+ /** @type {import('mock-config-server').MockServerConfig} */
109
+ const mockServerConfig = {
110
+ rest: {
111
+ baseUrl: '/api',
112
+ configs: [
113
+ {
114
+ path: '/user',
115
+ method: 'get',
116
+ routes: [
117
+ {
118
+ entities: {
119
+ headers: { 'name-header': 'Nursultan' }
120
+ },
121
+ data: { emoji: '🦁', name: 'Nursultan' }
122
+ },
123
+ {
124
+ entities: {
125
+ headers: { 'name-header': 'Dmitriy' }
126
+ },
127
+ data: { emoji: '☄', name: 'Dmitriy' }
128
+ }
129
+ ]
130
+ }
131
+ ]
132
+ }
133
+ };
134
+
135
+ module.exports = mockServerConfig;
136
+ ```
137
+
138
+ Now you can make a request with an additional header and get the desired result
139
+
140
+ ```javascript
141
+ fetch('http://localhost:31299/api/user', {
142
+ headers: {
143
+ 'name-header': 'Nursultan',
144
+ 'Content-Type': 'application/json'
145
+ }
146
+ })
147
+ .then((response) => response.json())
148
+ .then((data) => console.log(data)); // { emoji: '🦁', name: 'Nursultan' }
149
+ ```
150
+
151
+ ##### GraphQL example
152
+
153
+ ```javascript
154
+ /** @type {import('mock-config-server').MockServerConfig} */
155
+ const mockServerConfig = {
156
+ graphql: {
157
+ baseUrl: '/graphql',
158
+ configs: [
159
+ {
160
+ operationType: 'query',
161
+ operationName: 'GetUser',
162
+ routes: [
163
+ {
164
+ entities: {
165
+ headers: { 'name-header': 'Nursultan' }
166
+ },
167
+ data: { emoji: '🦁', name: 'Nursultan' }
168
+ },
169
+ {
170
+ entities: {
171
+ headers: { 'name-header': 'Dmitriy' }
172
+ },
173
+ data: { emoji: '☄', name: 'Dmitriy' }
174
+ }
175
+ ]
176
+ }
177
+ ]
178
+ }
179
+ };
180
+
181
+ module.exports = mockServerConfig;
182
+ ```
183
+
184
+ Now you can make a request with an additional header and get the desired result
185
+
186
+ ```javascript
187
+ const body = JSON.stringify({
188
+ query: 'query GetUser { name }'
189
+ });
190
+
191
+ fetch('http://localhost:31299/graphql', {
192
+ method: 'POST',
193
+ headers: {
194
+ 'name-header': 'Nursultan',
195
+ 'Content-Type': 'application/json'
196
+ },
197
+ body
198
+ })
199
+ .then((response) => response.json())
200
+ .then((data) => console.log(data)); // { emoji: '🦁', name: 'Nursultan' }
201
+ ```
202
+
203
+ #### Entity descriptors
204
+
205
+ If you need more complex logic for matching entities, you can use entity descriptors.
206
+ Descriptor is an object with `checkMode` and `value` fields that describe how the correctness of the actual entity is calculated.
207
+
208
+ Allowed `checkModes`
209
+ - equals - checks actual value for equality with descriptor value (default).
210
+ - notEquals - checks actual value for non-equality with descriptor value.
211
+ - exists - checks actual value for existence i.e. any value.
212
+ - notExists - checks actual value for non-existence i.e. undefined value.
213
+ - includes - checks actual value for including with descriptor value.
214
+ - notIncludes - checks actual value for non-including with descriptor value.
215
+ - startsWith - checks actual value for starting with descriptor value.
216
+ - notStartsWith - checks actual value for non-starting with descriptor value.
217
+ - endsWith - checks actual value for ending with descriptor value.
218
+ - notEndsWith - checks actual value for non-ending with descriptor value.
219
+ - regExp - checks actual value with descriptor regExp.
220
+ - function - checks actual value with descriptor function.
221
+
222
+ Value for `checkMode` except `function` | `exists` | `notExists` can be array, so you can write even more complex logic. For example "does not contain these values" or "must be match to one of these regExp".
223
+
224
+ ```javascript
225
+ /** @type {import('mock-config-server').MockServerConfig} */
226
+ const mockServerConfig = {
227
+ rest: {
228
+ baseUrl: '/api',
229
+ configs: [
230
+ {
231
+ path: '/user',
232
+ method: 'get',
233
+ routes: [
234
+ {
235
+ entities: {
236
+ headers: {
237
+ // 'name-header' is 'Dmitriy' or 'Nursultan'
238
+ 'name-header': {
239
+ checkMode: 'equals',
240
+ value: ['Dmitriy', 'Nursultan']
241
+ },
242
+ // check for 'equals' if descriptor not provided
243
+ role: 'developer'
244
+ },
245
+ cookies: {
246
+ // any 'token' cookie
247
+ token: {
248
+ checkMode: 'exists'
249
+ },
250
+ // 'someSecretToken' cookie can be '123-abc' or 'abc-999' for example
251
+ someSecretToken: {
252
+ checkMode: 'regExp',
253
+ value: [/^\d\d\d-abc$/, /^abc-\d\d\d$/]
254
+ }
255
+ }
256
+ },
257
+ data: 'Some user data for Dmitriy and Nursultan'
258
+ }
259
+ ]
260
+ }
261
+ ]
262
+ }
263
+ }
264
+
265
+ module.exports = mockServerConfig;
266
+ ```
267
+
268
+ `function checkMode` is the most powerful way to describe your `entities` logic, but in most cases you will be fine using other `checkModes`.
269
+
270
+ `Function value` has the following signature `(actualValue, checkFunction) => boolean`.
271
+ Return `true` if `actualValue` matches your logic or `false` otherwise.
272
+
273
+ You can use the `checkFunction` from second argument if you want to describe your logic in a more declarative way.
274
+ `checkFunction` has the following signature `(checkMode, actualValue, descriptorValue?) => boolean`.
275
+
276
+ ##### Using descriptors for part of REST body or GraphQL variables
277
+
278
+ If you want to check a certain field of your body or variables, you can use descriptors in flatten object style. In this case server will check every field in entity with corresponding actual field.
279
+ You can use descriptors for array body elements as well.
280
+
281
+ ```javascript
282
+ /** @type {import('mock-config-server').MockServerConfig} */
283
+ const mockServerConfig = {
284
+ rest: {
285
+ baseUrl: '/api',
286
+ configs: [
287
+ {
288
+ path: '/users',
289
+ method: 'post',
290
+ routes: [
291
+ {
292
+ entities: {
293
+ body: {
294
+ 'user.name': 'Sergey'
295
+ }
296
+ },
297
+ data: 'user.name in body is "Sergey"'
298
+ }
299
+ ]
300
+ },
301
+ {
302
+ path: '/posts',
303
+ method: 'post',
304
+ routes: [
305
+ {
306
+ entities: {
307
+ body: {
308
+ 'title': {
309
+ checkMode: 'startsWith',
310
+ value: 'A'
311
+ }
312
+ }
313
+ },
314
+ data: 'title in body starts with "A"'
315
+ }
316
+ ]
317
+ },
318
+ {
319
+ path: '/posts',
320
+ method: 'post',
321
+ routes: [
322
+ {
323
+ entities: {
324
+ body: [
325
+ {
326
+ checkMode: 'startsWith',
327
+ value: 1
328
+ },
329
+ 2
330
+ ]
331
+ },
332
+ data: 'array[0] starts with "1" and array[1] equals "2"'
333
+ }
334
+ ]
335
+ }
336
+ ]
337
+ }
338
+ }
339
+
340
+ module.exports = mockServerConfig;
341
+ ```
342
+
343
+ > To enable whole body/variables checking as plain object you should use descriptor for entire body/variables.
344
+
345
+ ```javascript
346
+ /** @type {import('mock-config-server').MockServerConfig} */
347
+ const mockServerConfig = {
348
+ rest: {
349
+ baseUrl: '/api',
350
+ configs: [
351
+ {
352
+ path: '/users',
353
+ method: 'post',
354
+ routes: [
355
+ {
356
+ entities: {
357
+ body: {
358
+ checkMode: 'equals',
359
+ value: {
360
+ user: {
361
+ name: 'Sergey',
362
+ emoji: '🐘',
363
+ roles: ['developer', 'moderator']
364
+ }
365
+ }
366
+ }
367
+ },
368
+ data: 'your body is strictly equals object from body entity value'
369
+ }
370
+ ]
371
+ }
372
+ ]
373
+ }
374
+ }
375
+
376
+ module.exports = mockServerConfig;
377
+ ```
378
+
379
+ #### Static Path
380
+
381
+ Entity for connecting statics to the server, like HTML, JSON, PNG, etc.
382
+
383
+ - `string` path to your static files
384
+ - `Object<{prefix, path}`
385
+ - `prefix` {string} path prefix for request
386
+ - `path` {string} path to your static files
387
+ - `Array<string | Object<{prefix, path}>>`
388
+
389
+ #### Cors
390
+
391
+ 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.
392
+
393
+ - `origin` {string | RegExp | Array<string | RegExp> | Function | Promise } available origins from which requests can be made
394
+ - `methods?` {Array<GET | POST | DELETE | PUT | PATCH>} available methods (default: `GET,OPTIONS,PUT,PATCH,POST,DELETE`)
395
+ - `allowedHeaders?` {Array<string>} allowed headers (default: `*`)
396
+ - `exposedHeaders?` {Array<string>} exposed headers (default: `*`)
397
+ - `credentials?` {boolean} param tells browsers whether to expose the response to the frontend JavaScript code (default: `true`)
398
+ - `maxAge?` {number} how long the results can be cached (default: `3600`)
399
+
400
+ #### Interceptors
401
+
402
+ Functions to change request or response parameters
403
+
404
+ - `request?` (params) => void
405
+ - `response?` (data, params) => any
406
+
407
+ ##### Request
408
+
409
+ - `params`
410
+ - `request` request object
411
+ - `setDelay` (delay) => Promise<void>
412
+ - `delay` {number} milliseconds of delay time
413
+ - `getHeader` (field) => string | number | string[] | undefined
414
+ - `field` {string} name of response header
415
+ - `getHeaders` () => Record<string | number | string[] | undefined>
416
+ - `getCookie` (name) => string | undefined
417
+ - `name` {string} name of cookie
418
+
419
+ ##### Response
420
+
421
+ - `data` {any} mock data of request
422
+ - `params`
423
+ - `request` request object
424
+ - `response` response object
425
+ - `setDelay` (delay) => Promise<void>
426
+ - `delay` {number} milliseconds of delay time
427
+ - `setStatusCode` (statusCode) => void
428
+ - `statusCode` {number} status code for response
429
+ - `setHeader` (field, value) => void
430
+ - `field` {string} name of response header
431
+ - `value` {string | string[] | undefined} value of response header
432
+ - `appendHeader` (field, value) => void
433
+ - `field` {string} name of response header
434
+ - `value` {string | string[] | undefined} value of response header
435
+ - `getHeader` (field) => string | number | string[] | undefined
436
+ - `field` {string} name of response header
437
+ - `getHeaders` () => Record<string | number | string[] | undefined>
438
+ - `setCookie` (name, value, options) => void
439
+ - `name` {string} name of cookie
440
+ - `value` {string} value of cookie
441
+ - `options` {[CookieOptions](https://expressjs.com/en/resources/middleware/cookie-session.html) | undefined} cookie options (like path, expires, etc.)
442
+ - `getCookie` (name) => string | undefined
443
+ - `name` {string} name of cookie
444
+ - `clearCookie` (name, options) => void
445
+ - `name` {string} name of cookie
446
+ - `options` {[CookieOptions](https://expressjs.com/en/resources/middleware/cookie-session.html) | undefined} cookie options (like path, expires, etc.)
447
+ - `attachment` (filename) => void
448
+ - `filename` {string} name of file in 'Content-Disposition' header
449
+
450
+ ## CLI usage
451
+
452
+ ```
453
+ mcs [options]
454
+
455
+ Options:
456
+ --baseUrl, -b Set base url (default: '/')
457
+ --port, -p Set port (default: 31299)
458
+ --staticPath, -s Set static path
459
+ --config, -c Set path to config file (default: './mock-server.config.(?:ts|mts|cts|js|mjs|cjs)')
460
+ --watch, -w Enables server restart after config file changes (default: false)
461
+
462
+ --version, -v Show version number
463
+ --help, -h Show help
464
+
465
+ Examples:
466
+ mcs --baseurl /base/url --port 3000 --config ./path/to/config.ts -w
467
+ mcs --help
468
+ ```
469
+
470
+ ## ✨ Contributors
471
+
472
+ <table>
473
+ <tr>
474
+ <td align="center" style="word-wrap: break-word; width: 100.0; height: 100.0">
475
+ <a href="https://github.com/debabin">
476
+ <img src="https://avatars.githubusercontent.com/u/45297354?v=4"
477
+ width="100;"
478
+ alt="debabin" />
479
+ <br />
480
+ <sub style="font-size:13px"><b>☄️ debabin</b></sub>
481
+ </a>
482
+ </td>
483
+ <td align="center" style="word-wrap: break-word; width: 100.0; height: 100.0">
484
+ <a href="https://github.com/MiaInturi">
485
+ <img src="https://avatars.githubusercontent.com/u/39031929?v=4"
486
+ width="100;"
487
+ alt="MiaInturi" />
488
+ <br />
489
+ <sub style="font-size:13px"><b>👹 MiaInturi</b></sub>
490
+ </a>
491
+ </td>
492
+ <td align="center" style="word-wrap: break-word; width: 100.0; height: 100.0">
493
+ <a href="https://github.com/RiceWithMeat">
494
+ <img src="https://avatars.githubusercontent.com/u/47690223?v=4"
495
+ width="100;"
496
+ alt="RiceWithMeat" />
497
+ <br />
498
+ <sub style="font-size:13px"><b>🐘 RiceWithMeat</b></sub>
499
+ </a>
500
+ </td>
501
+ </tr>
502
+ </table>