Simple service for API mock
npm install -g monis
monis [command] [options]
monis serve -c monis.json -p 3001
- You can specify the server listening port by
-p, --port
. - Monis will use
3001
as default port.
- Monis support
json
formated configuration &javascript
which export ajson
configuration. - You can specify config file by
-c, --config
. - It will use
monis.json
in current working directory as default.
- You can enable hot reload mode by
--hot
.
-
Prepare an configuration file with
json
orjavascript
.// monis.json { "/fruit": { "get": { "result": [ { "name": "apple", "price": 5.3 }, { "name": "melon", "price": 2.5 } ], "count": 2, "@code": 500 }, "post": "OK" }, "/meat": { "get": "ref#meat.json" } }
// monis.js const template = { '/fruits': { 'get': { 'results|1-4': [ { 'name|1': [ 'apple', 'melon', 'banaba', 'strawberry', 'cherry' ], 'price|1-20.2': 1 } ], count: function () { return this.results.length; }, '@code': 400 } }, '/fruits/:fruit': { 'get': function(params, query) { return { name: params.fruit, 'price|1-20.2': 1, '@code': 200 } } }, "/meat": { "get": "ref#meat.json" } }; module.exports = template;
-
Change working directory to configuration folder
$ cd /path/to/configuration/folder
-
Start Server
$ monis serve
monis will start automatically with router registered. If you try to visit
localhost:3001/fruits
, you can get the response:{ "results": [ { "name": "banaba", "price": 8.66 }, { "name": "melon", "price": 7.18 } ], "count": 2 }
monis configuration is like below:
{"path": { "method": response}}
There are three types of response
:
object
json
response is supported in configuration. you can also set the response of this request by using@code
in config json.{ "get": { "result": [ { "name": "apple", "price": 5.3 }, { "name": "melon", "price": 2.5 } ], "count": 2, "@code": 500 } }
string
{ "post": "OK" }
reference
you can set a json file as the response using
ref#
+relative path
.{ "get": "ref#meat.json" }
Javascript configuration
can handle more complex case. And it support all the functions provided by json configuration
as well.
Each javascript configuration
should export
a json
object
module.exports = {
'/fruits': {
get: {
result: [],
count: 0,
}
}
}
Monis
support mock function with Mockjs formated config.
To getting started with
Mockjs
, please refer to this document.
Here is an example for Mockjs
styled config:
module.exports = {
'/fruits': {
'get': {
'results|1-4': [
{
'name|1': [
'apple',
'melon',
'banaba',
'strawberry',
'cherry'
],
'price|1-20.2': 1
}
],
count: function () {
return this.results.length;
}
}
}
}
Return Code
is also supported in javascript
configuration.
module.exports = {
'/fruits': {
get: {
result: [],
count: 0,
'@code': 404
}
}
}
module.exports = {
// Route Parameter
'/fruits/:fruit': {
'get': function(params, query) {
return {
name: params.fruit,
// URL Query
// /fruits/apple?price=2
price: query.price || 1,
'@code': 200
}
}
}
}