|
/* |
|
* Copyright 2018 Google LLC |
|
* |
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
|
* you may not use this file except in compliance with the License. |
|
* You may obtain a copy of the License at |
|
* |
|
* https://www.apache.org/licenses/LICENSE-2.0 |
|
* |
|
* Unless required by applicable law or agreed to in writing, software |
|
* distributed under the License is distributed on an "AS IS" BASIS, |
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|
* See the License for the specific language governing permissions and |
|
* limitations under the License. |
|
*/ |
|
|
|
import * as functions from 'firebase-functions' |
|
|
|
export const onMessageCreate = functions.database |
|
.ref('/rooms/{roomId}/messages/{messageId}') |
|
.onCreate(async (snapshot, context) => { |
|
const roomId = context.params.roomId |
|
const messageId = context.params.messageId |
|
console.log(`New message ${messageId} in room ${roomId}`) |
|
|
|
const messageData = snapshot.val() |
|
const text = addPizzazz(messageData.text) |
|
await snapshot.ref.update({ text: text }) |
|
|
|
const countRef = snapshot.ref.parent.parent.child('messageCount') |
|
return countRef.transaction(count => { |
|
return count + 1 |
|
}) |
|
}) |
|
|
|
export const onMessageDelete = functions.database |
|
.ref('/rooms/{roomId}/messages/{messageId}') |
|
.onDelete(async (snapshot, context) => { |
|
const countRef = snapshot.ref.parent.parent.child('messageCount') |
|
return countRef.transaction(count => { |
|
return count - 1 |
|
}) |
|
}) |
|
|
|
function addPizzazz(text: string): string { |
|
return text.replace(/\bpizza\b/g, '🍕') |
|
} |
|
|
|
export const onMessageUpdate = functions.database |
|
.ref('/rooms/{roomId}/messages/{messageId}') |
|
.onUpdate((change, context) => { |
|
const before = change.before.val() |
|
const after = change.after.val() |
|
|
|
if (before.text === after.text) { |
|
console.log("Text didn't change") |
|
return null |
|
} |
|
|
|
const text = addPizzazz(after.text) |
|
const timeEdited = Date.now() |
|
return change.after.ref.update({ text, timeEdited }) |
|
}) |
Hello,
I was following your instructions in the youtube video. But when using change.after.val() - I am getting error: - Object is possibly 'undefined'.ts(2532) (parameter) change: functions.Change<functions.database.DataSnapshot>
Could you please look into it and let me know what was the issue.
Thanks
Shaun