Error in Typescript cloud function: response object is not callable

My cloud function is structured like this:

// const {onSchedule} = require("firebase-functions/v2/scheduler"); // The Cloud Functions for Firebase SDK to set up triggers and logging.
    import * as logger from "firebase-functions/logger";
    const {onRequest} = require('firebase-functions/v2/https');
    
    exports.dailyShiftNotification = onRequest(async (req, res) => {
        const promise = fetch(`http://localhost:3000/api/messaging/dailyShiftNotification`, {
            method: 'POST',
        }).then(res => {
            if (!res.ok) {
              logger.error("There was an error sending messages");
              return res.status(500).send('Error sending messages');
            }
            return res.json();
        }).then(result => {
            return result;
        });
        
        try {
            const result = await promise;
            console.log(result);
            return res.status(200).send('Messages sent!');
        } catch (error) {
            console.error('Error:', error);
            return res.status(500).send('Error sending messages');
        }
    });

I'm encountering an issue where I can't return a response from my function, getting an error stating

this expression is not callable. Type 'Number' has no call signatures

I've attempted to address this by using

import { Request, Response } from 'express';
and setting res: Response, req: Request but it hasn't resolved the problem. Even after installing node-fetch and trying //ts-ignore, the function still times out without sending a response.

Answer №1

The issue you're facing, as pointed out by Phil, is related to how you handle the response shadowing in the then() method. I suggest making some modifications to the overall formatting and functionality of your code, perhaps like this:

try {
 const response = await fetch(... rest of things) // Remove the THEN method
 if(!response.ok) { /* Handle errors as previously done in the then method */ }

 const result = await response.json();
 return res.status(200).send('Messages sent!');
} catch (e) {
 logger.error('Error:', e);
 return res.status(500).send('Error sending messages');
}
  

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

Retrieving data in Next.js

Exploring various techniques to retrieve information from APIs in next.js. Options include getServerSideProps, getStaticPaths, getStaticProps, Incremental Static Regeneration, and client-side rendering. If I need to send requests to the backend when a s ...

Exploring Typescript within React: Creating a property on the current instance

Within my non-TypeScript React component, I previously implemented: componentWillMount() { this.delayedSearch = _.debounce((val) => { this.onQuerySearch(val); }, 1000); } This was for debouncing user input on an input field. The corres ...

Finding the perfect pairing: How to align counters with objects?

public counter = 0; x0: any; x1: any; x2: any; x3: any; x4: any; next(){ this.counter += 1; this.storage.set("Count", this.counter); console.log(this.counter); this.logic(); } logic(){ //automatic counter here var xNum = JSON.parse(JSON.stri ...

What is the best way to include a new attribute in a TypeScript internal object?

I am trying to include a property declaration in the window.history object, but I received a TypeScript error message This is my code: const historyInstance = createHashHistory(); // npm hoistory module window.history.historyInstance = historyInstance; / ...

Having difficulty retrieving data despite providing the correct URL

I am encountering an issue with a fetch function designed to retrieve a JSON web token. Despite verifying the correctness of the URL, the function is not functioning as expected. Below is the front-end function: const handleSubmit = async (e) => { ...

Tips for finalizing a subscriber after a for loop finishes?

When you send a GET request to , you will receive the repositories owned by the user benawad. However, GitHub limits the number of repositories returned to 30. The user benawad currently has 246 repositories as of today (14/08/2021). In order to workarou ...

Ways to invoke a function in an angular component from a separate component located in a different .ts file

File3.ts export class3(){ method1(x,y){ .... } } File4.ts export class4(){ a: string = "abc" b: string ="xyz" //How can I call method1 and pass parameters from file 3? method1(x,y); } I attempted the following in Fi ...

Check if a string contains only special characters and no letters within them using regular expressions

My goal is to validate a string to ensure it contains letters only between two '#' symbols. For example: #one# + #two# - is considered a valid string #one# two - is not valid #one# + half + #two# - is also not a valid string (only #one# and # ...

By utilizing the HTML element ID to retrieve the input value, it is possible that the object in Typescript may be null

When coding a login feature with next.js, I encountered an issue: import type { NextPage } from 'next' import Head from 'next/head' import styles from '../styles/Home.module.css' import Router from 'nex ...

In React Native, you can pass native component properties as props, while also defining custom ones using a TypeScript interface

I am working on a component called AppText where I need to utilize a Props interface and also be able to accept additional props that can be spread using the spread operator. However, I encountered this error: Type '{ children: string; accessible: tru ...

Attempting to capture a previously unhandled error thrown by Axios when utilized in conjunction with React Query (with suspense mode enabled) within a NextJs application

Utilizing NextJS, React query (with axios and suspense mode), I am attempting to handle an intentional 404 error from my API. Although I successfully caught it in my error.js file, the same error still shows up in the console as "uncaught." https://i.stack ...

What's the method for validating the spread operator in Typescript?

Is it possible to prevent this code from compiling? (since it currently does...) const bar: { a: string } = { a: '', ...{b: ''} } ...

Is it possible to utilize Webpack 5's ChunkGroup API with several entries?

I am encountering an error message when attempting to upgrade from Webpack 4 to Webpack 5. The error states: Module.entryModule: Multiple entry modules are not supported by the deprecated API (Use the new ChunkGroup API) I have searched for information o ...

Having trouble fetching information from a JSON file stored in a local directory while using Angular 7

I am currently experiencing an issue with my code. It works fine when fetching data from a URL, but when I try to read from a local JSON file located in the assets folder, it returns an error. searchData() { const url: any = 'https://jsonplaceholde ...

Defining RefObject effectively in TypeScript

Greetings everyone, I am a newcomer to TypeScript and currently attempting to create a type for a RefObject that is of type HTMLAudioElement. However, I have encountered an error message. The error states: Type 'MutableRefObject<HTMLAudioElement> ...

The issue of Next.js public/assets/css not loading is commonly experienced on dynamically generated pages

I am in the process of developing a Next.js application and have decided to start from an HTML template. All the necessary assets have been included in both my Head and _document.js files as shown below: <Head> <meta name="viewport" ...

Transmit data via XMLHttpRequest in smaller portions or through a ReadableStream to minimize memory consumption when handling large datasets

Recently, I've been experimenting with JS's XMLHttpRequest Class for handling file uploads. Initially, I attempted to upload files using the following code: const file = thisFunctionReturnsAFileObject(); const request = new XMLHttpRequest(); req ...

After retrieving data successfully, the NextAuth Credentials function returns a null value

At this moment, I am facing challenges while integrating the next-auth credentials provider into my system. I am using axios (connecting to a different localhost) to validate the credentials (email & password). The Next.js system runs on http://localhost ...

Verifying completed fields before submitting

I'm in the process of designing a web form for users to complete. I want all fields to be filled out before they can click on the submit button. The submit button will remain disabled until the required fields are completed. However, even after settin ...

The function to increase the number of days on a date in Angular is experiencing technical issues

I'm facing an issue where I need to add 12 days to a specific date, but the new date is not coming out as expected. Below is the code snippet: addDays(days: number): any { let startDate = new Date(this.selectedDeliveryDate); let endDate = new ...