【问题标题】:How to update clients when database is edited outside of feathersjs app在feathersjs应用程序之外编辑数据库时如何更新客户端
【发布时间】:2019-01-04 11:19:45
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: javascript feathersjs


    【解决方案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/

    【讨论】:

      【解决方案2】:

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

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

      此处需要注意的事项(也在this issue 中讨论过):

      • 不会有用户或有关方法调用的任何其他信息
      • data 不会通过任何服务挂钩运行

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-05
        • 1970-01-01
        • 1970-01-01
        • 2015-08-05
        • 2011-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多