Reputation: 14241
I want to synchronize the data between my server's database and my Firebase realtime db.
The first part is done, syncing from my server to Firebase. The other part is the missing one: from Firebase to my server.
I'm trying to write a Firebase Cloud Function using a DB trigger (in this case an update on a table), but I don't know what am I doing wrong at the moment. In this code, the Lint shows this Each then() should return a value or throw (promise/always-return)
but I don't know where should I put that.
const functions = require('firebase-functions');
const axios = require('axios');
exports.syncUserAvailability = functions.database
.ref('/users/{userId}')
.onUpdate(event => {
const user = event.data.val()
updateUserIntoBackend(user.user_id, user.online)
})
function updateUserIntoBackend(userId, bool) {
promise = axios.put(
'http://MY_SERVER_IP/users/' + userId,
{
'online' : bool
},
{
'headers' : {
'Accept' : 'application/json',
'Content-Type' : 'application/json',
'Authorization' : 'Bearer ' + someToken
}
})
.then(function(response) {
console.log(response.data)
})
}
Upvotes: 0
Views: 1212
Reputation: 74680
Promises should always be returned from functions if you want anything else to use that promises resolution/rejection. If you are not returning the promise for something else to use, why are you using a promise?
Say you have a function that resolved a promise:
function somePromise(){
Promise.resolve('yay')
}
If you don't return the promise, then this will fail.
somePromise().then(yay => console.log(yay)
That would try to run the .then
function on undefined
(which is the return value of a function when not defined). So you must return the promise that does have the .then
function attached.
function somePromise(){
return Promise.resolve('yay')
}
It's possible your code is producing an error but because you have not returned the promise in onUpdate
, the firebase trigger can not wait for the promise to be resolved.
exports.syncUserAvailability = functions.database
.ref('/users/{userId}')
.onUpdate(event => {
const user = event.data.val()
return updateUserIntoBackend(user.user_id, user.online)
})
The same for the updateUserIntoBackend
, the promise chain must be returned from the function so the onUpdate
event function can wait for that promise to resolve.
function updateUserIntoBackend(userId, bool) {
return axios.put(
'http://MY_SERVER_IP/users/' + userId,
{
'online' : bool
},
{
'headers' : {
'Accept' : 'application/json',
'Content-Type' : 'application/json',
'Authorization' : 'Bearer ' + someToken
}
})
.then(function(response) {
console.log(response.data)
return response
})
}
The return in the final .then
might be redundant in this case but it's good practice to return something useful in case you do need to use it.
Upvotes: 1