Firebase云功能:如何从`change`和`context`获取数据?

时间:2018-04-10 17:12:44

标签: javascript firebase google-cloud-firestore google-cloud-functions

Firebase SDK for Cloud Functions Migration Guide: Beta to version 1.0文档说明云功能触发onUpdate参数现在为(change, context)。如果我记录change,我会得到一个对象:

Change {
  before: 
   QueryDocumentSnapshot {
     _ref: DocumentReference { _firestore: [Object], _referencePath: [Object] },
     _fieldsProto: { word: [Object] },
     _readTime: undefined,
     _createTime: '2018-04-10T15:37:11.775234000Z',
     _updateTime: '2018-04-10T15:58:06.388975000Z' },
  after: 
   QueryDocumentSnapshot {
     _ref: DocumentReference { _firestore: [Object], _referencePath: [Object] },
     _fieldsProto: { word: [Object] },
     _readTime: undefined,
     _createTime: '2018-04-10T15:37:11.775234000Z',
     _updateTime: '2018-04-10T15:58:06.388975000Z' } }

文档说我可以使用change.before.val()change.after.val()从此对象获取数据。但是记录change.before.val()会导致出现此错误消息:

TypeError: change.before.val is not a function

记录change.after.val()会产生以下错误消息:

TypeError: Cannot read property 'val' of undefined

记录context会导致此对象无法包含我想要的数据:

{ eventId: 'a981ffc3-a07a-4b17-8698-0f3ef6207ced-0',
  timestamp: '2018-04-10T17:03:00.699887Z',
  eventType: 'google.firestore.document.update',
  resource: 
   { service: 'firestore.googleapis.com',
     name: 'projects/languagetwo-cd94d/databases/(default)/documents/Oxford_Dictionaries/Word_Request' },
  params: { Word_Request: 'Word_Request' } }

(change, context)参数是仅适用于实时数据库而不适用于Cloud Firestore?

这是我的代码:

exports.oxfordPronunciation = functions.firestore.document('Oxford_Dictionaries/{Word_Request}').onUpdate((change, context) => {

console.log(change);

  let options = {
    url: 'https://od-api.oxforddictionaries.com/api/v1/entries/en/ace/pronunciations%3B%20regions%3Dus',
    headers: {
      'app_id': 'TDK',
      'app_key': 'swordfish'
    }
  };

  function callback(error, response, body) {
    if (!error && response.statusCode == 200) {
      var word = JSON.parse(body);
      admin.firestore().collection('Oxford_Dictionaries').doc('Word_Response').set({ 'token': word });
    }
  }

  request(options, callback);
  return 0;
});

以下是我的Node模块:

npm list --depth=0 
functions@ /Users/TDK/LanguageTwo/functions
├── firebase-admin@5.12.0
├── firebase-functions@1.0.1
└── request@2.85.0

1 个答案:

答案 0 :(得分:3)

Firestore中,您需要使用data()代替val()

exports.dbWrite = functions.firestore.document('/path').onWrite((change, context) => {
const beforeData = change.before.data(); // data before the write
const afterData = change.after.data(); // data after the write
});