Some code paths fail to return a value in Google Cloud Function callable functions

When utilizing async functions in my cloud function and including a 'return' statement in each potential output, I am still encountering the error message Not all code paths return a value

I attempted removing my database calls and only leaving the 'return {data:{...}};' to resolve the error.

Furthermore, I tried enclosing everything within a 'try' 'catch' block.

I currently have two blocks get().then()...catch().. which seems like it should work as expected.

export const getUsersInHere = functions.https.onCall((data, context) => 
{
    if(!context || !context.auth || !context.auth.uid)
    {
        return {data:{message:"Please login again...", success:false}};
    }
    else if(data)
    {
        const my_uid = context.auth.uid;
        db.collection(`InHere/${my_uid}`).get().then(snapshot => 
        {
           return {data:{}, success:true};
        }).catch(e =>
        {
            return {data:{message:"No last message yet...", success:false}};
        });
    }
    else 
    {
        return {data:{message:"no body sent", success:false}};
    }
});

Although I expect to deploy my cloud function with firebase deploy, I am receiving deployment errors:


src/index.ts:83:62 - error TS7030: Not all code paths return a value.

83 export const getUsersInHere = functions.https.onCall((data, context) =>

Note I discovered that 'firestore deploy' works when I added 'async' into the callable signature. However, the warning/error persists in Microsoft Visual Studio Code (Not all code paths return a value.ts(7030))

export const getUsersInThisChatRoom = functions.https.onCall(async (data, context) =>

Answer №1

When working with callables, you have the option to either directly return the object intended for serialization and transmission to the client, or you can return a promise that will resolve with the object to be sent. In your else if block, all you need to do is return the promise:

// make sure to add 'return' on the next line
return db.collection(`InHere/${my_uid}`).get().then(snapshot => 
{
    return {data:{}, success:true};
}).catch(e =>
{
    return {data:{message:"No last message yet...", success:false}};
});

This will result in the promise being returned, which will resolve with the value from either the then or catch callback.

Using async/await is not mandatory, but if you choose to do so, you should replace the then and catch blocks with the appropriate async/await syntax. The code structure will be quite different in this case.

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

NextRouter does not have a property called "refresh"

Here is the provided code snippet: "use client"; import { useRouter } from "next/router"; import { useState } from "react"; export default function CreatePrompt() { const [title, setTitle] = useState(""); const ...

Adal TypeScript Document

Recently, I've been experimenting with the TypeScript version of adal.js. As part of my setup process, I'm referring to this link to install adal.ts. However, after executing the command: npm install adal-typescript --save a new "node_modules" ...

What is the method for importing the "numeric" library version "^1.2.6" into an Angular project?

I recently added the package "numeric": "^1.2.6" to my project. In addition, I included the types: "@types/numeric": "^1.2.1" When attempting to import this into my Angular application: import * as numeric from &ap ...

Displaying a collection of objects in HTML by iterating through an array

As someone new to coding, I am eager to tackle the following challenge: I have designed 3 distinct classes. The primary class is the Place class, followed by a restaurant class and an events class. Both the restaurant class and events class inherit core p ...

I'm looking for a way to modify my standard function so that it can receive warnings

Below is my function called defc export function defc<T extends Record<string,any> >(f:(a:T)=>void){ return function(a:T){ return f(a) } } The purpose of this function is to ensure the correct return type of func ...

The inference of optional generic types is not occurring

I need help addressing a type error in my TypeScript wrapper for handling NextJS API requests. Specifically, I am facing an issue when trying to pass a single type for one of the generic types in the function. To illustrate this error, I have created a si ...

Encountered an issue while trying to read the property 'temp' of undefined within an HTML document

Can someone help me with this issue? I'm facing an error with the JSON data retrieved from an API: ERROR in src/app/weather/weather.component.ts(39,30): error TS2339: Property 'main' does not exist on type 'Iweather[]' Here is ...

Utilizing Google Cloud Functions with NPM

I'm currently attempting to utilize a Google Cloud function to convert a 3D model into an image. However, my function is failing to deploy. I have made attempts using both `ypm install` and `npm install` in the package file. Deployment error: Build f ...

Expanding unfamiliar categories

Currently, I am working with Gutenberg blocks in a headless manner. Each Gutenberg block is defined by the following structure: type Block = { name: string; className?: string; key?: string | number; clientId: string; innerBlocks: Block ...

styles.css is generating an ERROR message, indicating that it is unable to read properties of null when trying to access the 'classList'

Hey there, I've been working on adding a background color change to my navbar when the scrollY exceeds 30px, and it's functioning properly. However, I'm encountering an error in the console which states that the new classList cannot be added ...

How come my uploaded Excel Javascript add-on opens in an external browser instead of the task pane?

Note: It has come to my attention that I must save the taskpane.html file on my local drive before it opens in an external browser. This detail slipped my notice last week. I am currently developing a Javascript, or rather Typescript, API add-in for Excel ...

How can the outcome of the useQuery be integrated with the defaultValues in the useForm function?

Hey there amazing developers! I need some help with a query. When using useQuery, the imported values can be undefined which makes it tricky to apply them as defaultValues. Does anyone have a good solution for this? Maybe something like this would work. ...

Transform a specialized function into a generic function with static typing

First off, I have a network of routes structured like this: interface RouteObject { id: string; path: string; children?: RouteObject[]; } const routeObjects: RouteObject[] = [ { id: 'root', path: '/', children: [ ...

The benefits of a modular design in a React and TypeScript library

Following a tutorial on creating a library with React, Typescript, and rollup, I successfully managed to get everything working. However, as my project grows with additional features, I'm looking to have modular exports similar to what is seen in redu ...

Exploring TypeScript reflections within a specific namespace

(Building upon previous discussions about dynamically loading a TypeScript class) If I am currently within a namespace, is there a method to reference classes within the namespace in order to utilize 'reflection' to invoke their constructors? n ...

How can a nullable variable be converted into an interface in TypeScript?

Encountered an issue while working on a vue3.x typescript project. The vue file structure is as follows: <template> <Comp ref="compRef" /> </template> <script lang="ts" setup> import {ref} from "vue& ...

Utilizing a file type validator in SurveyJs: A guide

Is there a way to validate uploaded documents on a form using surveyJs and typescript with a custom validator before the file is uploaded? The current issue I am facing is that the validator gets called after the upload, resulting in an API error for unsup ...

What could be the reason behind Typescript's unexpected behavior when handling the severity prop in Material UI Alerts?

Trying to integrate Typescript into my react project and encountering a particular error: Type 'string' is not assignable to type 'Color | undefined'. The issue arises when I have the following setup... const foo = {stuff:"succes ...

What is the best way to verify if the ReactDOM.render method has been invoked with a React component as an argument

Here's the code snippet: index.tsx: import React, { Component } from 'react'; import ReactDOM from 'react-dom'; export function Loading(props) { return <div {...props}>loading...</div>; } export class MyComponent e ...

Custom Tokens for Firestore

I am attempting to utilize a custom authentication token with firestore. My approach involves using nodejs to create the token with the following script. const admin = require('firebase-admin'); const serviceAccount = require('./ServiceAcco ...