javascript - 如何使用 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);
});
});
解决方案
的签名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);
});
});
另见:
- 关于处理来自实时数据库的事件数据的Cloud Functions 文档
- 有关将代码升级到 1.0的Cloud Functions 文档
推荐阅读
- ios - 以 Xib 作为根视图的自定义视图
- arrays - 避免数组中的重复
- node.js - 在 node-sass@4.12.0 安装脚本 'node scripts/install.js' 失败
- javascript - 如何在引导表中显示 API JSON 数据
- r - 根据数值范围从数据框中的因子列获取级别
- python - 替换熊猫的功能给予相同的价值
- google-chrome-extension - 如何从南非以外的非洲国家/地区支付 Chrome 网上应用店开发者注册费?
- android - 使用android jetpack导航中的底部导航加载另一个片段后如何自动向下滚动工具栏
- django - 如何使用闪亮服务器修复反向代理 nginx
- sql - Regexp_Like 仅验证大写字符 [AZ] 和数字 [0-9]