2020-09-24
|~2 min read
|273 words
I’ve been using MirageJS to mock out API calls for a React App recently and really like it!
One small issue I ran into was how to handle multiple namespaces in the API routes.
Since my app makes use of two existing namespaces for the API, I wanted to mock that with MirageJS.
Working with colleagues, we came up with two general approaches:
routes
methodThe former works well if you have only one or two routes to the alternate namespace and the majority can be handled within the “primary” namespace. If, however, the routes are evenly split (or you suspect you may add more later) the latter will save keystrokes.
In fact, the docs demonstrate how the first approach might look:
// source: https://miragejs.com/api/classes/server/#namespace
new Server({
routes() {
// this route handles /auth
this.get('/auth', function() { ...});
this.namespace = '/api';
// this route will handle the URL '/api/contacts'
this.get('/contacts', 'contacts');
};
})
What about the alternative? Where we want to effectively have multiple namespaced routes?
import { Server as MirageServer, Response } from 'miragejs';
import { generate } from 'olo-data-generator';
export function serverConfig(Server: typeof MirageServer): MirageServer {
return new Server({
routes() {
// PRIMARY namespace
this.namespace = 'api';
this.get('settings', () => {
const data = { settingA: 100, settingBIds: ['0e951690-3878-5cc2-9ed4-e305b516044b'] };
return data;
});
this.post('settings', () => new Response(200));
// ALTERNATE namespace(s)
this.namespace = 'alternate';
this.get('keys', () => return new Response(200, {}, {keys: ['1','2','3']}))
},
environment: process.env.NODE_ENV === 'test' ? 'test' : 'development',
});
}
In this way I’m able to mock out multiple
Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!