DEV Community

sasurau4
sasurau4

Posted on

Create mock API server with Authorization by Micro, GraphQL

In these days, Modern web application divided into 2 parts.
One is client side such as web browser, iOS or Android application.
Another is server side.
They are connected with web API.

If we define API schema like GraphQL or Swagger, this Architecture enable us to develop frontend and backend in parallel.

Parallel development seems good and faster than other methods, but it cause problem about frontend development.
How to develop frontend when no backend implementation?

One answer is mock backend server from schema.

So, This article introduce how to mock GraphQL server with json-web-token authorization.
The code is here

Tools

The reason why I choice micro as mock-server

micro-dev features are very useful.
Hot reloading make us faster to write mock server, Pretty logs in stdout are very convenient for debugging and some other feature are good.

Of course, we can also use same features as micro-dev with express-server.
To enable hot reload, install webpack and some related npm modules, modify webpack config and some others.
To enable pretty log, apply middleware, customize morgan output.
They are a bit complicated.

So, micro-dev has these features by default.

Recipe

All routes

module.exports = router(
  post('/auth/login', loginHandler),
  post('/graphql', graphqlHandler),
  get('/graphql', graphqlHandler)
);
Enter fullscreen mode Exit fullscreen mode

Only two routes one is for login, another is graphql.
micro doesn't have router itself, so use micro-router.
This is very simple!

Login Handler

const loginHandler = async (req, res) => {
  const body = await json(req);
  const { email, password } = body;

  // check correct user's email and password set
  if (!isUser({ email, password })) {
    return send(res, 401, 'Incorrect email or password');
  }

  const access_token = createToken({ email, password });
  return send(res, 200, { access_token });
};
Enter fullscreen mode Exit fullscreen mode

LoginHandler simply check whether email and password in request body is correct combination or not.
If pass the check, send 200 with access_token.

More details about authorization with jwt, see auth.js

GraphQL Handler

const apolloHandler = apolloServer.createHandler();

const graphqlHandler = async (req, res) => {

  const { authorization } = req.headers;

  // check authorization format check
  if (authorization === undefined || authorization.split(' ')[0] !== 'Bearer') {
    return send(res, 401, { error: 'Error in authorization format' });
  }

  // check token
  const { error } = await verifyToken(authorization.split(' ')[1]).catch(e => ({
    data: null,
    error: e,
  }));

  if (error) {
    console.log(error);
    return send(res, 401, { error: 'Error access_token is revoked' });
  }

  return apolloHandler(req, res);
};
Enter fullscreen mode Exit fullscreen mode

GraphQL handler simply check whether Bearer token in request header is valid or not.
If pass the check, it return apolloHandler that is defined in apollo-server-micro.

GraphQL resovers and schemas are ommited this article, see apollo-server.js.

Note:
You want to see GraphQL playgruond in your browser for trying queries.
Adding some checks and early return of apolloHandler.
In my repo, check user-agent as Chrome or not.

Conclusion

Micro-dev server using API mock server is very good for developmer experience.
No config, Good looks log, Hot reloading.

If you interested in micro, see awesome-micro!
Thanks for reading.

Reference

This article inspired by below articles. Thanks!
https://qiita.com/acro5piano/items/d421e2d41ee15e20e1de
https://qiita.com/oz4you/items/3f3223048bd2109de47b

Top comments (0)