Hacktoberfest, mainly, but also just a search for a package like this that took me more than an hour and ultimately pointed me to Mockoon (which is great, btw, check it out (opens new window)). But I figured I should make this too, since I have a soft spot for cute zero-dep tools, so here we are. Hope you'll enjoy using it as much, as I did developing it.
Mock It Now!The hardest part was easily the hot reloading (opens new window). I didn't want it to be "dumb" and to simply re-parse the whole mockfile on each request, which brought me to node's fs.watch
method which I had some issues with. Then there was an issue with config not removing the old keys for some reason, but everything ended up working using the plain ol' delete <propertyName>
.
Oh! And also the dynamic URL part was a bit confusing at first. Since I'm not really writing recursive logic on a daily basis it always takes me a while to figure out. But hey, it was worth it! Now puremock has support for /some/path/:dynamicPart
urls, with overrides if there is also an exact url defined and all the other things you would expect from something like express' router.
Since the whole idea came together from the need to dump a JSON file somewhere and have a mock server running, the config is very basic.
{
"GET <path>": {
"response": {
"status": Number,
"header": Object, // { headerName: headerValue },
"response": Object
}
},
}
So your generic mockfile can look like this
{
"GET /": {
"response": {
"status": "ok"
}
},
"GET /error": {
"status": 503,
"header": {
"x-powered-by": "mock-api-server"
},
"response": {
"error": "Internal Server Error"
}
},
"GET /articles/:name": {
"response": {
"title": "Foobar"
}
}
}
Pretty neat, eh?