Using TypeScript to encapsulate a Firebase promise

I am in the process of refactoring two functions to make them more concise and efficient:

  async registerUser(newUser: User) {
    await this.db.auth
      .createUserWithEmailAndPassword(newUser.email, newUser.pass)
      .then(data => {
        this.db.auth.currentUser.getIdToken().then(reply => {
          this.http
            .post('http://localhost:3000/login', { token: reply })
            .toPromise()
            .then(response => {
              if (response['valid'] === 'true') {
                localStorage.setItem('user', JSON.stringify(reply));
                this.router.navigate(['dash']);
              }
            });
        });
      })
      .catch(err => {
        console.log('registration failed: ' + err.message);
      });
  }

  async signIn(newUser: User) {
    await this.db.auth
      .signInWithEmailAndPassword(newUser.email, newUser.pass)
      .then(data => {
        this.db.auth.currentUser.getIdToken().then(reply => {
          this.http
            .post('http://localhost:3000/login', { token: reply })
            .toPromise()
            .then(response => {
              if (response['valid'] === 'true') {
                localStorage.setItem('user', JSON.stringify(reply));
                this.router.navigate(['dash']);
              }
            });
        });
      })
      .catch(err => {
        console.log('signIn failed: ' + err.message);
      });
  }

I aim to streamline these functions by creating a separate method that encapsulates both functionalities for reusability. I'm currently working on this new method and need advice on how to merge these functions effectively since I'm not well-versed in promises. What should be included in the resolve() section of these two promises to ensure my new method operates correctly?

  async useAuth(user: User, action: string) {
    if (action === 'signIn') {
      return await new Promise((resolve, reject) => {
        this.db.auth.signInWithEmailAndPassword(user.email, user.pass);
      });
    } else if (action === 'register') {
      return await new Promise((resolve, reject) => {
        this.db.auth.createUserWithEmailAndPassword(user.email, user.pass);
      });
    }

Answer №1

Both methods are already structured to return a Promise<UserCredential>. Therefore, there is no necessity to encapsulate them in another Promise.

async useAuth(user: User, action: string) 
{
    let result; // data type defined as UserCredential

    if (action === 'signIn') 
    {
      result = await this.db.auth.signInWithEmailAndPassword(user.email, user.pass);
    } 
    else if (action === 'register') 
    {
      result = await this.db.auth.createUserWithEmailAndPassword(user.email, user.pass);
    }
    else
    {
        throw "unknown action " + action;
    }

    return result;
}

Answer №2

NineBerry's response was spot on, so I decided to go ahead and utilize the following code:

  async useAuth(user: User, action: string) {
    if (action === 'signIn')
      return await this.db.auth.signInWithEmailAndPassword(user.email, user.pass);
    else if (action === 'register')
      return await this.db.auth.createUserWithEmailAndPassword(user.email, user.pass);
  }

This method worked perfectly for me!

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

Obtain the ID of the textarea element when it is clicked

Is there a way to retrieve the id of a textarea that was focused when another element is clicked? I have tried using $(':input:focus').attr('id'), but the textarea quickly loses focus after the click, making it impossible to obtain the ...

Complete guide on modifying CSS with Selenium (Includes downloadable Source Code)

I am looking to switch the css styling of a website using Python and Selenium. My initial step was to retrieve the current CSS value. Now, I aim to alter this css value. The Python code output is as follows: 0px 0px 0px 270px How can I change it from 0 ...

Enhance Website Speed by Storing PHP Array on Server?

Is there a way to optimize the page load time by storing a PHP array on the server instead of parsing it from a CSV file every time the page is reloaded? The CSV file only updates once an hour, so constantly processing 100k+ elements for each user seems un ...

Determine the type of class or instance from the constructor function

How can you determine the class type or instance type using a constructor function? EDIT: Given only the prototype, how can you identify the class type? Refer to the example with decorators. Class User {} // It's really disappointing that I have to ...

Using React/Vite with createBrowserRouter in a subdirectory will not function properly unless a trailing slash is included

My current project involves using React/Vite/Express to create an app that is hosted within a subdirectory. For example, let's say the app is hosted at: https://example.com/my/app/ In my Vite configuration, I have specified base as ./ export default ...

My ability to click() a button is working fine, but I am unable to view the innerHTML/length. What could be the issue? (NodeJS

Initially, my goal is to verify the existence of the modal and then proceed by clicking "continue". However, I am facing an issue where I can click continue without successfully determining if the modal exists in the first place. This occurs because when I ...

Exploring the contents of an array

I am attempting to use weatherapi for obtaining forecast data and my goal is to access the hourly forecast in order to display the time and condition text for each hour object within a react component. However, I have been struggling to figure out how to r ...

Change a `as const` object into a type that is more broadly applicable

Creating a Generic Type from an Immutable Object Using "as const" Consider the following immutable object: const usersDefaultValues = { firstName: '', isGuest: false } as const We aim to generate the following type/interface based on this o ...

Creating a multi-step form in Rails without using the Wizard gem allows for more

My Rails 3.2.14 app gathers call data and the new/edit action form is quite lengthy on a single page. I am interested in implementing a multistep form using JS/client side processing to navigate between steps. While considering the Wicked Gem for multi-ste ...

Divide a collection of objects into groups based on 2-hour time spans

I have an array of objects that I need to split into chunks of 2 hours each, starting on the hour (e.g. 10.00 - 12.00, 12.00 - 14.00, etc). Here is my current solution, but I feel like it may not be the most efficient: Please consider the day variable, w ...

Exploring the power of jQuery's deferred method and utilizing the ajax beforeSend

Using the deferred object in $.ajax allows for: Replacing the success-callback with the deferred-method done() Replacing the error-callback with the deferred-method fail() And replacing the complete-callback with always() When using: var jqxhr = $.ajax ...

Identifying when a user is idle on the browser

My current project involves developing an internal business application that requires tracking the time spent by users on a specific task. While users may access additional pages or documents for information while filling out a form, accurately monitoring ...

What could be the reason for the discrepancy between my get_token() function and the value obtained from request.META.get("CSRF_COOKIE")?

Can anyone shed light on why I'm facing this particular issue? I am currently exploring the integration of Angular 17 as a Frontend with Django as a Backend. While validating a form, I encountered an issue where the token obtained from Django does no ...

It appears that the ngOnInit function is being activated prior to receiving any data through the Input()

For a personal challenge, I am working on creating a website that showcases a list of League Of Legends champions. Users can click on the champion icons to access more details. However, I am facing an issue where the champion details (specifically images) ...

Choose from a dropdown menu to either activate or deactivate a user account

I'm new to php and I need help getting this code to function properly delete.php <?php include_once 'dbconfig.php'; if($_POST['del_id']) { $id = $_POST['del_id']; $stmt=$db_con->prepare("UPDATE tbluse ...

Tips for preventing the ng-click event of a table row from being triggered when you specifically want to activate the ng-click event of a checkbox

So, I've got this situation where when clicking on a Table Row, it opens a modal thanks to ng-click. <tr ng-repeat="cpPortfolioItem in cpPortfolioTitles" ng-click="viewIndividualDetailsByTitle(cpPortfolioItem)"> But now, there&apos ...

Retrieve the content from paragraph elements excluding any text enclosed within span tags using the Document.querySelector method

Exploring the following element structure: <p> <span class="ts-aria-only"> Departure </span> RUH <span class="ts-aria-only">&nbsp;Riyadh</span> </p> In an attempt to extract the text RUH, it has been disc ...

Retrieve the text content of the <ul> <li> elements following a click on them

Currently, I am able to pass the .innerTXT of any item I click in my list of items. However, when I click on a nested item like statistics -> tests, I want to display the entire path and not just 'tests'. Can someone assist me in resolving thi ...

Resolving Cross-Origin Resource Sharing issues with AWS SDK (Lightsail API) and Vue.js

I'm currently working on a small vue.js application that utilizes aws-sdk to retrieve information about Lightsail instances. However, I keep encountering this issue. :8081/#/:1 Access to XMLHttpRequest at 'https://lightsail.us-west-2.amazonaws.c ...

In React/Next.js, it seems that pressing the useState button twice is required in order for an event to trigger

When working with react/nextjs, I encountered an issue with a click event where I'm trying to use setState to modify an array. Strangely, the modification only takes effect after two clicks of the button. Here is the initial state array: const [array ...