Processing HTTP requests routed from Firebase Hosting to Cloud Functions

I'm currently working on integrating data patching with my Firestore database using http. My goal is to achieve this without relying on an external server, by utilizing Firebase Hosting and Functions.

Firstly, I set up my Firebase project and imported express, body-parser, and firebase-functions-helper into the functions.

Next, I configured my firebase.json file to link the source to the specific function:

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

Secondly, I wrote TypeScript code to upload data from the HTTP patch request to the Firestore database. This script is stored in functions/src/index.ts file.

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');
    }
})

However, when attempting to use Postman to patch data at , I encounter a 404-error stating: "Cannot PATCH /api/v1/XXX"

I have verified that I am providing the correct document Id and ensuring proper JSON data. Can anyone provide assistance or insights on this issue?

Answer №1

It appears that the URL you are using does not correspond to the specified route. The route is designed to respond to paths containing /sensor/*:

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

However, the URL you provided does not include the word "sensor" in its path:

/api/v1/OaSmA27EGQV3urL6fO9g

To ensure compatibility with your route, consider adjusting your path like so:

/api/v1/sensor/OaSmA27EGQV3urL6fO9g

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging generics within TypeScript

I have developed a class in TypeScript that uses generics. export class ModelTransformer { static hostelTransformer: HostelTransformer; static fromAtoB(instance: T): U { if (instance instanceof HostelType) { return ModelTrans ...

The Ngrx action fails to finish despite encountering an error during execution

An Issue with Action Completion Post-Error Within my application, I have implemented an action for deleting a user. Prior to deletion, the user is prompted on screen with a Dialog to input the administrator password. If the correct password is provided, t ...

Having trouble accessing the file in the browser

I have successfully implemented code for file uploads :: var express=require('express'); var mysql=require('mysql'); var fs=require('fs'); var http=require('http'); var crypto=require('crypto'); var app=e ...

Compilation issues encountered while running TypeScript in Dockerfile

I am encountering an issue with my Dockerfile during the TypeScript compilation step. Below is the snippet of code where it fails: FROM node:12 WORKDIR /usr/src/app # SETUP COPY package.json . COPY tsconfig.json . COPY src . RUN npm install -g yarn@^1. ...

What is the most effective way to handle DOM events in Angular 8?

Looking to listen for the 'storage' event from the window in Angular 8. What is the recommended approach to achieving this in Angular? window.addEventListener('storage', () => { }); One method involves using Renderer2, but are ther ...

The dependency that was installed in the node_modules directory is now showing as missing the

I have encountered an issue with 2 TS packages. The first package, project-1, is installed as a dependency in the second package, project-2. While I am able to import and access all type definitions of project-1 in project-2, the dependencies (node_modules ...

Guide to aligning a component in the middle of the screen - Angular

As I delve into my project using Angular, I find myself unsure about the best approach to rendering a component within the main component. Check out the repository: https://github.com/jrsbaum/crud-angular See the demo here: Login credentials: Email: [e ...

Node.js and Express: Delivering Seamless Video Streaming via HTTP 206 Partial Content

Having a binary file like an mp4 video in a MarkLogic database, I am utilizing the Node.js API of the database to stream this document in segments. The structure is as follows: html document <video controls="controls" width="600"> <source src= ...

Utilizing markModified inside a mongoose class that does not inherit from mongoose.Document

In my Typescript code using mongoose ODM, I am implementing a simple queue structure. The challenge arises when directly mutating an array instead of assigning a new value to it because mongoose doesn't automatically recognize the change. To resolve t ...

I am unable to utilize the outcome of a custom hook within a function or within an effect hook

I've developed a unique custom hook that retrieves a list of individuals File: persons.hooks.ts import {useEffect, useState} from "react"; import Person from "../../models/person/Person"; const usePersons = () => { const ...

What is the best practice for storing angular partials - should they be kept in the public/ directory, views/ directory, or another location altogether

Currently developing a Pinterest-inspired platform to enhance my understanding of node.js. I'm contemplating where to store my partial views, such as those for rendering pins - should they be placed in the public/partials folder or within the views/ d ...

An issue encountered while implementing a post method with fetch and Express

I'm just starting out, so I hope my question isn't too basic. My goal is to send a longitude and latitude from client-side JavaScript to a Node.js server using Fetch and Express.js. Below is the HTML code snippet: <!DOCTYPE html> <html ...

When I incorporate Express into my React project, I encounter an error stating that the prototype

After attempting to set up a basic React project that connects to a MySQL database, I encountered an error. When requiring 'express' and rebuilding the project, I received the following message when trying to open it in the browser: "Uncaught Ty ...

Find and return a specific record from MongoDB if it matches the exact value

model.js import mongoose from 'mongoose'; const { Schema, Types } = mongoose; const participants = { user_id: Types.ObjectId(), isAdmin: Boolean } const groupSchema = new Schema({ id: Types.ObjectId(), // String is shorthand for {type: St ...

Ways to determine if a specified character sequence is present in an Enumerator?

One of my coding dilemmas involves an enum that looks like this: export enum someEnum { None = <any>'', value1 = <any>'value1', value2 = <any>'value2', value3 = <any>'value3' ...

Why is my input field value not getting set by Angular's patchValue function

I've been attempting to populate an input field using the form group with patchValue(), but for some reason, the input remains empty. Here's a snippet of my code... component.html <form [formGroup]="createStoreForm" (ngSubmit)="createStor ...

An EJS array nested within an object

Below is the nodejs(express) code snippet: response.redirect('file', {test: [{name:'sarah', arr:[1,2,3]}, {name:'beck', arr:[2,3,4]}]} In my ejs file, I am trying to access the 'arr' for each name in the arra ...

Enhancing a UMD module definition with TypeScript 2: A step-by-step guide

Currently, I am in the process of creating TypeScript definition files for two libraries that are meant to be used with the new @types approach. Both libraries adhere to the UMD pattern, allowing them to be consumed either as modules or by referencing them ...

Angular 5: Issues with retrieving response using HttpClient's get request

Alright, so typically I work with Angular 1.*, but I decided to dive into Angular 5 and man, it's been a bit of a challenge. It feels unnecessarily complex, but oh well... So I'm trying to make an HTTP call, and I have this node API that is retu ...

Merge attributes from objects within an array

I am seeking assistance with a basic task in TypeScript as a newcomer to the language. My challenge involves manipulating an array of objects like this: // Sample data let boop = [ {a: 5, b: 10}, {a: 7, c: 8}, {a: 6, b: 7, c: 9} ]; My objectiv ...