首页 > 解决方案 > 如何使用 onWrite 的事件

问题描述

我想在 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);
      });
});

标签: javascriptfirebasefirebase-realtime-databasegoogle-cloud-functions

解决方案


的签名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);
      });
});

另见:


推荐阅读