如何在feathersjs app之外编辑数据库时更新客户端

问题描述 投票:0回答:2

我有两个服务器端应用程序编辑同一个数据库。

一台服务器是feathersjs应用程序,另一台服务器是一个简单的nodejs应用程序。前端应用程序通过feathersjs客户端连接到feathersjs应用程序。

如果nodejs应用程序编辑数据库,我可以更新连接到feathersjs应用程序的客户端吗?目前,在featherjs应用程序之外进行的任何更改都不会反映在feathersjs客户端上。

我可以以某种方式触发修补事件并强制客户端下载更新的数据吗?

javascript feathersjs
2个回答
1
投票

如果您使用mongodb和WiredTiger storageEngine,您可以使用collection.watch()函数并在您的羽毛应用程序中添加一个类似于此的监视器

   //src/services/monitor.js 
   module.exports = function(app){
      //get mongo client
      const mongoClient = app.get('mongoClient');
      //connect db
      mongoClient.then(db => {

        //collection to watch
        const collection = db.collection('your_collection_name')

        //watch collection
        const changeStream = collection.watch({ fullDocument: 'updateLookup' });

        //on some data changed
        changeStream.on('change', data => {
          console.log ( 'something is changed in your collection' , data )
          //your service.emit
        });
      })
    }

然后我在/src/services/index.js中添加了这个简单的显示器(可能不是正确的方式,但它的工作原理)

//src/services/index.js
...
const monitor = require('./monitor.js');
module.exports = function (app) {
   ...
   app.configure(monitor);
   ...
}; 

收集的每次更改都会返回数据

{ _id:
   { _data:
      '825C7F03230000001C29295A100490DEF2C65812410FABF0DE46F9C89D7246645F696400645C1AC097B189CBD5D4A24D330004' },
  operationType: 'replace',
  clusterTime:
   Timestamp { _bsontype: 'Timestamp', low_: 28, high_: 1551827747 },
  fullDocument:
   { _id: 5c1ac097b189cbd5d4a24d33,
     id: '12',
     language: 'it-IT',
     category: 'some data',
     slug: '',
     description: 'some data',
     src:'',
     color: 'card',
     status: true,
     home: true,
     order_int: '3',
     visual: 'card' },
  ns: { db: 'mydb', coll: 'mycollection' },
  documentKey: { _id: 5c1ac097b189cbd5d4a24d33 } }

更多信息在这里https://docs.mongodb.com/manual/reference/method/db.collection.watch/


1
投票

正如您所指出的,只有通过Feathers API进行的更改才会得到反映,但在服务器上,您始终可以通过service.emit发出所需的事件:

dbConnection.on('someDatabaseUpdate', data => {
  app.service('messages').emit('patched', data);
  app.service('messages').emit('updated', data);
});

这里要注意的事项(也在this issue中讨论过):

  • 没有关于方法调用的用户或任何其他信息
  • data不会通过任何服务挂钩运行
© www.soinside.com 2019 - 2024. All rights reserved.