Search code examples
typescriptfirebaseexpressgoogle-cloud-functionsfirebase-hosting

Handling HTTP requests forwarded from Firebase Hosting to Cloud Functions


I'm currently trying to patch data to my Firestore database using http. I'm trying to do this without using a external server, so by using Firebase Hosting and Functions.

First I initialized my Firebase project and I imported express, body-parser and firebase-functions-helper into the functions.

Then I added this to my firebase.json, so the source is linked to the exact function

 "rewrites": [
      {
        "source": "/api/v1/**",
        "function": "webApi"
      }
    ]

Second, I wrote this typescript that should upload the data from the HTTP patch to the Firestore database. This is stored in functions/src/index.ts

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import * as firebaseHelper from 'firebase-functions-helper/dist';
import * as express from 'express';
import * as bodyParser from 'body-parser';

admin.initializeApp(functions.config().firebase);
const db = admin.firestore();

const app = express();
const main = express();

main.use(bodyParser.json());
main.use(bodyParser.urlencoded({extended: false}));
main.use('/api/v1/', app);

const sensorsCollection = 'sensors';
export const webApi = functions.https.onRequest(main);

app.patch('/sensor/:sensorId', async(req, res) => {
    try{
        await firebaseHelper.firestore.updateDocument(db, sensorsCollection, req.params.sensorId, req.body);
        res.status(200).send('Update Success');
    }catch(error){
        res.status(204).send('Patch Error');
    }
})

But when I use postman to patch data to https://my-project.com/api/v1/document-id it gives a 404-error containing: "Cannot PATCH /api/v1/XXX"

I double checked I have the exact document Id and I check if I have proper JSON data. Does somebody know the awnser and please help me?


Solution

  • Your URL just does not match your route. Your route is set to trigger on paths that match /sensor/*:

    app.patch('/sensor/:sensorId', async(req, res) => {
    

    But your URL doesn't even have "sensor" anywhere in its path:

    /api/v1/OaSmA27EGQV3urL6fO9g
    

    You should adjust your path to match what's handled by your route. Perhaps you meant something more like this:

    /api/v1/sensor/OaSmA27EGQV3urL6fO9g