使用ES6Proxy延迟加载资源
我正在为存储在 MongoDB 中的文档(类似于 Mongoose)构建类似 ActiveRecord 类的东西。我有两个目标:
-
使用代理拦截文档上的所有属性设置器,并自动创建要发送到 Mongo 的更新查询。我已经在 SO 上找到了解决此问题的方法。
-
防止从数据库中进行不必要的读取。即如果在文档上执行一个函数,并且该函数只设置属性,并且不使用文档的现有属性,那么我不需要从数据库中读取文档,我可以直接更新它. 但是,如果该函数使用文档的任何属性,我必须先从数据库中读取它,然后才能继续使用代码。例子:
// Don't load the document yet, wait for a property 'read'. const order = new Order({ id: '123abc' }); // Set property. order.destination = 'USA'; // No property 'read', Order class can just directly send a update query to Mongo ({ $set: { destination: 'USA' } }). await order.save();// Don't load the document yet, wait for a property 'read'. const order = new Order({ id: '123abc' }); // Read 'weight' from the order object/document and then set 'shipmentCost'. // Now that a 'get' operation is performed, Proxy needs to step in and load the document '123abc' from Mongo. // 'weight' will be read from the newly-loaded document. order.shipmentCost = order.weight * 4.5; await order.save();
我该怎么办?这似乎很简单:在文档对象上设置一个“get”陷阱。如果它是第一个属性“get”,则从 Mongo 加载文档并缓存它。但是如何将异步操作放入 getter 中?