service-mocker

2 minute read Published:

Service workers to the rescue!
Table of Contents

While prototyping a frontend application I came across an amazing project that I wanted to share.

It’s called service-mocker and what it does is - by applying some neat request hooking magic, allows you to write a backend prototype of your server in a ExpressJS-like syntax, right inside your frontend application.

What is even neater - they are employing service workers (obviously working only on modern browsers) which allows you to see the requests to your fake/mock backend inside the Network request panel!

Let’s see how it works (I’ll be demonstrating on a create-react-app application)

1 Create your app with create-react-app

2 Perform npm run eject

Because we’ll have to modify webpack scripts in order to add an additional entry point for the ‘server’.

3 Install the mocker

Do npm i service-mocker --save-dev

4 Include the pointer to the mocker server script

In config/paths.js around line 37 add: serverJs: resolveApp('src/server.js'),

5 Prepare the splitting

In config/webpack.dev.js change the entry to look like this:

entry: {
  'src/app': [
    require.resolve('react-dev-utils/webpackHotDevClient'),
    require.resolve('./polyfills'),
    paths.appIndexJs
  ],
  'src/server': paths.serverJs
}

And the configuration of HtmlWebpackPlugin to look like this:

 new HtmlWebpackPlugin({
      inject: true,
      chunks: ['src/app'],
      template: paths.appHtml,
    }),

What we are doing here is making sure that webpack will generate two JS files from our source code and will inject only one of them into the HTML file. The other one will be loaded by the service worker code.

6 Write your mock server!

import { createServer } from 'service-mocker/server';
const { router } = createServer("/api");

router.post("/process", async (req, res) => {
  let body = await req.json();
  res.json({result: body});
});

// or you can use the shorthand method
router.get('/greet', 'Hello new world!');

7 The last step

Hook the service-mocker so that all HTTP requests for ‘/api’ will to it instead of an actual backend server: A good place for this is index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { createClient } from 'service-mocker/client';
const client = createClient('server.js');
client.ready.then(async () => {
    ReactDOM.render(
        <App />,
        document.getElementById('root')
    );
});

Now, from any place in code, fire a request to /api/greet or /api/process and watch the magic!

comments powered by Disqus