【问题标题】:How to use event of onWrite如何使用 onWrite 的事件
【发布时间】:2018-07-18 22:06:56
【问题描述】:

我想在 onWrite((change,context) 中获取 post_id 的值 请帮忙?

const functions = require('firebase-functions');
const request = require('request-promise')


exports.indexPostsToElastic = functions.database.ref('/posts/{post_id}')
.onWrite(event => {

    let post_id = event.params.post_id;
});

exports.indexPostsToElastic = functions.database.ref('/posts/{post_id}')
.onWrite(( change,context) => {

    let postData = change.after.val();


    console.log('Indexing post:', postData);

    let elasticSearchConfig = functions.config().elasticsearch;
    let elasticSearchUrl = elasticSearchConfig.url + 'posts/post/' + post_id;
    let elasticSearchMethod = postData ? 'POST' : 'DELETE';

    let elasticSearchRequest = {
        method: elasticSearchMethod,
        url: elasticSearchUrl,
        auth:{
            username: elasticSearchConfig.username,
            password: elasticSearchConfig.password,
        },
        body: postData,
        json: true
      };

      return request(elasticSearchRequest).then(response => {
         console.log("ElasticSearch response", response);
      });
});

【问题讨论】:

    标签: javascript firebase firebase-realtime-database google-cloud-functions


    【解决方案1】:

    onWrite 的签名已更改。要从参数中获取值并使用它,请确保您只有一个函数,然后获取参数值:

    const functions = require('firebase-functions');
    const request = require('request-promise')
    
    
    exports.indexPostsToElastic = functions.database.ref('/posts/{post_id}')
    .onWrite((change, context) => {
    
        let post_id = context.params.post_id; // get post_id value from params
    
        let postData = change.after.val();
    
    
        console.log('Indexing post:', postData);
    
        let elasticSearchConfig = functions.config().elasticsearch;
        let elasticSearchUrl = elasticSearchConfig.url + 'posts/post/' + post_id;
        let elasticSearchMethod = postData ? 'POST' : 'DELETE';
    
        let elasticSearchRequest = {
            method: elasticSearchMethod,
            url: elasticSearchUrl,
            auth:{
                username: elasticSearchConfig.username,
                password: elasticSearchConfig.password,
            },
            body: postData,
            json: true
          };
    
          return request(elasticSearchRequest).then(response => {
             console.log("ElasticSearch response", response);
          });
    });
    

    另见:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-19
      • 2017-11-19
      • 2018-08-01
      • 2019-05-05
      • 2017-10-27
      • 2018-03-28
      • 2017-08-02
      • 2022-12-20
      相关资源
      最近更新 更多