sumedhe
sumedhe

Reputation: 1018

Can't update firebase database using firebase cloud functions without using database triggers

I created a firebase function to update a value in firebase database when an API call is made. It gives the following error.

i  deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run lint

> functions@ lint /home/sumedhe/Project/mobile-atm-server/functions
> tslint --project tsconfig.json


ERROR: /home/sumedhe/Project/mobile-atm-server/functions/src/index.ts[12, 5]: Promises must be handled appropriately

npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! functions@ lint: `tslint --project tsconfig.json`
npm ERR! Exit status 2
npm ERR! 
npm ERR! Failed at the functions@ lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/sumedhe/.npm/_logs/2018-05-27T20_11_58_855Z-debug.log

Error: functions predeploy error: Command terminated with non-zero exit code2

Code

import * as express from "express";
import * as admin from "firebase-admin";
import * as functions from "firebase-functions";
const app = express();
admin.initializeApp();

app.get("/mytransactions/", async function getUser(req: express.Request, res: express.Response) {

    // HERE IT GIVES THE ERROR //
    admin.database().ref('/modified').set("yes");
});
exports.api = functions.https.onRequest(app);

But if I use the same code with firebase database trigger, it works well.

exports.touch = functions.database.ref('/transactions/{item}').onWrite(
   (change, context) => admin.database().ref('/modified').set("yes"));

Upvotes: 3

Views: 824

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317467

The lint error says:

[12, 5]: Promises must be handled appropriately

This means on line 12 (of JavaScript transpiled from TypeScript) you're note handling a promise. The following function returns a promise:

admin.database().ref('/modified').set("yes");

You need to do something with that promise. Given that this is an HTTP type function, you should send something back to the client with respect to the result of the promise. Perhaps like this:

admin.database().ref('/modified').set("yes")
.then(() => {
    res.send('ok')
})
.catch(err => {
    res.status(500).send(err)
})

It's up to you what you want to do, but you need to deal with continuations and errors from methods that return promises, such as DatabaseReference.set().

Upvotes: 2

Related Questions