我想在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);
});
});
答案 0 :(得分:0)
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);
});
});
另请参阅: