Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the LocalStorage API to persist the Miragejs db

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?

like image 709
Anthony Avatar asked Sep 18 '25 10:09

Anthony


2 Answers

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));
}
like image 69
Dan O Avatar answered Sep 21 '25 00:09

Dan O


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);
};
like image 43
adamkarminski Avatar answered Sep 21 '25 00:09

adamkarminski