Despite having everything in order, Firebase Cloud is returning null values

I have created a Cloud Function using TypeScript, with async calls included.

exports.verifyOtp = functions.https.onCall((data,context)=>{
  phoneNumber = data.phoneNumber;
  otp = data.otp;
  let email:string = data.email;
  let password:string = data.password;
  let displayName:string= data.displayName;

  authFunction.validateOtp(phoneNumber, otp,(otpErr,otpValue) => {
    if(otpErr){
      console.error(otpErr);
      return {otpErr};
    }else{ 
    return authFunction.createUser(email,false,phoneNumber,password,displayName,false,(err,value) => {
        if(err) 
        {
          console.error(err);
          return Promise.reject(err);
        }
        else{
          console.log(value); 
          return Promise.resolve(value);
        }                  
          });
    } 
});
  });

Provided below is the code for authFunction.validateOtp

 validateOtp(phoneNumber:string, otp:string,callback:Function){
  let otpValidationApi:string = "https://<api>/verifyRequestOTP.php?authkey="+this.authKey+"&mobile="+phoneNumber+
  "&otp="+otp;
  https.get(otpValidationApi, (resp) => {
    let data = '';
    resp.on('data', (chunk) => {
      data += chunk;
      });
      resp.on('end', () => {
        let result = JSON.parse(data);
        var y=result.type;
        callback(null,y);
      });
  }).on("error",(err)=>{
    console.log("Error: "+err.message);
  });
 }

I am attempting to receive the output/return value on my Android app using:

private static FirebaseFunctions mFunctions = FirebaseFunctions.getInstance();
mFunctions.getHttpsCallable(nameOfFunction).call(data)
           .continueWith(new Continuation<HttpsCallableResult, String>() {
               @Override
               public String then(@NonNull Task<HttpsCallableResult> task) throws Exception {
                   String result2 = (String) task.getResult().getData();
                   return result2;
               }
           });

Nevertheless, the variable result2 in the Android code consistently returns null, despite the Cloud Function working correctly as anticipated.

Could you please assist me in identifying my mistake?

Answer №1

To ensure continuity in your Cloud Function with the HTTP API calls made by otpValidation, it is essential to have it return a promise and propagate these promises upwards through the function. Currently, without any return statement at the top level code, there's a risk of Cloud Functions shutting down after the final } is executed, potentially interrupting ongoing processes like the HTTP call or the createUser function.

The initial step involves modifying otpValidation to return a promise, maintaining its resolve/reject state:

 otpValidation(phoneNumber:string, otp:string): Promise<Any> {
   let otpValidationApi:string = "https://<api>/verifyRequestOTP.php?authkey="+this.authKey+"&mobile="+phoneNumber+
  "&otp="+otp;
   return new Promise(function(resolve, reject) {
     https.get(otpValidationApi, (resp) => {
       let data = '';
       resp.on('data', (chunk) => {
         data += chunk;
       });
       resp.on('end', () => {
         let result = JSON.parse(data);
         var y=result.type;
         resolve(y);
       });
     }).on("error",(err)=>{
       console.log("Error: "+err.message);
       reject(err);
     });
   });
 }

Once this adjustment is complete, you can efficiently handle the returned value from otpValidation by chaining multiple then() functions together:

exports.validateOtp = functions.https.onCall((data,context)=>{
  phoneNumber = data.phoneNumber;
  otp = data.otp;
  let email:string = data.email;
  let password:string = data.password;
  let displayName:string= data.displayName;

  return authFunction.otpValidation(phoneNumber,otp).then(function(optValue) {
    return authFunction.createUser(email,false,phoneNumber,password,displayName,false,(err,value) => {
        if(err) 
        {
          console.error(err);
          return Promise.reject(err);
        }
        else{
          console.log(value); 
          return Promise.resolve(value);
        }                  
      });
    } 
});

Further analysis of your code may prompt a similar change for authFunction.createUser to also return a promise. If necessary, employ a comparable approach as demonstrated above for auth.otpValidation.

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

steps for exporting an array generated within a promise

Currently, I am following a project tutorial from Mozilla Developer about building a local library. This tutorial involves learning how to work with Node.js, Express, Mongoose, and MongoDB. However, I have decided to swap out Mongoose and MongoDB for Fires ...

Managing the display of numerous ngFor components

If you're interested in learning more about the features I will include, here's a brief overview. I plan to have a project section with cards displayed for each project, all populated from a JSON file. When users click on a card on the website, a ...

The Typescript object property is deemed as 'undefined' even though it has not been defined

I'm relatively new to working with Typescript and I'm facing a challenge that seems quite silly: When I fetch an 'agent' object from a service. this.agentsController.getAgent(matricule).subscribe({ next: agent => { con ...

Develop a query builder in TypeORM where the source table (FROM) is a join table

I am currently working on translating this SQL query into TypeORM using the QueryBuilder: SELECT user_places.user_id, place.mpath FROM public.user_root_places_place user_places INNER JOIN public.place place ON place.id = user_places.place_id The ...

The type '0 | Element | undefined' cannot be assigned to the type 'Element'

I encountered the following error: An error occurred when trying to render: Type '0 | Element | undefined' is not assignable to type 'Element'. Type 'undefined' is not assignable to type 'ReactElement<any, any>&apo ...

What is the process for obtaining a list of all branches within a repository?

For instance, imagine I have five different branches within the current repository: master, branch1, branch2, branch3, and branch4. How can we use TypeScript for a Probot build to access these branch names? My Attempt: import { Application } from 'p ...

Unexpected behavior observed in React TypeScript when using the useRef hook. TypeScript does not generate errors for incorrect ref types

I am encountering an issue with a simple react component. Even though TypeScript should throw an error, it does not when I use HTMLInputElement as the type for useRef hook and assign it to a div element. import { useRef } from "react" export de ...

Page displaying before the home screen of an application with blank white background

I created an Ionic2 app and successfully launched it on Google Play store. Everything is running smoothly except for one issue - a white page that appears before the app's home view. Can anyone provide guidance on how to resolve this problem? For fur ...

What could be the reason why the keypress event doesn't seem to be functioning properly on

Currently, I am utilizing Angular and the Ionic framework. Here is a snippet of the HTML code that I have written: <div><ion-input type="text" id="phoneNumber" [(ngModel)]="phoneNumber" (keypress)="phoneNumericCh ...

Button in Angular gets stuck when a touchscreen is long pressed

In my Angular2 application, I am facing an issue with a button when running on a Windows 10 touchscreen PC in Chrome. Normally, the button works fine and executes the click function. However, if the button is held for 1-2 seconds, it gets stuck and fails t ...

In Angular ngrx, when using parameters 'action' and 'action', it is important to note that they are not compatible with each other. Additionally, it is crucial that the property 'payload' is not

I have recently started working with Angular and I am using ngrx to manage the state in my application. However, when I try to compile the code, I encounter an error that says 'Types of parameters 'action' and 'action' are incompat ...

In Certain Circumstances, Redirects Are Applicable

I have set up Private Routing in my project. With this configuration, if there is a token stored in the localStorage, users can access private routes. If not, they will be redirected to the /404 page: const token = localStorage.getItem('token'); ...

`I'm having trouble with ion-select functionality`

Having an issue with implementing an ion-select in Ionic 3. Despite following the Ionic documentation, I am unable to identify my mistake. My code is as follows: hosts: any[] = [ '*MANAGER*', 'Alberto Bellesini', 'Alessan ...

When I try to install dependencies with Hardhat, the "Typechain" folder does not appear in the directory

After installing all the dependencies, I noticed that the "typechain" folder was missing in the typescript hardhat. How can I retrieve it? Try running npm init Then, do npm install --save-dev hardhat Next, run npx hardaht You should see an option to se ...

Mastering the utilization of bootstrap-select in TypeScript while ensuring "noImplicitAny" is set to true can be quite the challenge, especially when confronted with the issue of bootstrap-select/index

Hello, I am currently exploring Typescript and attempting to incorporate bootstrap-select into a project that requires "noImplicitAny": true. However, I am encountering an issue while trying to import BootstrapSelect from @types/bootstrap-select. The erro ...

Total the values of several items within the array

Here is the data I currently have: const arrayA = [{name:'a', amount: 10, serviceId: '23a', test:'SUCCESS'}, {name:'a', amount: 9, test:'FAIL'}, {name:'b', amount: ...

Using Angular to make an HTTP POST request to fetch data

My trusty .net backpack has been working flawlessly. However, I encountered an issue when trying to connect it with the Angular front end. All backend requests are post requests and require passing an ApiKey in the body of each request. Interestingly, ever ...

"Error: Unfinished string literal encountered" occurring in a TypeScript app.component.ts file in NativeScript

I've been trying to learn NativeScript through a tutorial, but I keep encountering errors. Here is an excerpt from my app.component.ts file: import { Component } from '@angular/core'; @Component ({ selector: 'my-app', temp ...

Tips for effectively handling the data received from a webservice when logging into a system

My web service provides me with permissions from my user. The permissions are stored as an array in JSON format. I need to find a way to access and display this data in another function. {"StatusCode":0,"StatusMessage":"Authenticated Successfully", "Token ...

Exploring the capabilities of combining Typescript with withStyles in the latest @material-ui/core framework

I have been working on updating some old Typescript code that was using material-ui@next to now use @material-ui/core. Typescript Version: 2.8.3 @material-ui/core: 1.1.0 I created a simple component that accepts a single prop, but when I try to use it, t ...