{"id":13602187,"url":"https://github.com/siberiacancode/mock-config-server","last_synced_at":"2025-07-14T05:31:31.547Z","repository":{"id":65310483,"uuid":"589149589","full_name":"siberiacancode/mock-config-server","owner":"siberiacancode","description":"🎉 tool that easily and quickly imitates server operation, create full fake api in few steps","archived":false,"fork":false,"pushed_at":"2024-01-31T10:46:52.000Z","size":1306,"stargazers_count":51,"open_issues_count":27,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2024-02-01T13:56:25.452Z","etag":null,"topics":["api","config","data","database","fake","graphql","mock","mock-server","mocking","rest","rest-api","server"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/mock-config-server","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/siberiacancode.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2023-01-15T08:21:29.000Z","updated_at":"2024-02-05T06:35:48.522Z","dependencies_parsed_at":"2023-09-24T09:16:24.953Z","dependency_job_id":"df5621e9-bb95-45ed-9f96-7bfc5ccb575b","html_url":"https://github.com/siberiacancode/mock-config-server","commit_stats":null,"previous_names":[],"tags_count":22,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/siberiacancode%2Fmock-config-server","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/siberiacancode%2Fmock-config-server/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/siberiacancode%2Fmock-config-server/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/siberiacancode%2Fmock-config-server/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/siberiacancode","download_url":"https://codeload.github.com/siberiacancode/mock-config-server/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":225952182,"owners_count":17550509,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","config","data","database","fake","graphql","mock","mock-server","mocking","rest","rest-api","server"],"created_at":"2024-08-01T18:01:15.949Z","updated_at":"2025-07-14T05:31:31.532Z","avatar_url":"https://github.com/siberiacancode.png","language":"TypeScript","funding_links":[],"categories":["api"],"sub_categories":[],"readme":"# 🎉 Mock Config Server\n\ntool that easily and quickly imitates server operation, create full fake api in few steps\n\n## Install\n\nInstall with [npm](https://www.npmjs.com/) or [yarn](https://yarnpkg.com/)\n\n```bash\n$ npm i mock-config-server --save --dev\n# or\n$ yarn add mock-config-server --dev\n```\n\n## 🦉 Philosophy\n\n**🎉 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.\n\n## Features\n\n- **TypeScript support out of the box** - full typed package\n- **Full Rest Api support** - using simple configs of a certain format, you can easily simulate rest operation of servers\n- **GraphQL support** - using simple configs of a certain format, you can easily simulate graphlql operation of servers\n- **Database** - use mock database with all CRUD operations\n- **CORS setup** - turn on and off CORS, fully customizable when CORS is turned on\n- **Support for any kind of static** - server can return any type of static file if needed. Images, HTML, CSS, JSON, etc\n\n## Usage\n\nInstall **🎉 Mock Config Server** with [npm](https://www.npmjs.com/) or [yarn](https://yarnpkg.com/)\n\n```bash\n$ npm i mock-config-server --save --dev\n# or\n$ yarn add mock-config-server --dev\n```\n\nCreate a `mock-server.config.js` file with server configuration\n\n```javascript\n/** @type {import('mock-config-server').FlatMockServerConfig} */\nconst flatMockServerConfig = [\n  {\n    baseUrl: '/api'\n  },\n  {\n    configs: [\n      {\n        path: '/user',\n        method: 'get',\n        routes: [{ data: { emoji: '🦁', name: 'Nursultan' } }]\n      }\n    ]\n  }\n];\n\nexport default flatMockServerConfig;\n```\n\nStart **🎉 Mock Config Server**\n\n```bash\n$ npx mock-config-server\n```\n\n\u003e If the package is already installed you can use short command `mcs`\n\n## 🎭 Parameters for mock-server.config.(js|ts)\n\n### Settings\n\n- `staticPath?` {StaticPath} entity for working with static files, [read](#static-path)\n- `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)\n- `cors?` {Cors} CORS settings object (default: `CORS is turn off`), [read](#cors)\n- `port?` {number} server port (default: `31299`)\n- `baseUrl?` {string} part of the url that will be substituted at the beginning of the request url (default: `'/'`)\n- `database?` Database config for mock requests [read](#database)\n  - `data` {Object | string} initial data for database\n  - `routes?` {Object | string} map of custom routes for database\n\n### Components\n\n- `name` {string} name of component\n- `baseUrl?` {string} part of the url that will be substituted at the beginning of rest request url (default: `'/'`)\n- `configs` {Array\u003cRestRequestConfig | GraphQLRequestConfig\u003e} configs for mock requests, [read](#configs)\n  - `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors)\n\n### Configs\n\nConfigs 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\n\n#### Rest request config\n\nEvery route must be configured to handle response content in one of three ways: data or [queue](#polling) or [file](#file-responses).\n\n- `path` `string | RegExp` request path\n- `method` `'get' | 'post' | 'delete' | 'put' | 'patch' | 'options'` rest api method\n- `routes` `RestRouteConfig[]` request routes\n  - `data?` `any` mock data of request\n  - `queue?` `Array\u003c{ time?: number; data: any}\u003e` queue for polling with opportunity to set time for each response\n  - `file?` `string` path to file for return in response\n  - `settings?` `Settings` settings for route (polling on/off, etc.)\n  - `entities?` `Object\u003cheaders | cookies | query | params | body\u003e` object that helps in data retrieval\n  - `interceptors?` `Interceptors` functions to change request or response parameters, [read](#interceptors)\n- `interceptors?` `Interceptors` functions to change request or response parameters, [read](#interceptors)\n\n##### Rest example\n\n```javascript\n/** @type {import('mock-config-server').FlatMockServerConfig} */\nconst flatMockServerConfig = [\n  {\n    baseUrl: '/api'\n  },\n  {\n    configs: [\n      {\n        path: '/user',\n        method: 'get',\n        routes: [\n          {\n            entities: {\n              headers: { 'name-header': 'Nursultan' }\n            },\n            data: { emoji: '🦁', name: 'Nursultan' }\n          },\n          {\n            entities: {\n              headers: { 'name-header': 'Dmitriy' }\n            },\n            data: { emoji: '☄', name: 'Dmitriy' }\n          }\n        ]\n      }\n    ]\n  }\n];\n\nexport default flatMockServerConfig;\n```\n\nNow you can make a request with an additional header and get the desired result\n\n```javascript\nfetch('http://localhost:31299/api/user', {\n  headers: {\n    'name-header': 'Nursultan',\n    'Content-Type': 'application/json'\n  }\n})\n  .then((response) =\u003e response.json())\n  .then((data) =\u003e console.log(data)); // {  emoji: '🦁', name: 'Nursultan' }\n```\n\n#### GraphQL request config\n\nEvery route must be configured to handle response content in one of two ways: data or [queue](#polling).\n\n- `operationType` `query | mutation` graphql operation type\n- `operationName?` `string | RegExp` graphql operation name\n- `query?`: `string` graphql query as string\n- `routes` `GraphQLRouteConfig[]` request routes\n  - `data?` `any` mock data of request\n  - `queue?` `Array\u003c{ time?: number; data: any}\u003e` queue for polling with opportunity to set time for each response\n  - `settings?` `Settings` settings for route (polling on/off, etc.)\n  - `entities?` `Object\u003cheaders | cookies | query | variables\u003e` object that helps in data retrieval\n  - `interceptors?` `Interceptors` functions to change request or response parameters, [read](#interceptors)\n- `interceptors?` `Interceptors` functions to change request or response parameters, [read](#interceptors)\n\n\u003e Every graphql config should contain `operationName` or `query` or both of them\n\n##### GraphQL example\n\n```javascript\n/** @type {import('mock-config-server').FlatMockServerConfig} */\nconst flatMockServerConfig = [\n  {\n    baseUrl: '/graphql'\n  },\n  {\n    configs: [\n      {\n        operationType: 'query',\n        operationName: 'GetUser',\n        routes: [\n          {\n            entities: {\n              headers: { 'name-header': 'Nursultan' }\n            },\n            data: { emoji: '🦁', name: 'Nursultan' }\n          },\n          {\n            entities: {\n              headers: { 'name-header': 'Dmitriy' }\n            },\n            data: { emoji: '☄', name: 'Dmitriy' }\n          }\n        ]\n      }\n    ]\n  }\n];\n\nexport default flatMockServerConfig;\n```\n\nNow you can make a request with an additional header and get the desired result\n\n```javascript\nconst body = JSON.stringify({\n  query: 'query GetUser { name }'\n});\n\nfetch('http://localhost:31299/graphql', {\n  method: 'POST',\n  headers: {\n    'name-header': 'Nursultan',\n    'Content-Type': 'application/json'\n  },\n  body\n})\n  .then((response) =\u003e response.json())\n  .then((data) =\u003e console.log(data)); // {  emoji: '🦁', name: 'Nursultan' }\n```\n\n#### Entity descriptors\n\nIf you need more complex logic for matching entities, you can use entity descriptors.\nDescriptor is an object with `checkMode` and `value` fields that describe how the correctness of the actual entity is calculated.\n\nAllowed `checkModes`\n\n- equals - checks actual value for equality with descriptor value (default).\n- notEquals - checks actual value for non-equality with descriptor value.\n- exists - checks actual value for existence i.e. any value.\n- notExists - checks actual value for non-existence i.e. undefined value.\n- includes - checks actual value for including with descriptor value.\n- notIncludes - checks actual value for non-including with descriptor value.\n- startsWith - checks actual value for starting with descriptor value.\n- notStartsWith - checks actual value for non-starting with descriptor value.\n- endsWith - checks actual value for ending with descriptor value.\n- notEndsWith - checks actual value for non-ending with descriptor value.\n- regExp - checks actual value with descriptor regExp.\n- function - checks actual value with descriptor function.\n\n```javascript\n/** @type {import('mock-config-server').FlatMockServerConfig} */\nconst flatMockServerConfig = [\n  {\n    baseUrl: '/api'\n  },\n  {\n    configs: [\n      {\n        path: '/user',\n        method: 'get',\n        routes: [\n          {\n            entities: {\n              headers: {\n                // 'name-header' is 'Dmitriy'\n                'name-header': {\n                  checkMode: 'equals',\n                  value: 'Dmitriy'\n                },\n                // check for 'equals' if descriptor not provided\n                // i.e. it is the same as `role: { checkMode: 'equals', value: 'developer' }`\n                role: 'developer'\n              },\n              cookies: {\n                // any 'token' cookie\n                token: {\n                  checkMode: 'exists'\n                },\n                // 'someSecretToken' cookie can be '123-abc' or '456-abc' for example\n                someSecretToken: {\n                  checkMode: 'regExp',\n                  value: /^\\d\\d\\d-abc$/\n                }\n              }\n            },\n            data: 'Some user data for Dmitriy'\n          }\n        ]\n      }\n    ]\n  }\n];\n\nexport default flatMockServerConfig;\n```\n\n#### Descriptor _oneOf_ property\n\nFor `checkMode` with the `value` property (all `checkMode` options except `exists` and `notExists`) you can use an array as value.\nMock server will find matches by iterating through the array until **some** match is found.\nTo be able to use this functionality you need to explicitly set `oneOf: true` property in descriptor object.\n\n```javascript\n/** @type {import('mock-config-server').FlatMockServerConfig} */\nconst flatMockServerConfig = [\n  {\n    baseUrl: '/api'\n  },\n  {\n    configs: [\n      {\n        path: '/user',\n        method: 'post',\n        routes: [\n          {\n            entities: {\n              // if body equals to { key1: 'value1' } OR { key2: 'value2' } then mock-config-server return 'Some user data 1'\n              body: {\n                checkMode: 'equals',\n                value: [{ key1: 'value1' }, { key2: 'value2' }],\n                oneOf: true\n              }\n            },\n            data: 'Some user data 1'\n          },\n          {\n            entities: {\n              // if body equals to [{ key1: 'value1' }, { key2: 'value2' }] then mock-config-server return 'Some user data 2'\n              // NO `oneOf` =\u003e array processed entirely\n              body: {\n                checkMode: 'equals',\n                value: [{ key1: 'value1' }, { key2: 'value2' }]\n              }\n            },\n            data: 'Some user data 2'\n          }\n        ]\n      }\n    ]\n  }\n];\n\nexport default flatMockServerConfig;\n```\n\n#### Function check mode\n\n`function checkMode` is the most powerful way to describe your `entities` logic, but in most cases you will be fine using other `checkModes`.\n\n`Function value` has the following signature `(actualValue, checkFunction) =\u003e boolean`.\nReturn `true` if `actualValue` matches your logic or `false` otherwise.\n\nYou can use the `checkFunction` from second argument if you want to describe your logic in a more declarative way.\n`checkFunction` has the following signature `(checkMode, actualValue, descriptorValue?) =\u003e boolean`.\n\n```javascript\n/** @type {import('mock-config-server').FlatMockServerConfig} */\nconst flatMockServerConfig = [\n  {\n    baseUrl: '/api'\n  },\n  {\n    configs: [\n      {\n        path: '/posts/:postId',\n        method: 'post',\n        routes: [\n          {\n            entities: {\n              params: {\n                postId: {\n                  checkMode: 'function',\n                  value: (actualValue) =\u003e +actualValue \u003e= 0 \u0026\u0026 +actualValue \u003c= 50\n                },\n              },\n              cookies: {\n                authToken: {\n                  checkMode: 'function',\n                  value: (actualValue, checkFunction) =\u003e\n                    checkFunction('equals', actualValue, 123) ||\n                    checkFunction('startsWith', actualValue, 2)\n                }\n              }\n            },\n            data: 'Some user data'\n          }\n        ]\n      }\n    ]\n  }\n];\n\nmodule.exports = flatMockServerConfig;\n```\n\n##### Using descriptors for part of REST body or GraphQL variables\n\nIf you want to check a deep nested property of your body or variables via descriptor you can use flatten object style. In this case server will check every field in entity with corresponding actual field. I.e. you can use descriptors only for properties of entity object (not for properties of nested objects).\n\n```javascript\n/** @type {import('mock-config-server').FlatMockServerConfig} */\nconst flatMockServerConfig = [\n  {\n    baseUrl: '/api'\n  },\n  {\n    configs: [\n      {\n        path: '/users',\n        method: 'post',\n        routes: [\n          {\n            entities: {\n              body: {\n                // if body has properties like { user: { name: 'Sergey' } } OR { 'user.name': 'Sergey' } then mock-config-server return data\n                'user.name': {\n                  checkMode: 'equals',\n                  value: 'Sergey'\n                }\n              }\n            },\n            data: 'user.name in body is \"Sergey\"'\n          }\n        ]\n      }\n    ]\n  }\n];\n\nexport default flatMockServerConfig;\n```\n\nYou can also use descriptor for whole body or variables entity.\n\n\u003e When you use 'equals'/'notEquals' check mode for whole body or variables mock-config-server is strictly compare entity and actual value. It means that you must specify **ALL** properties from actual body or variables.\n\n```javascript\n/** @type {import('mock-config-server').FlatMockServerConfig} */\nconst flatMockServerConfig = [\n  {\n    baseUrl: '/api'\n  },\n  {\n    configs: [\n      {\n        path: '/users',\n        method: 'post',\n        routes: [\n          {\n            entities: {\n              body: {\n                // if actual body contains some extra property(-ies) then this entity won't match\n                checkMode: 'equals',\n                value: {\n                  user: {\n                    name: 'Sergey',\n                    emoji: '🐘',\n                    roles: ['developer', 'moderator']\n                  }\n                }\n              }\n            },\n            data: 'your body is strictly equals object from body entity value'\n          }\n        ]\n      }\n    ]\n  }\n];\n\nexport default flatMockServerConfig;\n```\n\n#### File responses\n\nRest routes support paths to files. If a route is matched, the server will send data from the file. If the file is not found, the server will return 404.\n\n```javascript\n/** @type {import('mock-config-server').FlatMockServerConfig} */\nconst flatMockServerConfig = [\n  {\n    baseUrl: '/api'\n  },\n  {\n    configs: [\n      {\n        path: '/files/settings',\n        method: 'get',\n        routes: [\n          {\n            file: './settings.json'\n          }\n        ]\n      }\n    ]\n  }\n];\n\nexport default flatMockServerConfig;\n```\n\n\u003e If the file path is absolute, then this path will be used as is. If the file path is relative, it will be appended to the current working directory.\n\nIf the file exists, response interceptors will receive `file descriptor` as the `data` argument:\n\n`File descriptor` is an object with `path` and `file` fields that describe file location and file content.\n\n- `path` `string` path to the file. Same as `file` passed in route\n- `file` `Buffer` file content as binary buffer\n\n\u003e Note to return file descriptor from interceptor. Server will send a buffer from `data.file` with corresponding `Content-Type` and `Content-Disposition` headers.\n\u003e If you return invalid file descriptor, server will send it as json data.\n\n```javascript\n/** @type {import('mock-config-server').FlatMockServerConfig} */\nconst flatMockServerConfig = [\n  {\n    baseUrl: '/api'\n  },\n  {\n    configs: [\n      {\n        path: '/files/settings',\n        method: 'get',\n        routes: [\n          {\n            file: './settings.json',\n            interceptors: {\n              response: (data) =\u003e {\n                const { file, path } = data;\n                const buffer = file; // some logic with buffer\n                fs.writeFileSync(path, buffer); // rewrite ./settings.json file on disk with new content\n                return { path, file: buffer };\n              }\n            }\n          }\n        ]\n      }\n    ]\n  }\n];\n\nexport default flatMockServerConfig;\n```\n\n\u003e Any changes to the data will not affect the file on disk unless you manually rewrite it.\n\n\u003e If you return a new `path` from interceptor, server will send file corresponding to this path or 404 error otherwise.\n\n#### Polling\n\nRoutes support polling for data. To add polling for data, you must specify the `polling setting` and use `queue` property instead of `data` or `file`.\n\n`queue` is an array containing `data` or `file` that should be returned in order.\n\n\u003e After receiving the last value from polling, the queue is reset and the next request will return the first value from the queue.\n\n```javascript\n/** @type {import('mock-config-server').FlatMockServerConfig} */\nconst flatMockServerConfig = [\n  {\n    baseUrl: '/api'\n  },\n  {\n    configs: [\n      {\n        path: '/user',\n        method: 'get',\n        routes: [\n          {\n            settings: { polling: true },\n            queue: [\n              { data: { emoji: '🦁', name: 'Nursultan' } },\n              { data: { emoji: '☄', name: 'Dmitriy' } },\n              { file: './users/Sergey.json' }\n            ]\n          }\n        ]\n      }\n    ]\n  }\n];\n\nexport default flatMockServerConfig;\n```\n\nUsing the additional `time` properties in milliseconds, you can specify how much time certain data should be returned\n\n```javascript\n/** @type {import('mock-config-server').FlatMockServerConfig} */\nconst flatMockServerConfig = [\n  {\n    baseUrl: '/api'\n  },\n  {\n    configs: [\n      {\n        path: '/user',\n        method: 'get',\n        routes: [\n          {\n            settings: { polling: true },\n            queue: [\n              { time: 5000, data: { emoji: '🦁', name: 'Nursultan' } },\n              { data: { emoji: '☄', name: 'Dmitriy' } }\n            ]\n          }\n        ]\n      }\n    ]\n  }\n];\n\nexport default flatMockServerConfig;\n```\n\n#### Static Path\n\nEntity for connecting statics to the server, like HTML, JSON, PNG, etc.\n\n- `string` path to your static files\n- `Object\u003c{prefix, path}`\n  - `prefix` `string` path prefix for request\n  - `path` `string` path to your static files\n- `Array\u003cstring | Object\u003c{prefix, path}\u003e\u003e`\n\n#### Cors\n\nObject 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.\n\n- `origin` `string | RegExp | Array\u003cstring | RegExp\u003e | Function | Promise` available origins from which requests can be made\n- `methods?` `Array\u003cGET | POST | DELETE | PUT | PATCH\u003e` available methods (default: `GET,OPTIONS,PUT,PATCH,POST,DELETE`)\n- `allowedHeaders?` `Array\u003cstring\u003e` allowed headers (default: `*`)\n- `exposedHeaders?` `Array\u003cstring\u003e` exposed headers (default: `*`)\n- `credentials?` `boolean` param tells browsers whether to expose the response to the frontend JavaScript code (default: `true`)\n- `maxAge?` `number` how long the results can be cached (default: `3600`)\n\n#### Interceptors\n\nFunctions to change request or response parameters\n\n- `request?` `(params) =\u003e void`\n- `response?` `(data, params) =\u003e any`\n\n\u003e request interceptors (except interceptor for route) are called regardless of whether the server found a route match or not. So changes in request interceptors can affect whether the server finds the route or not\n\n##### Request\n\n- `params`\n  - `request` request object\n  - `setDelay` `(delay) =\u003e Promise\u003cvoid\u003e`\n    - `delay` `number` milliseconds of delay time\n  - `getHeader` `(field) =\u003e string | number | string[] | undefined`\n    - `field` `string` name of response header\n  - `getHeaders` `() =\u003e Record\u003cstring | number | string[] | undefined\u003e`\n  - `getCookie` `(name) =\u003e string | undefined`\n    - `name` `string` name of cookie\n  - `log` `(logger) =\u003e Partial\u003cLoggerTokens\u003e` logger function [read](#logger)\n    - `logger` `Logger | undefined` logger options\n\n##### Response\n\n- `data` `any` mock data of request\n- `params`\n  - `request` request object\n  - `response` response object\n  - `setDelay` `(delay) =\u003e Promise\u003cvoid\u003e`\n    - `delay` `number` milliseconds of delay time\n  - `setStatusCode` `(statusCode) =\u003e void`\n    - `statusCode` `number` status code for response\n  - `setHeader` `(field, value) =\u003e void`\n    - `field` `string` name of response header\n    - `value` `string | string[] | undefined` value of response header\n  - `appendHeader` `(field, value) =\u003e void`\n    - `field` `string` name of response header\n    - `value` `string | string[] | undefined` value of response header\n  - `getHeader` `(field) =\u003e string | number | string[] | undefined`\n    - `field` `string` name of response header\n  - `getHeaders` `() =\u003e Record\u003cstring | number | string[] | undefined\u003e`\n  - `setCookie` `(name, value, options) =\u003e void`\n    - `name` `string` name of cookie\n    - `value` `string` value of cookie\n    - `options` `[CookieOptions](https://expressjs.com/en/resources/middleware/cookie-session.html) | undefined` cookie options (like path, expires, etc.)\n  - `getCookie` `(name) =\u003e string | undefined`\n    - `name` `string` name of cookie\n  - `clearCookie` `(name, options) =\u003e void`\n    - `name` `string` name of cookie\n    - `options` `[CookieOptions](https://expressjs.com/en/resources/middleware/cookie-session.html) | undefined` cookie options (like path, expires, etc.)\n  - `attachment` `(filename) =\u003e void`\n    - `filename` `string` name of file in 'Content-Disposition' header\n  - `log` `(logger) =\u003e Partial\u003cLoggerTokens\u003e` logger function [read](#logger)\n    - `logger` `Logger | undefined` logger options\n\n#### Logger\n\nYou can log requests and responses using `log` function in any [interceptor](#interceptors).\n\n`log` has the following signature `(logger?: Logger) =\u003e Partial\u003cLoggerTokens\u003e`.\n\n`logger` parameter has the following optional properties\n\n- `options?` `LoggerOptions` object map containing tokens to log. Keys is token names, values is boolean. `true` will add token into log, `false` will remove. If `options` property is not passed, following tokens will be logged\n  - Request\n    - type\n    - id\n    - timestamp\n    - method\n    - url\n  - Response\n    - type\n    - id\n    - timestamp\n    - method\n    - url\n    - statusCode\n    - data\n- `rewrite?` `(tokens: Partial\u003cLoggerTokens\u003e) =\u003e void` function to replace default `console.dir(tokens, { depth: null })` appearance\n\n`log` function returns object with logged token values\n\n```javascript\n/** @type {import('mock-config-server').FlatMockServerConfig} */\nconst flatMockServerConfig = [\n  {\n    baseUrl: '/api'\n  },\n  {\n    configs: [\n      {\n        path: '/posts',\n        method: 'get',\n        routes: [\n          {\n            interceptors: {\n              request: ({ log }) =\u003e {\n                log({\n                  // logs following object in terminal\n                  options: {\n                    // {\n                    id: true, //  id: 1,\n                    type: true, //  type: 'request',\n                    timestamp: true, //  timestamp: '31.12.2024, 23:59:59,999',\n                    method: true, //  method: 'GET',\n                    url: true //  url: 'http://localhost:31299/api/rest/posts/1'\n                  } // }\n                });\n              },\n              response: (data, { log }) =\u003e {\n                log({\n                  // logs following string in terminal\n                  options: {\n                    // response get: http://localhost:31299/api/rest/posts/1 =\u003e 200\n                    type: true,\n                    statusCode: true,\n                    method: true,\n                    url: true\n                  },\n                  rewrite: ({ type, statusCode, method, url }) =\u003e {\n                    console.info(`${type} ${method}: ${url} =\u003e ${statusCode}`);\n                  }\n                });\n                return data;\n              }\n            }\n          }\n        ]\n      }\n    ]\n  }\n];\n\nexport default flatMockServerConfig;\n```\n\n\u003e By default, `timestamp` and `method` tokens are prettified.\n\u003e Timestamp transforms from UNIX-timestamp number to `DD.MM.YYYY, HH:mm:ss,sss` string.\n\u003e Method transforms from lower case to upper case.\n\u003e If `rewrite` function is used, those tokens will remain unformatted. You can format them as you need.\n\n##### Logger tokens\n\n- `type?` `'request' | 'response'` type of log\n- `id?` `number` unique id of request to reference request log with response log\n- `timestamp?` `number` UNIX-timestamp in milliseconds\n- `method?` `'get' | 'post' | 'delete' | 'put' | 'patch' | 'options'` HTTP method\n- `url?` `string` requested URL\n- `graphQLOperationType?` `'query' | 'mutation' | null` GraphQL operation type. `null` if request is not GraphQL\n- `graphQLOperationName?` `string` GraphQL operation name. `null` if request is not GraphQL\n- `graphQLQuery?` `string` GraphQL query. `null` if request is not GraphQL\n- `variables?`: `Record\u003cstring, any\u003e` GraphQL variables. `null` if request is not GraphQL or variables is not passed\n- `headers?` `Record\u003cstring, any\u003e` headers object\n- `cookies?` `Record\u003cstring, any\u003e` cookies object\n- `query?` `Record\u003cstring, any\u003e` query object\n- `params?` `Record\u003cstring, any\u003e` params object\n- `body?` `any` body\n\nResponse logger has additional tokens\n\n- `statusCode?` `number` response status code\n- `data?` `any` data returned to client\n\nIf you need to log specific properties in mapped entities (headers, cookies, query, params), use `Record\u003cstring, boolean\u003e` object instead of boolean.\nIn that case logger will use following logic:\n\n- if some token is `true`, entity will be filtered by `whitelist` logic. _Only_ enabled ones will be logged.\n- if all tokens is `false`, entity will be filtered by `blacklist` logic. All entities will be logged _except_ disabled ones.\n\n\u003e Whitelist logic have priority over blacklist if you pass `true` and `false` in same entity.\n\n```javascript\n/** @type {import('mock-config-server').FlatMockServerConfig} */\nconst flatMockServerConfig = [\n  {\n    baseUrl: '/api'\n  },\n  {\n    configs: [\n      {\n        path: '/posts',\n        method: 'get',\n        routes: [\n          {\n            interceptors: {\n              request: ({ log }) =\u003e {\n                log({\n                  // whitelist. only query1 and query2 will be logged\n                  options: {\n                    query: {\n                      query1: true,\n                      query2: true\n                    }\n                  }\n                });\n                log({\n                  // whitelist. only cookie1 and cookie2 will be logged\n                  options: {\n                    cookies: {\n                      cookie1: true,\n                      cookie2: true,\n                      cookie3: false\n                    }\n                  }\n                });\n                log({\n                  // blacklist. all headers will be logged except header1\n                  options: {\n                    headers: {\n                      header1: false\n                    }\n                  }\n                });\n              }\n            },\n            data: {}\n          }\n        ]\n      }\n    ]\n  }\n];\n\nexport default flatMockServerConfig;\n```\n\n## Database\n\nWith `mock-config-server` you can create your own mock database with all CRUD operations\n\n- `data` `Object | string` initial data for database\n- `routes?` `Object | string` map of custom routes for database\n\n### Basic example\n\n```javascript\nconst flatMockServerConfig = [\n  {\n    database: {\n      data: {\n        users: [{ id: 1, name: 'John' }],\n        settings: {\n          blocked: false\n        }\n      }\n    }\n  }\n];\n```\n\nNow you have the following routes for requests\n\n#### Collection routes\n\n```\nGET    /users\nPOST   /users\nGET    /users/1\nPUT    /users/1\nPATCH  /users/1\nDELETE /users/1\n```\n\n#### Single routes\n\n```\nGET   /settings\nPOST  /settings\nPUT   /settings\nPATCH /settings\n```\n\n\u003e Collection routes created from arrays which all elements have **unique**(!) id. Other database parts become single routes.\n\nAlso, there are additional routes: `/__db` and `/__routes`\n\n```\n__db -\u003e return data from database config\n__routes -\u003e return routes from database config\n```\n\n### Routes example\n\n```javascript\nconst flatMockServerConfig = [\n  {\n    database: {\n      data: {\n        users: [{ id: 1, name: 'John' }],\n        settings: {\n          blocked: false\n        }\n      },\n      routes: {\n        '/api/users/:id': '/users/:id',\n        '/*/my-settings': '/settings'\n      }\n    }\n  }\n];\n```\n\nNow following routes will work correctly\n\n```\n/api/users/1 -\u003e return data for /users/1\n/some/custom/url/my-settings -\u003e return data for /settings\n```\n\nNote some things:\n\n- String routes should start with forward slash\n- If you want to use id param in route then use only `:id` template\n- You can use `wildcard` only for custom route, **not for real route**\n\n### Filter\n\n\u003e Use . to access deep properties\n\n```\nGET /users?name=siberiacancode\nGET /users?id=1\u0026id=2\nGET /users?author.name=siberiacancode\n```\n\n### Pagination\n\n\u003e Use \\_page and optionally \\_limit to paginate returned data.\n\n```\nGET /users?_page=1\nGET /users?_page=1\u0026_limit=5\n```\n\n\u003e **\\_limit** is 10 by default\n\nThe returned data has the format:\n\n```\n{\n  _link: Link,\n  results: Data[]\n}\n```\n\nIn the **Link** header you'll get **count**, **pages**, **next** and **prev** links.\n\n#### Link\n\n- `count` `number` total count of elements\n- `pages` `number` count of pages\n- `next` `string | null` query string for next link\n- `prev` `string | null` query string for prev link\n\n### Sort\n\n\u003e Use \\_sort and \\_order, use . to access deep properties\n\n```\nGET /users?_sort=name\nGET /users/1/transfers?_sort=id\u0026_order=asc\nGET /users?_sort=address.city\u0026_order=desc\n```\n\n\u003e **\\_order** is 'asc' by default\n\nFor multiple fields:\n\n```\nGET /users?_sort=id\u0026_order=desc\u0026_sort=name\u0026_order=asc\n```\n\n### Slice\n\n\u003e X-Total-Count header is included in the response\n\n```\nGET /users?_begin=20\nGET /users?_begin=20\u0026_end=30\n```\n\nWorks exactly as [slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice), \\_begin and \\_end are optional\n\n### Full text search\n\n\u003e Add \\_q parameter for search data, search can be done by strings and numbers\n\n```\nGET /users?_q=siberia\n```\n\nFor multiple search\n\n```\nGET /users?_q=siberia\u0026_q=24\n```\n\n### File example\n\n```javascript\nconst flatMockServerConfig = [\n  {\n    database: {\n      data: './data.json',\n      routes: './routes.json'\n    }\n  }\n];\n```\n\nInstead of objects you can use paths to **JSON** files which contain needed data or routes\n\n## CLI usage\n\n```\nmcs [options]\n\nOptions:\n  --baseUrl, -b         Set base url (default: '/')\n  --port, -p            Set port (default: 31299)\n  --staticPath, -s      Set static path\n  --config, -c          Set path to config file (default: './mock-server.config.(?:ts|mts|cts|js|mjs|cjs)')\n  --watch, -w           Enables server restart after config file changes (default: false)\n\n  --version, -v         Show version number\n  --help, -h            Show help\n\nExamples:\n  mcs --baseurl /base/url --port 3000 --config ./path/to/config.ts -w\n  mcs --help\n```\n\n## Init Command\n\nThe init command is used to initialize a new project or set up the initial configuration for a tool. It helps users get started with a new project by providing a streamlined setup process.\n\n```\nmcs init\n\nExamples:\n  mcs init\n  mcs init --baseurl /base/url --port 3000\n```\n\n## ✨ Contributors\n\n\u003ctable\u003e\n\u003ctr\u003e\n    \u003ctd align=\"center\" style=\"word-wrap: break-word; width: 100.0; height: 100.0\"\u003e\n        \u003ca href=\"https://github.com/debabin\"\u003e\n            \u003cimg src=\"https://avatars.githubusercontent.com/u/45297354?v=4\"\n            width=\"100;\"  \n            alt=\"debabin\" /\u003e\n            \u003cbr /\u003e\n            \u003csub style=\"font-size:13px\"\u003e\u003cb\u003e☄️ debabin\u003c/b\u003e\u003c/sub\u003e\n        \u003c/a\u003e\n    \u003c/td\u003e\n    \u003ctd align=\"center\" style=\"word-wrap: break-word; width: 100.0; height: 100.0\"\u003e\n        \u003ca href=\"https://github.com/MiaInturi\"\u003e\n            \u003cimg src=\"https://avatars.githubusercontent.com/u/39031929?v=4\"\n            width=\"100;\"  \n            alt=\"MiaInturi\" /\u003e\n            \u003cbr /\u003e\n            \u003csub style=\"font-size:13px\"\u003e\u003cb\u003e👹 MiaInturi\u003c/b\u003e\u003c/sub\u003e\n        \u003c/a\u003e\n    \u003c/td\u003e\n      \u003ctd align=\"center\" style=\"word-wrap: break-word; width: 100.0; height: 100.0\"\u003e\n        \u003ca href=\"https://github.com/RiceWithMeat\"\u003e\n            \u003cimg src=\"https://avatars.githubusercontent.com/u/47690223?v=4\"\n            width=\"100;\"  \n            alt=\"RiceWithMeat\" /\u003e\n            \u003cbr /\u003e\n            \u003csub style=\"font-size:13px\"\u003e\u003cb\u003e🐘 RiceWithMeat\u003c/b\u003e\u003c/sub\u003e\n        \u003c/a\u003e\n    \u003c/td\u003e\n    \u003ctd align=\"center\" style=\"word-wrap: break-word; width: 100.0; height: 100.0\"\u003e\n        \u003ca href=\"https://github.com/anv296\"\u003e\n            \u003cimg src=\"https://avatars.githubusercontent.com/u/39154399?s=400\u0026u=7c4fcc6d120f4b13ccbd03a9a384622b6523c376\u0026v=4\"\n            width=\"100;\"  \n            alt=\"anv296\" /\u003e\n            \u003cbr /\u003e\n            \u003csub style=\"font-size:13px\"\u003e\u003cb\u003e🎱️ anv296\u003c/b\u003e\u003c/sub\u003e\n        \u003c/a\u003e\n    \u003c/td\u003e\n        \u003ctd align=\"center\" style=\"word-wrap: break-word; width: 100.0; height: 100.0\"\u003e\n        \u003ca href=\"https://github.com/kvelian\"\u003e\n            \u003cimg src=\"https://avatars.githubusercontent.com/u/81089091?s=400\u0026u=7c4fcc6d120f4b13ccbd03a9a384622b6523c376\u0026v=4\"\n            width=\"100;\"  \n            alt=\"kvelian\" /\u003e\n            \u003cbr /\u003e\n            \u003csub style=\"font-size:13px\"\u003e\u003cb\u003e🌵 kvelian\u003c/b\u003e\u003c/sub\u003e\n        \u003c/a\u003e\n    \u003c/td\u003e\n  \u003c/tr\u003e\n\u003c/table\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsiberiacancode%2Fmock-config-server","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsiberiacancode%2Fmock-config-server","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsiberiacancode%2Fmock-config-server/lists"}