mock-config-server 3.0.1 → 3.1.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 (146) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +614 -502
  3. package/dist/bin/bin.js +8 -3
  4. package/dist/bin/build.js +51 -45
  5. package/dist/bin/cli.js +37 -44
  6. package/dist/bin/helpers/index.js +36 -17
  7. package/dist/bin/helpers/resolveConfigFile.js +20 -17
  8. package/dist/bin/helpers/resolveConfigFilePath.js +12 -35
  9. package/dist/bin/helpers/resolveExportsFromSourceCode.js +11 -8
  10. package/dist/bin/resolveConfigFilePath/resolveConfigFilePath.js +12 -35
  11. package/dist/bin/run.js +17 -12
  12. package/dist/bin/validateMockServerConfig/helpers/index.js +25 -16
  13. package/dist/bin/validateMockServerConfig/helpers/isCheckModeValid/index.js +14 -15
  14. package/dist/bin/validateMockServerConfig/helpers/isCheckModeValid/isCheckModeValid.js +8 -6
  15. package/dist/bin/validateMockServerConfig/helpers/isDescriptorValueValid/index.js +14 -15
  16. package/dist/bin/validateMockServerConfig/helpers/isDescriptorValueValid/isDescriptorValueValid.js +15 -18
  17. package/dist/bin/validateMockServerConfig/validateBaseUrl/validateBaseUrl.js +12 -9
  18. package/dist/bin/validateMockServerConfig/validateCors/validateCors.js +75 -73
  19. package/dist/bin/validateMockServerConfig/validateDatabaseConfig/validateDatabaseConfig.d.ts +1 -0
  20. package/dist/bin/validateMockServerConfig/validateDatabaseConfig/validateDatabaseConfig.js +45 -0
  21. package/dist/bin/validateMockServerConfig/validateGraphqlConfig/validateGraphqlConfig.js +47 -43
  22. package/dist/bin/validateMockServerConfig/validateGraphqlConfig/validateRoutes/validateRoutes.js +90 -83
  23. package/dist/bin/validateMockServerConfig/validateInterceptors/validateInterceptors.js +22 -16
  24. package/dist/bin/validateMockServerConfig/validateMockServerConfig.js +29 -27
  25. package/dist/bin/validateMockServerConfig/validatePort/validatePort.js +9 -6
  26. package/dist/bin/validateMockServerConfig/validateRestConfig/validateRestConfig.js +52 -47
  27. package/dist/bin/validateMockServerConfig/validateRestConfig/validateRoutes/validateRoutes.js +94 -87
  28. package/dist/bin/validateMockServerConfig/validateStaticPath/validateStaticPath.js +43 -34
  29. package/dist/index.js +14 -15
  30. package/dist/src/core/database/createDatabaseRoutes/createDatabaseRoutes.d.ts +3 -0
  31. package/dist/src/core/database/createDatabaseRoutes/createDatabaseRoutes.js +33 -0
  32. package/dist/src/core/database/createDatabaseRoutes/helpers/array/createNewId/createNewId.d.ts +4 -0
  33. package/dist/src/core/database/createDatabaseRoutes/helpers/array/createNewId/createNewId.js +16 -0
  34. package/dist/src/core/database/createDatabaseRoutes/helpers/array/findIndexById/findIndexById.d.ts +4 -0
  35. package/dist/src/core/database/createDatabaseRoutes/helpers/array/findIndexById/findIndexById.js +8 -0
  36. package/dist/src/core/database/createDatabaseRoutes/helpers/array/index.d.ts +3 -0
  37. package/dist/src/core/database/createDatabaseRoutes/helpers/array/index.js +38 -0
  38. package/dist/src/core/database/createDatabaseRoutes/helpers/array/isIndex/isIndex.d.ts +1 -0
  39. package/dist/src/core/database/createDatabaseRoutes/helpers/array/isIndex/isIndex.js +8 -0
  40. package/dist/src/core/database/createDatabaseRoutes/helpers/createNestedDatabaseRoutes/createNestedDatabaseRoutes.d.ts +4 -0
  41. package/dist/src/core/database/createDatabaseRoutes/helpers/createNestedDatabaseRoutes/createNestedDatabaseRoutes.js +88 -0
  42. package/dist/src/core/database/createDatabaseRoutes/helpers/createRewrittenDatabaseRoutes/createRewrittenDatabaseRoutes.d.ts +2 -0
  43. package/dist/src/core/database/createDatabaseRoutes/helpers/createRewrittenDatabaseRoutes/createRewrittenDatabaseRoutes.js +12 -0
  44. package/dist/src/core/database/createDatabaseRoutes/helpers/createShallowDatabaseRoutes/createShallowDatabaseRoutes.d.ts +4 -0
  45. package/dist/src/core/database/createDatabaseRoutes/helpers/createShallowDatabaseRoutes/createShallowDatabaseRoutes.js +38 -0
  46. package/dist/src/core/database/createDatabaseRoutes/helpers/index.d.ts +5 -0
  47. package/dist/src/core/database/createDatabaseRoutes/helpers/index.js +60 -0
  48. package/dist/src/core/database/createDatabaseRoutes/helpers/splitDatabaseByNesting/splitDatabaseByNesting.d.ts +5 -0
  49. package/dist/src/core/database/createDatabaseRoutes/helpers/splitDatabaseByNesting/splitDatabaseByNesting.js +30 -0
  50. package/dist/src/core/database/createDatabaseRoutes/storages/File/FileStorage.d.ts +11 -0
  51. package/dist/src/core/database/createDatabaseRoutes/storages/File/FileStorage.js +64 -0
  52. package/dist/src/core/database/createDatabaseRoutes/storages/File/FileWriter.d.ts +11 -0
  53. package/dist/src/core/database/createDatabaseRoutes/storages/File/FileWriter.js +58 -0
  54. package/dist/src/core/database/createDatabaseRoutes/storages/Memory/MemoryStorage.d.ts +10 -0
  55. package/dist/src/core/database/createDatabaseRoutes/storages/Memory/MemoryStorage.js +54 -0
  56. package/dist/src/core/database/createDatabaseRoutes/storages/index.d.ts +2 -0
  57. package/dist/src/core/database/createDatabaseRoutes/storages/index.js +27 -0
  58. package/dist/src/core/database/index.d.ts +1 -0
  59. package/dist/src/core/database/index.js +16 -0
  60. package/dist/src/core/graphql/createGraphQLRoutes/createGraphQLRoutes.js +96 -83
  61. package/dist/src/core/graphql/createGraphQLRoutes/helpers/index.js +14 -15
  62. package/dist/src/core/graphql/createGraphQLRoutes/helpers/prepareGraphQLRequestConfigs/prepareGraphQLRequestConfigs.js +36 -30
  63. package/dist/src/core/graphql/index.js +14 -15
  64. package/dist/src/core/middlewares/cookieParseMiddleware/cookieParseMiddleware.js +15 -13
  65. package/dist/src/core/middlewares/cookieParseMiddleware/helpers/index.js +14 -15
  66. package/dist/src/core/middlewares/cookieParseMiddleware/helpers/parseCookie/parseCookie.js +16 -14
  67. package/dist/src/core/middlewares/corsMiddleware/corsMiddleware.js +48 -41
  68. package/dist/src/core/middlewares/corsMiddleware/helpers/getAllowedOrigins/getAllowedOrigins.js +13 -10
  69. package/dist/src/core/middlewares/corsMiddleware/helpers/index.js +14 -15
  70. package/dist/src/core/middlewares/destroyerMiddleware/destroyerMiddleware.js +21 -18
  71. package/dist/src/core/middlewares/errorMiddleware/errorMiddleware.js +18 -15
  72. package/dist/src/core/middlewares/index.js +92 -23
  73. package/dist/src/core/middlewares/noCorsMiddleware/noCorsMiddleware.js +21 -21
  74. package/dist/src/core/middlewares/notFoundMiddleware/helpers/getGraphqlUrlSuggestions/getGraphqlUrlSuggestions.js +24 -16
  75. package/dist/src/core/middlewares/notFoundMiddleware/helpers/getLevenshteinDistance/getLevenshteinDistance.js +78 -74
  76. package/dist/src/core/middlewares/notFoundMiddleware/helpers/getRestUrlSuggestions/getRestUrlSuggestions.js +36 -31
  77. package/dist/src/core/middlewares/notFoundMiddleware/helpers/getRestUrlSuggestions/helpers/getActualRestUrlMeaningfulString/getActualRestUrlMeaningfulString.js +6 -5
  78. package/dist/src/core/middlewares/notFoundMiddleware/helpers/getRestUrlSuggestions/helpers/getPatternRestUrlMeaningfulString/getPatternRestUrlMeaningfulString.js +6 -3
  79. package/dist/src/core/middlewares/notFoundMiddleware/helpers/getRestUrlSuggestions/helpers/index.js +25 -16
  80. package/dist/src/core/middlewares/notFoundMiddleware/helpers/index.js +36 -17
  81. package/dist/src/core/middlewares/notFoundMiddleware/notFoundMiddleware.js +63 -48
  82. package/dist/src/core/middlewares/requestInterceptorMiddleware/requestInterceptorMiddleware.js +13 -7
  83. package/dist/src/core/middlewares/staticMiddleware/staticMiddleware.js +26 -25
  84. package/dist/src/core/rest/createRestRoutes/createRestRoutes.js +71 -56
  85. package/dist/src/core/rest/createRestRoutes/helpers/index.js +14 -15
  86. package/dist/src/core/rest/createRestRoutes/helpers/prepareRestRequestConfigs/prepareRestRequestConfigs.js +38 -32
  87. package/dist/src/core/rest/index.js +14 -15
  88. package/dist/src/index.js +36 -17
  89. package/dist/src/server/createMockServer/createMockServer.js +74 -53
  90. package/dist/src/server/index.js +25 -16
  91. package/dist/src/server/startMockServer/startMockServer.js +20 -17
  92. package/dist/src/static/views/assets/icons/scheme-dark.svg +3 -3
  93. package/dist/src/static/views/assets/icons/scheme-light.svg +3 -3
  94. package/dist/src/static/views/assets/styles/global.css +88 -88
  95. package/dist/src/static/views/components/header/index.css +55 -55
  96. package/dist/src/static/views/components/header/index.ejs +39 -39
  97. package/dist/src/static/views/components/header/index.js +1 -1
  98. package/dist/src/static/views/features/scheme/dark.css +12 -12
  99. package/dist/src/static/views/features/scheme/index.ejs +3 -3
  100. package/dist/src/static/views/features/scheme/index.js +31 -31
  101. package/dist/src/static/views/features/scheme/light.css +12 -12
  102. package/dist/src/static/views/features/tab/index.css +30 -30
  103. package/dist/src/static/views/features/tab/index.ejs +1 -1
  104. package/dist/src/static/views/features/tab/index.js +12 -12
  105. package/dist/src/static/views/pages/404/index.css +10 -10
  106. package/dist/src/static/views/pages/404/index.ejs +84 -84
  107. package/dist/src/utils/constants/appPath.js +6 -2
  108. package/dist/src/utils/constants/checkModes.js +21 -30
  109. package/dist/src/utils/constants/default.js +15 -11
  110. package/dist/src/utils/constants/index.js +36 -17
  111. package/dist/src/utils/helpers/asyncHandler.js +6 -3
  112. package/dist/src/utils/helpers/config/index.js +14 -15
  113. package/dist/src/utils/helpers/config/resolveEntityValues/resolveEntityValues.js +109 -122
  114. package/dist/src/utils/helpers/entities/convertToEntityDescriptor/convertToEntityDescriptor.js +10 -6
  115. package/dist/src/utils/helpers/entities/index.js +25 -16
  116. package/dist/src/utils/helpers/entities/isEntityDescriptor/isEntityDescriptor.js +7 -4
  117. package/dist/src/utils/helpers/graphql/getGraphQLInput/getGraphQLInput.js +28 -18
  118. package/dist/src/utils/helpers/graphql/index.js +36 -17
  119. package/dist/src/utils/helpers/graphql/parseGraphQLRequest/parseGraphQLRequest.js +11 -9
  120. package/dist/src/utils/helpers/graphql/parseQuery/parseQuery.js +20 -17
  121. package/dist/src/utils/helpers/index.js +114 -25
  122. package/dist/src/utils/helpers/interceptors/callRequestInterceptor/callRequestInterceptor.js +22 -16
  123. package/dist/src/utils/helpers/interceptors/callResponseInterceptors/callResponseInterceptors.js +56 -48
  124. package/dist/src/utils/helpers/interceptors/helpers/setDelay.js +8 -5
  125. package/dist/src/utils/helpers/interceptors/index.js +25 -16
  126. package/dist/src/utils/helpers/isPlainObject/isPlainObject.js +6 -6
  127. package/dist/src/utils/helpers/isPrimitive/isPrimitive.js +6 -3
  128. package/dist/src/utils/helpers/isRegExp/isRegExp.js +6 -3
  129. package/dist/src/utils/helpers/sleep.js +7 -4
  130. package/dist/src/utils/helpers/url/convertWin32PathToUnix/convertWin32PathToUnix.js +6 -6
  131. package/dist/src/utils/helpers/url/getUrlParts/getUrlParts.js +7 -4
  132. package/dist/src/utils/helpers/url/index.js +47 -18
  133. package/dist/src/utils/helpers/url/removeLeadingAndTrailingSlashes/removeLeadingAndTrailingSlashes.js +6 -3
  134. package/dist/src/utils/helpers/url/urlJoin/urlJoin.js +11 -10
  135. package/dist/src/utils/types/checkModes.js +1 -2
  136. package/dist/src/utils/types/database.d.ts +6 -0
  137. package/dist/src/utils/types/database.js +1 -0
  138. package/dist/src/utils/types/graphql.js +1 -2
  139. package/dist/src/utils/types/index.d.ts +1 -0
  140. package/dist/src/utils/types/index.js +80 -20
  141. package/dist/src/utils/types/interceptors.js +1 -2
  142. package/dist/src/utils/types/rest.js +1 -2
  143. package/dist/src/utils/types/server.d.ts +5 -0
  144. package/dist/src/utils/types/server.js +1 -2
  145. package/dist/src/utils/types/values.js +1 -2
  146. package/package.json +130 -113
package/README.md CHANGED
@@ -1,502 +1,614 @@
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>
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
+ - **Database** - use mock database with all CRUD operations
25
+ - **CORS setup** - turn on and off CORS, fully customizable when CORS is turned on
26
+ - **Support for any kind of static** - server can return any type of static file if needed. Images, HTML, CSS, JSON, etc
27
+
28
+ ## Usage
29
+
30
+ Install **🎉 Mock Config Server** with [npm](https://www.npmjs.com/) or [yarn](https://yarnpkg.com/)
31
+
32
+ ```bash
33
+ $ npm i mock-config-server --save --dev
34
+ # or
35
+ $ yarn add mock-config-server --dev
36
+ ```
37
+
38
+ Create a `mock-server.config.js` file with server configuration
39
+
40
+ ```javascript
41
+ /** @type {import('mock-config-server').MockServerConfig} */
42
+ const mockServerConfig = {
43
+ rest: {
44
+ baseUrl: '/api',
45
+ configs: [
46
+ {
47
+ path: '/user',
48
+ method: 'get',
49
+ routes: [{ data: { emoji: '🦁', name: 'Nursultan' } }]
50
+ }
51
+ ]
52
+ }
53
+ };
54
+
55
+ export default mockServerConfig;
56
+ ```
57
+
58
+ Start **🎉 Mock Config Server**
59
+
60
+ ```bash
61
+ $ npx mock-config-server
62
+ ```
63
+
64
+ > If the package is already installed you can use short command `mcs`
65
+
66
+ ## 🎭 Parameters for mock-server.config.(js|ts)
67
+
68
+ - `rest?` Rest configs for mock requests
69
+ - `baseUrl?` {string} part of the url that will be substituted at the beginning of rest request url (default: `'/'`)
70
+ - `configs` {Array<RestRequestConfig>} configs for mock requests, [read](#configs)
71
+ - `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)
72
+ - `graphql?` GraphQL configs for mock requests
73
+ - `baseUrl?` {string} part of the url that will be substituted at the beginning of graphql request url (default: `'/'`)
74
+ - `configs` {Array<GraphQLRequestConfig>} configs for mock requests, [read](#configs)
75
+ - `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)
76
+ - `database?` Database config for mock requests [read](#Database)
77
+ - `data` {Object | string} initial data for database
78
+ - `routes?` {Object | string} map of custom routes for database
79
+ - `staticPath?` {StaticPath} entity for working with static files, [read](#static-path)
80
+ - `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)
81
+ - `cors?` {Cors} CORS settings object (default: `CORS is turn off`), [read](#cors)
82
+ - `port?` {number} server port (default: `31299`)
83
+ - `baseUrl?` {string} part of the url that will be substituted at the beginning of the request url (default: `'/'`)
84
+
85
+ ### Configs
86
+
87
+ 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
88
+
89
+ ##### Rest request config
90
+
91
+ - `path` {string | RegExp} request path
92
+ - `method` {GET | POST | DELETE | PUT | PATCH} rest api method
93
+ - `routes` {RestRouteConfig[]} request routes
94
+ - `data` {any} mock data of request
95
+ - `entities?` Object<headers | cookies | query | params | body> object that helps in data retrieval
96
+ - `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)
97
+ - `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)
98
+
99
+ ##### GraphQL request config
100
+
101
+ - `operationType` {query | mutation} graphql operation type
102
+ - `operationName` {string} graphql operation name
103
+ - `routes` {GraphQLRouteConfig[]} request routes
104
+ - `data` {any} mock data of request
105
+ - `entities?` Object<headers | cookies | query | variables> object that helps in data retrieval
106
+ - `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)
107
+ - `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)
108
+
109
+ ##### Rest example
110
+
111
+ ```javascript
112
+ /** @type {import('mock-config-server').MockServerConfig} */
113
+ const mockServerConfig = {
114
+ rest: {
115
+ baseUrl: '/api',
116
+ configs: [
117
+ {
118
+ path: '/user',
119
+ method: 'get',
120
+ routes: [
121
+ {
122
+ entities: {
123
+ headers: { 'name-header': 'Nursultan' }
124
+ },
125
+ data: { emoji: '🦁', name: 'Nursultan' }
126
+ },
127
+ {
128
+ entities: {
129
+ headers: { 'name-header': 'Dmitriy' }
130
+ },
131
+ data: { emoji: '☄', name: 'Dmitriy' }
132
+ }
133
+ ]
134
+ }
135
+ ]
136
+ }
137
+ };
138
+
139
+ module.exports = mockServerConfig;
140
+ ```
141
+
142
+ Now you can make a request with an additional header and get the desired result
143
+
144
+ ```javascript
145
+ fetch('http://localhost:31299/api/user', {
146
+ headers: {
147
+ 'name-header': 'Nursultan',
148
+ 'Content-Type': 'application/json'
149
+ }
150
+ })
151
+ .then((response) => response.json())
152
+ .then((data) => console.log(data)); // { emoji: '🦁', name: 'Nursultan' }
153
+ ```
154
+
155
+ ##### GraphQL example
156
+
157
+ ```javascript
158
+ /** @type {import('mock-config-server').MockServerConfig} */
159
+ const mockServerConfig = {
160
+ graphql: {
161
+ baseUrl: '/graphql',
162
+ configs: [
163
+ {
164
+ operationType: 'query',
165
+ operationName: 'GetUser',
166
+ routes: [
167
+ {
168
+ entities: {
169
+ headers: { 'name-header': 'Nursultan' }
170
+ },
171
+ data: { emoji: '🦁', name: 'Nursultan' }
172
+ },
173
+ {
174
+ entities: {
175
+ headers: { 'name-header': 'Dmitriy' }
176
+ },
177
+ data: { emoji: '☄', name: 'Dmitriy' }
178
+ }
179
+ ]
180
+ }
181
+ ]
182
+ }
183
+ };
184
+
185
+ module.exports = mockServerConfig;
186
+ ```
187
+
188
+ Now you can make a request with an additional header and get the desired result
189
+
190
+ ```javascript
191
+ const body = JSON.stringify({
192
+ query: 'query GetUser { name }'
193
+ });
194
+
195
+ fetch('http://localhost:31299/graphql', {
196
+ method: 'POST',
197
+ headers: {
198
+ 'name-header': 'Nursultan',
199
+ 'Content-Type': 'application/json'
200
+ },
201
+ body
202
+ })
203
+ .then((response) => response.json())
204
+ .then((data) => console.log(data)); // { emoji: '🦁', name: 'Nursultan' }
205
+ ```
206
+
207
+ #### Entity descriptors
208
+
209
+ If you need more complex logic for matching entities, you can use entity descriptors.
210
+ Descriptor is an object with `checkMode` and `value` fields that describe how the correctness of the actual entity is calculated.
211
+
212
+ Allowed `checkModes`
213
+ - equals - checks actual value for equality with descriptor value (default).
214
+ - notEquals - checks actual value for non-equality with descriptor value.
215
+ - exists - checks actual value for existence i.e. any value.
216
+ - notExists - checks actual value for non-existence i.e. undefined value.
217
+ - includes - checks actual value for including with descriptor value.
218
+ - notIncludes - checks actual value for non-including with descriptor value.
219
+ - startsWith - checks actual value for starting with descriptor value.
220
+ - notStartsWith - checks actual value for non-starting with descriptor value.
221
+ - endsWith - checks actual value for ending with descriptor value.
222
+ - notEndsWith - checks actual value for non-ending with descriptor value.
223
+ - regExp - checks actual value with descriptor regExp.
224
+ - function - checks actual value with descriptor function.
225
+
226
+ 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".
227
+
228
+ ```javascript
229
+ /** @type {import('mock-config-server').MockServerConfig} */
230
+ const mockServerConfig = {
231
+ rest: {
232
+ baseUrl: '/api',
233
+ configs: [
234
+ {
235
+ path: '/user',
236
+ method: 'get',
237
+ routes: [
238
+ {
239
+ entities: {
240
+ headers: {
241
+ // 'name-header' is 'Dmitriy' or 'Nursultan'
242
+ 'name-header': {
243
+ checkMode: 'equals',
244
+ value: ['Dmitriy', 'Nursultan']
245
+ },
246
+ // check for 'equals' if descriptor not provided
247
+ role: 'developer'
248
+ },
249
+ cookies: {
250
+ // any 'token' cookie
251
+ token: {
252
+ checkMode: 'exists'
253
+ },
254
+ // 'someSecretToken' cookie can be '123-abc' or 'abc-999' for example
255
+ someSecretToken: {
256
+ checkMode: 'regExp',
257
+ value: [/^\d\d\d-abc$/, /^abc-\d\d\d$/]
258
+ }
259
+ }
260
+ },
261
+ data: 'Some user data for Dmitriy and Nursultan'
262
+ }
263
+ ]
264
+ }
265
+ ]
266
+ }
267
+ }
268
+
269
+ module.exports = mockServerConfig;
270
+ ```
271
+
272
+ `function checkMode` is the most powerful way to describe your `entities` logic, but in most cases you will be fine using other `checkModes`.
273
+
274
+ `Function value` has the following signature `(actualValue, checkFunction) => boolean`.
275
+ Return `true` if `actualValue` matches your logic or `false` otherwise.
276
+
277
+ You can use the `checkFunction` from second argument if you want to describe your logic in a more declarative way.
278
+ `checkFunction` has the following signature `(checkMode, actualValue, descriptorValue?) => boolean`.
279
+
280
+ ##### Using descriptors for part of REST body or GraphQL variables
281
+
282
+ 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.
283
+ You can use descriptors for array body elements as well.
284
+
285
+ ```javascript
286
+ /** @type {import('mock-config-server').MockServerConfig} */
287
+ const mockServerConfig = {
288
+ rest: {
289
+ baseUrl: '/api',
290
+ configs: [
291
+ {
292
+ path: '/users',
293
+ method: 'post',
294
+ routes: [
295
+ {
296
+ entities: {
297
+ body: {
298
+ 'user.name': 'Sergey'
299
+ }
300
+ },
301
+ data: 'user.name in body is "Sergey"'
302
+ }
303
+ ]
304
+ },
305
+ {
306
+ path: '/posts',
307
+ method: 'post',
308
+ routes: [
309
+ {
310
+ entities: {
311
+ body: {
312
+ 'title': {
313
+ checkMode: 'startsWith',
314
+ value: 'A'
315
+ }
316
+ }
317
+ },
318
+ data: 'title in body starts with "A"'
319
+ }
320
+ ]
321
+ },
322
+ {
323
+ path: '/posts',
324
+ method: 'post',
325
+ routes: [
326
+ {
327
+ entities: {
328
+ body: [
329
+ {
330
+ checkMode: 'startsWith',
331
+ value: 1
332
+ },
333
+ 2
334
+ ]
335
+ },
336
+ data: 'array[0] starts with "1" and array[1] equals "2"'
337
+ }
338
+ ]
339
+ }
340
+ ]
341
+ }
342
+ }
343
+
344
+ module.exports = mockServerConfig;
345
+ ```
346
+
347
+ > To enable whole body/variables checking as plain object you should use descriptor for entire body/variables.
348
+
349
+ ```javascript
350
+ /** @type {import('mock-config-server').MockServerConfig} */
351
+ const mockServerConfig = {
352
+ rest: {
353
+ baseUrl: '/api',
354
+ configs: [
355
+ {
356
+ path: '/users',
357
+ method: 'post',
358
+ routes: [
359
+ {
360
+ entities: {
361
+ body: {
362
+ checkMode: 'equals',
363
+ value: {
364
+ user: {
365
+ name: 'Sergey',
366
+ emoji: '🐘',
367
+ roles: ['developer', 'moderator']
368
+ }
369
+ }
370
+ }
371
+ },
372
+ data: 'your body is strictly equals object from body entity value'
373
+ }
374
+ ]
375
+ }
376
+ ]
377
+ }
378
+ }
379
+
380
+ module.exports = mockServerConfig;
381
+ ```
382
+
383
+ #### Static Path
384
+
385
+ Entity for connecting statics to the server, like HTML, JSON, PNG, etc.
386
+
387
+ - `string` path to your static files
388
+ - `Object<{prefix, path}`
389
+ - `prefix` {string} path prefix for request
390
+ - `path` {string} path to your static files
391
+ - `Array<string | Object<{prefix, path}>>`
392
+
393
+ #### Cors
394
+
395
+ 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.
396
+
397
+ - `origin` {string | RegExp | Array<string | RegExp> | Function | Promise } available origins from which requests can be made
398
+ - `methods?` {Array<GET | POST | DELETE | PUT | PATCH>} available methods (default: `GET,OPTIONS,PUT,PATCH,POST,DELETE`)
399
+ - `allowedHeaders?` {Array<string>} allowed headers (default: `*`)
400
+ - `exposedHeaders?` {Array<string>} exposed headers (default: `*`)
401
+ - `credentials?` {boolean} param tells browsers whether to expose the response to the frontend JavaScript code (default: `true`)
402
+ - `maxAge?` {number} how long the results can be cached (default: `3600`)
403
+
404
+ #### Interceptors
405
+
406
+ Functions to change request or response parameters
407
+
408
+ - `request?` (params) => void
409
+ - `response?` (data, params) => any
410
+
411
+ ##### Request
412
+
413
+ - `params`
414
+ - `request` request object
415
+ - `setDelay` (delay) => Promise<void>
416
+ - `delay` {number} milliseconds of delay time
417
+ - `getHeader` (field) => string | number | string[] | undefined
418
+ - `field` {string} name of response header
419
+ - `getHeaders` () => Record<string | number | string[] | undefined>
420
+ - `getCookie` (name) => string | undefined
421
+ - `name` {string} name of cookie
422
+
423
+ ##### Response
424
+
425
+ - `data` {any} mock data of request
426
+ - `params`
427
+ - `request` request object
428
+ - `response` response object
429
+ - `setDelay` (delay) => Promise<void>
430
+ - `delay` {number} milliseconds of delay time
431
+ - `setStatusCode` (statusCode) => void
432
+ - `statusCode` {number} status code for response
433
+ - `setHeader` (field, value) => void
434
+ - `field` {string} name of response header
435
+ - `value` {string | string[] | undefined} value of response header
436
+ - `appendHeader` (field, value) => void
437
+ - `field` {string} name of response header
438
+ - `value` {string | string[] | undefined} value of response header
439
+ - `getHeader` (field) => string | number | string[] | undefined
440
+ - `field` {string} name of response header
441
+ - `getHeaders` () => Record<string | number | string[] | undefined>
442
+ - `setCookie` (name, value, options) => void
443
+ - `name` {string} name of cookie
444
+ - `value` {string} value of cookie
445
+ - `options` {[CookieOptions](https://expressjs.com/en/resources/middleware/cookie-session.html) | undefined} cookie options (like path, expires, etc.)
446
+ - `getCookie` (name) => string | undefined
447
+ - `name` {string} name of cookie
448
+ - `clearCookie` (name, options) => void
449
+ - `name` {string} name of cookie
450
+ - `options` {[CookieOptions](https://expressjs.com/en/resources/middleware/cookie-session.html) | undefined} cookie options (like path, expires, etc.)
451
+ - `attachment` (filename) => void
452
+ - `filename` {string} name of file in 'Content-Disposition' header
453
+
454
+ ## Database
455
+
456
+ With `mock-config-server` you can create your own mock database with all CRUD operations
457
+ - `data` {Object | string} initial data for database
458
+ - `routes?` {Object | string} map of custom routes for database
459
+
460
+ ### Basic example
461
+
462
+ ```javascript
463
+ const mockServerConfig = {
464
+ database: {
465
+ data: {
466
+ users: [
467
+ { id: 1, name: 'John' }
468
+ ],
469
+ settings: {
470
+ blocked: false
471
+ }
472
+ }
473
+ }
474
+ };
475
+ ```
476
+
477
+ Now you have the following routes for requests
478
+
479
+ #### Collection routes
480
+ ```
481
+ GET /users
482
+ POST /users
483
+ GET /users/1
484
+ PUT /users/1
485
+ PATCH /users/1
486
+ DELETE /users/1
487
+ ```
488
+
489
+ #### Single routes
490
+
491
+ ```
492
+ GET /settings
493
+ POST /settings
494
+ PUT /settings
495
+ PATCH /settings
496
+ ```
497
+
498
+ > Collection routes created from arrays which all elements have **unique**(!) id. Other database parts become single routes.
499
+
500
+ Also, there are additional routes: `/__db` and `/__routes`
501
+
502
+ ```
503
+ __db -> return data from database config
504
+ __routes -> return routes from database config
505
+ ```
506
+
507
+ ### Routes example
508
+
509
+ ```javascript
510
+ const mockServerConfig = {
511
+ database: {
512
+ data: {
513
+ users: [
514
+ { id: 1, name: 'John' }
515
+ ],
516
+ settings: {
517
+ blocked: false
518
+ }
519
+ },
520
+ routes: {
521
+ '/api/users/:id': '/users/:id',
522
+ '/*/my-settings': '/settings'
523
+ }
524
+ }
525
+ };
526
+ ```
527
+
528
+ Now following routes will work correctly
529
+
530
+ ```
531
+ /api/users/1 -> return data for /users/1
532
+ /some/custom/url/my-settings -> return data for /settings
533
+ ```
534
+
535
+ Note some things:
536
+ - String routes should start with forward slash
537
+ - If you want to use id param in route then use only `:id` template
538
+ - You can use `wildcard` only for custom route, **not for real route**
539
+
540
+ ### File example
541
+
542
+ ```javascript
543
+ const mockServerConfig = {
544
+ database: {
545
+ data: './data.json',
546
+ routes: './routes.json'
547
+ }
548
+ };
549
+ ```
550
+
551
+ Instead of objects you can use paths to **JSON** files which contain needed data or routes
552
+
553
+ ## CLI usage
554
+
555
+ ```
556
+ mcs [options]
557
+
558
+ Options:
559
+ --baseUrl, -b Set base url (default: '/')
560
+ --port, -p Set port (default: 31299)
561
+ --staticPath, -s Set static path
562
+ --config, -c Set path to config file (default: './mock-server.config.(?:ts|mts|cts|js|mjs|cjs)')
563
+ --watch, -w Enables server restart after config file changes (default: false)
564
+
565
+ --version, -v Show version number
566
+ --help, -h Show help
567
+
568
+ Examples:
569
+ mcs --baseurl /base/url --port 3000 --config ./path/to/config.ts -w
570
+ mcs --help
571
+ ```
572
+
573
+ ## ✨ Contributors
574
+
575
+ <table>
576
+ <tr>
577
+ <td align="center" style="word-wrap: break-word; width: 100.0; height: 100.0">
578
+ <a href="https://github.com/debabin">
579
+ <img src="https://avatars.githubusercontent.com/u/45297354?v=4"
580
+ width="100;"
581
+ alt="debabin" />
582
+ <br />
583
+ <sub style="font-size:13px"><b>☄️ debabin</b></sub>
584
+ </a>
585
+ </td>
586
+ <td align="center" style="word-wrap: break-word; width: 100.0; height: 100.0">
587
+ <a href="https://github.com/MiaInturi">
588
+ <img src="https://avatars.githubusercontent.com/u/39031929?v=4"
589
+ width="100;"
590
+ alt="MiaInturi" />
591
+ <br />
592
+ <sub style="font-size:13px"><b>👹 MiaInturi</b></sub>
593
+ </a>
594
+ </td>
595
+ <td align="center" style="word-wrap: break-word; width: 100.0; height: 100.0">
596
+ <a href="https://github.com/RiceWithMeat">
597
+ <img src="https://avatars.githubusercontent.com/u/47690223?v=4"
598
+ width="100;"
599
+ alt="RiceWithMeat" />
600
+ <br />
601
+ <sub style="font-size:13px"><b>🐘 RiceWithMeat</b></sub>
602
+ </a>
603
+ </td>
604
+ <td align="center" style="word-wrap: break-word; width: 100.0; height: 100.0">
605
+ <a href="https://github.com/anv296">
606
+ <img src="https://avatars.githubusercontent.com/u/39154399?s=400&u=7c4fcc6d120f4b13ccbd03a9a384622b6523c376&v=4"
607
+ width="100;"
608
+ alt="anv296" />
609
+ <br />
610
+ <sub style="font-size:13px"><b>🎱️ anv296</b></sub>
611
+ </a>
612
+ </td>
613
+ </tr>
614
+ </table>