Using the LocalStorage API to persist the Miragejs db

635 Views Asked by At

While reading the docs for miragejs, on this page, it says:

Mirage resets its state on every browser reload, which can be a double-edged sword but is often what you want for development and testing. (You can use localStorage if you'd like to add temporary persistence to Mirage.)

However, I can't seem to find any documentation or examples anywhere on how to actually set up local storage for db persistence.

Does anyone have any experience with this, or know of some code examples or walkthroughs I could reference?

2

There are 2 best solutions below

0
On

a crude solution would be to dump the db after each modification:

const server = createServer(...);

// https://miragejs.com/api/classes/server/#pretender
server.pretender.handledRequest = function(verb) {
  if (verb.toLowerCase() !== 'get' && verb.toLowerCase() !== 'head') {
    localStorage.setItem('db', JSON.stringify(server.db.dump()));
  }
};

and restore it upon server creation:

const dbData = localStorage.getItem('db');

if (dbData) {
  // https://miragejs.com/api/classes/db/#load-data
  server.db.loadData(JSON.parse(dbData));
}
0
On

Dan's answer works great, but there's one side-effect you should be aware of - you overwrite Mirage's original callback function that is responsible for logging request in the console.

My solution was to first store the original callback as a variable, then hook, do my things and then fire the original callback.

const mirageRequestHandler = server.pretender.handledRequest;
server.pretender.handledRequest = (verb, path, request) => {
    if (!['get', 'head'].includes(verb.toLowerCase())) {
        setLocalDb(server);
    }

    mirageRequestHandler(verb, path, request);
};