简体   繁体   English

使用 LocalStorage API 保存 Miragejs 数据库

[英]Using the LocalStorage API to persist the Miragejs db

While reading the docs for miragejs, on this page , it says:在阅读 miragejs 的文档时,在此页面上,它说:

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. Mirage 会在每次重新加载浏览器时重置其 state,这可能是一把双刃剑,但通常是开发和测试所需的。 (You can use localStorage if you'd like to add temporary persistence to Mirage.) (如果您想为 Mirage 添加临时持久性,可以使用 localStorage。)

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?有没有人对此有任何经验,或者知道我可以参考的一些代码示例或演练?

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));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM