Puremock

⚡️ A zero-dependency mock api server ⚡️

Motivation

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). 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 cool parts

  • No dependencies. Which is just a nice thing to have for me personally.
  • Super-simple. The whole source is only 3 js files.
  • Mockfile Hot-Reload support. No need to use nodemon or tools like that.

The not so cool parts

  • Sometimes the watcher method fails to load mockfile. No idea why, so I just rety a couple times internally.
  • No predefined responses for popular error codes like 503, 401 and so on. Would've been nice to have those.

How does it work

The hardest part was easily the hot reloading. 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.

Config

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
    }
  },
}
1
2
3
4
5
6
7
8
9

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"
    }
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

Pretty neat, eh?