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

Sending the HTML input value to a Knockout view

Can someone assist me with a dilemma I'm facing? Within CRM on Demand, I have a view that needs to extract values from CRM input fields to conduct a search against CRM via web service. If duplicate records are found, the view should display them. Be ...

What is the best way to extract a nested array of objects and merge them into the main array?

I've been working on a feature that involves grouping and ungrouping items. A few days ago, I posted this question: How can I group specific items within an object in the same array and delete them from the core array? where some helpful individuals ...

Angular Form: displaying multiple hashtags within an input field

Utilizing Angular CLI and Angular Material, I have created a form to input new hashtags. I am facing difficulty in displaying previously added hashtags in the input field. Below is the code I have written: form.component.html <form [formGroup]="crea ...

Converting JSON objects into TypeScript classes: A step-by-step guide

My challenge lies in converting Django responses into Angular's User array. This conversion is necessary due to variations in variable names (first_name vs firstName) and implementing specific logic within the Angular User constructor. In simple term ...

What steps can I take to ensure TypeScript compiler approves of variance in calling generic handlers, such as those used in expressJS middleware?

disclaimer: I am a bit uncertain about variance in general... Here is the scenario I am facing: // index.ts import express from 'express'; import {Request, Response} from 'express'; const app = express(); app.use(handler); interface ...

Navigating between different views and pages within Angular FullCalendar can be achieved by utilizing the appropriate handlers for next,

After successfully integrating Angular fullCalendar into my Angular project and displaying events that I can click on, I found myself stuck when trying to handle clicks on the next and prev buttons as well as view changes. Unfortunately, the official docum ...

Error: Conversion of "2018-01-01-12:12:12:123456" to a date is not possible for the 'DatePipe' filter

<td>{{suite.testSuiteAttributes && suite.testSuiteAttributes.modifiedTimestamp | date: 'yyyy-MM-dd' }} </td> I am trying to display the date in the "05-Feb-2018 11:00:00 PM CST" CST format, but I keep getting an ...

Flashing issues when utilizing the Jquery ui slider within an Angular 2 component

I recently incorporated a jquery-ui slider plugin into an angular 2 component and it's been working well overall, but I have encountered an annoying issue. Whenever the slider is used, there is a flickering effect on the screen. Interestingly, when I ...

Guide to sending a HTTP POST request with parameters in typescript

I need assistance sending a POST request using parameters in the following format: http://127.0.0.1:9000/api?command={"command":"value","params":{"key":"value","key":"value","key":"value","key":value,}} I attempted to do this but encountered an issue: l ...

Exporting a constant as a default in TypeScript

We are currently developing a TypeScript library that will be published to our private NPM environment. The goal is for this library to be usable in TS, ES6, or ES5 projects. Let's call the npm package foo. The main file of the library serves as an e ...

Can a custom structural directive be utilized under certain circumstances within Angular?

Presently, I am working with a unique custom structural directive that looks like this: <div *someDirective>. This specific directive displays a div only when certain conditions are met. However, I am faced with the challenge of implementing condit ...

"Utilizing Typescript's keyof operator on its own

I'm grappling with the challenge of creating a type that can utilize the typeof its own keys, but I'm hitting a roadblock. Below is a simplified version of what I'm attempting to achieve: type SpecialType = Record<string, (getter: <K e ...

The Typescript SyntaxError occurs when attempting to use an import statement outside of a module, typically within a separate file that contains

I am currently developing a Minecraft bot using the mineflayer library from GitHub. To make my code more organized and reusable, I decided to switch to TypeScript and ensure readability in my project structure (see image here: https://i.stack.imgur.com/znX ...

Tips for detecting the end of a scroll view in a list view

I've encountered an issue with my scrollView that allows for infinite scrolling until the banner or container disappears. What I'm aiming for is to restrict scrolling once you reach the last section, like number 3, to prevent the name part from m ...

What is the best way to transform a JavaScript object into an array?

Here is the information I have: {product_quantity: {quantity: 13, code: "AAA", warehouse: "1000",}} The product_quantity field is part of a JSON object in a MongoDB database. I am looking to convert it into this format: {"produ ...

Make sure to always keep all stars contained within a div element

How can I keep five stars inside a div even when the screen size is small? I have created a div with an image and I want to place five stars within that div. However, as I reduce the size of the screen, the stars come out of the box. Is there a way to en ...

The typings for object properties in Typescript

I recently encountered a function call in my code: var myVar = myFunction({ property: 'prop', functionProperty() { console.log(this.property); }, functionProperty2() { this.functionProperty(); } }); I' ...

Exploring the various form types supported by 'react-hook-form'

I utilized react hooks form to create this form: import React from "react"; import ReactDOM from "react-dom"; import { useForm, SubmitHandler } from "react-hook-form"; import "./styles.css"; function App() { type ...

How to calculate the sum of all values in a FormArray in Angular

I am trying to retrieve the input values from each row and then calculate the sum of these rows. Here is my HTML code: <ng-container formArrayName="cap_values"> <tbody *ngFor="let item of capValues.controls; let i=index" [formGroupName]="i"& ...

What is the method for dynamically assigning a name to ngModel?

I have the following code snippet: vmarray[]={'Code','Name','Place','City'} export class VMDetail { lstrData1:string; lstrData2:string; lstrData3:string; lstrData4:string; lstrData5:string; ...