🎉 Mock Config Server
tool that easily and quickly imitates server operation, create full fake api in few steps
Install
Install with npm or yarn
$ npm i mock-config-server --save --dev
$ yarn add mock-config-server --dev
🦉 Philosophy
🎉 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 and mock-service-worker 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.
Features
- TypeScript support out of the box - full typed package
- Full Rest Api support - using simple configs of a certain format, you can easily simulate rest operation of servers
- GraphQL support - using simple configs of a certain format, you can easily simulate graphlql operation of servers
- CORS setup - turn on and off CORS, fully customizable when CORS is turned on
- Support for any kind of static - server can return any type of static file if needed. Images, HTML, CSS, JSON, etc
Usage
Install 🎉 Mock Config Server with npm or yarn
$ npm i mock-config-server --save --dev
$ yarn add mock-config-server --dev
Create a mock-server.config.js
file with server configuration
const mockServerConfig = {
rest: {
baseUrl: '/api',
configs: [
{
path: '/user',
method: 'get',
routes: [{ data: { emoji: '🦁', name: 'Nursultan' } }]
}
]
}
};
export default mockServerConfig;
Start 🎉 Mock Config Server
$ npx mock-config-server
If the package is already installed you can use short command mcs
🎭 Parameters for mock-server.config.(js|ts)
rest?
Rest configs for mock requests
baseUrl?
{string} part of the url that will be substituted at the beginning of rest request url (default: '/'
)configs
{Array} configs for mock requests, readinterceptors?
{Interceptors} functions to change request or response parameters, read
graphql?
GraphQL configs for mock requests
baseUrl?
{string} part of the url that will be substituted at the beginning of graphql request url (default: '/'
)configs
{Array} configs for mock requests, readinterceptors?
{Interceptors} functions to change request or response parameters, read
staticPath?
{StaticPath} entity for working with static files, readinterceptors?
{Interceptors} functions to change request or response parameters, readcors?
{Cors} CORS settings object (default: CORS is turn off
), readport?
{number} server port (default: 31299
)baseUrl?
{string} part of the url that will be substituted at the beginning of the request url (default: '/'
)
Configs
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
Rest request config
path
{string | RegExp} request pathmethod
{GET | POST | DELETE | PUT | PATCH} rest api methodroutes
{RestRouteConfig[]} request routes
data
{any} mock data of requestentities?
Object<headers | cookies | query | params | body> object that helps in data retrievalinterceptors?
{Interceptors} functions to change request or response parameters, read
interceptors?
{Interceptors} functions to change request or response parameters, read
GraphQL request config
operationType
{query | mutation} graphql operation typeoperationName
{string} graphql operation nameroutes
{GraphQLRouteConfig[]} request routes
data
{any} mock data of requestentities?
Object<headers | cookies | query | variables> object that helps in data retrievalinterceptors?
{Interceptors} functions to change request or response parameters, read
interceptors?
{Interceptors} functions to change request or response parameters, read
Rest example
const mockServerConfig = {
rest: {
baseUrl: '/api',
configs: [
{
path: '/user',
method: 'get',
routes: [
{
entities: {
headers: { 'name-header': 'Nursultan' }
},
data: { emoji: '🦁', name: 'Nursultan' }
},
{
entities: {
headers: { 'name-header': 'Dmitriy' }
},
data: { emoji: '☄', name: 'Dmitriy' }
}
]
}
]
}
};
module.exports = mockServerConfig;
Now you can make a request with an additional header and get the desired result
fetch('http://localhost:31299/api/user', {
headers: {
'name-header': 'Nursultan',
'Content-Type': 'application/json'
}
})
.then((response) => response.json())
.then((data) => console.log(data));
GraphQL example
const mockServerConfig = {
graphql: {
baseUrl: '/graphql',
configs: [
{
operationType: 'query',
operationName: 'GetUser',
routes: [
{
entities: {
headers: { 'name-header': 'Nursultan' }
},
data: { emoji: '🦁', name: 'Nursultan' }
},
{
entities: {
headers: { 'name-header': 'Dmitriy' }
},
data: { emoji: '☄', name: 'Dmitriy' }
}
]
}
]
}
};
module.exports = mockServerConfig;
Now you can make a request with an additional header and get the desired result
const body = JSON.stringify({
query: 'query GetUser { name }'
});
fetch('http://localhost:31299/graphql', {
method: 'POST',
headers: {
'name-header': 'Nursultan',
'Content-Type': 'application/json'
},
body
})
.then((response) => response.json())
.then((data) => console.log(data));
Static Path
Entity for connecting statics to the server, like HTML, JSON, PNG, etc.
string
path to your static filesObject<{prefix, path}
prefix
{string} path prefix for requestpath
{string} path to your static files
Array<string | Object<{prefix, path}>>
Cors
Object with settings for 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.
origin
{string | RegExp | Array<string | RegExp> | Function | Promise } available origins from which requests can be mademethods?
{Array<GET | POST | DELETE | PUT | PATCH>} available methods (default: *
)allowedHeaders?
{Array} allowed headers (default: *
)exposedHeaders?
{Array} exposed headers (default: *
)credentials?
{boolean} param tells browsers whether to expose the response to the frontend JavaScript code (default: true
)maxAge?
{number} how long the results can be cached (default: 3600
)
Interceptors
Functions to change request or response parameters
request?
(params) => voidresponse?
(data, params) => any
Request
params
request
request objectsetDelay
(delay) => Promise
delay
{number} milliseconds of delay time
getHeader
(field) => string | number | string[] | undefined
field
{string} name of response header
getHeaders
() => Record<string | number | string[] | undefined>getCookie
(name) => string | undefined
name
{string} name of cookie
Response
data
{any} mock data of requestparams
request
request objectresponse
response objectsetDelay
(delay) => Promise
delay
{number} milliseconds of delay time
setStatusCode
(statusCode) => void
statusCode
{number} status code for response
setHeader
(field, value) => void
field
{string} name of response headervalue
{string | string[] | undefined} value of response header
appendHeader
(field, value) => void
field
{string} name of response headervalue
{string | string[] | undefined} value of response header
getHeader
(field) => string | number | string[] | undefined
field
{string} name of response header
getHeaders
() => Record<string | number | string[] | undefined>setCookie
(name, value, options) => void
name
{string} name of cookievalue
{string} value of cookieoptions
{CookieOptions | undefined} cookie options (like path, expires, etc.)
getCookie
(name) => string | undefined
name
{string} name of cookie
clearCookie
(name, options) => void
name
{string} name of cookieoptions
{CookieOptions | undefined} cookie options (like path, expires, etc.)
attachment
(filename) => void
filename
{string} name of file in 'Content-Disposition' header
CLI usage
mcs [options]
Options:
--baseUrl, -b Set base url (default: '/')
--port, -p Set port (default: 31299)
--staticPath, -s Set static path
--config, -c Set path to config file (default: './mock-server.config.(?:ts|mts|cts|js|mjs|cjs)')
--watch, -w Enables server restart after config file changes (default: false)
--version, -v Show version number
--help, -h Show help
Examples:
mcs --baseurl /base/url --port 3000 --config ./path/to/config.ts -w
mcs --help
✨ Contributors