javascript - Firebase functions algolia onWrite
问题描述
I want the user I added for firebase to be automatically added to the algolia, and I created such a function, but I get some errors
My onWrite Functions
exports.updateIndex = functions.database.ref('/Users/{userId}').onWrite(event => {
var client = algoliasearch(ALGOLIA_APP_ID,ALGOLIA_ADMIN_KEY);
const index = client.initIndex('Users');
const userId = event.params.userId;
const data = event.data.val()
if (!data) {
return index.deleteObject(bookId, (err) => {
if (err) throw err
console.log('User Removed from Algolia Index', userId)
})}
data['objectID'] = userId
return index.saveObject(data, (err, content) => {
if (err) throw err
console.log('User Updated in Algolia Index', data.objectID)
})
});
I am receiving such an error
TypeError: Cannot read property 'userId' of undefined
at exports.updateIndex.functions.database.ref.onWrite.event (/user_code/index.js:43:29)
at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27)
at next (native)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36)
at /var/tmp/worker/worker.js:716:24
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
Actually I don't understand database.ref('/Users/{userId}')? How can I do?
解决方案
Change this:
exports.updateIndex = functions.database.ref('/Users/{userId}').onWrite(event => {
const userId = event.params.userId;
const data = event.data.val()
into this:
exports.updateIndex = functions.database.ref('/Users/{userId}').onWrite((change,context) => {
const userId = context.params.userId;
const data = change.after.val();
The cloud functions were updated and onWrite
now has two parameters change
and context
. To be able to retrieve the wildcards then you need to use the context
parameter.
The
context
parameter provides information about the function's execution. Identical across asynchronous functions types, context contains the fieldseventId
,timestamp
,eventType
,resource
, andparams
.
more info here:
https://firebase.google.com/docs/functions/beta-v1-diff#realtime-database
推荐阅读
- haskell - Set value of record field to calculation involving another field in same record
- reactjs - 将我的静态网站的 AWS 给定域更改为 godaddy 域
- angular - 如何为版本 7 更新 Angular 项目版本 5
- fortran - 如何将包含字符串的文本文件读入Fortran中的数组
- python - 如何仅获取与模式匹配的文件名
- swift - 视频缩略图被颠倒了
- sql-server - 我无法让我的 Microsoft SQL Server 触发器正常运行
- forms - 使用 yup 和自定义验证来验证 react-final-form 表单
- vue.js - 如何将 BootstrapVue 在 Nuxt.js 中使用 Purgecss 所需的所有内容列入白名单
- pandas - 在熊猫中将重复的索引合并为一个