Having trouble with variable imports in typescript?

I am facing an issue with ESLint where it says that the Request and Response from the first line are unused. However, if I remove them, ESLint then complains that req.headers.authorization does not exist. So, I imported them from functions and the intellisense worked, but now it is saying they are unused. How can I solve this issue? I want to mention that the type of this parameter in my function is a request, and it has the authorization property.

By the way, I am using a singleton pattern and this function will be called passing the req and res parameters inside a cloud function.

import { Request, Response } from 'firebase-functions';
import { auth } from 'firebase-admin';

const authInstance = auth();

export class Authenticator {
  static instance: Authenticator;

  private constructor() {}

  static getInstance() {
    if (Authenticator.instance === null) {
      Authenticator.instance = new Authenticator();
    }
    return Authenticator.instance;
  }

  async authenticate(
    req: Request,
    res: Response,
    log: boolean = false
  ): Promise<void> {
    if (
      !req.headers.authorization ||
      !req.headers.authorization.startsWith('Bearer ')
    ) {
      const response = {
        code: 'auth/missing-argument',
        message: 'Unauthorized Access',
      };

      res.status(401).json(response);
    }

    const token = req.headers.authorization.split('Bearer ')[1];

    try {
      const decodedToken = await authInstance.verifyIdToken(token);

      if (log === true) {
        const user = await authInstance.getUser(decodedToken.uid);
        const logInfo = {
          userId: decodedToken.uid,
          user: user.displayName,
          email: user.email,
          timeGenerated: decodedToken.iat,
          time: new Date().toDateString(),
        };
        console.log(logInfo);
      }
    } catch (error) {
      console.log(error);
      if (error.code === 'auth/argument-error') {
        const response = {
          code: error.code,
          message:
            'Something wrong with your TOKEN, please make sure that you passed the entire string in JWT format',
        };
        res.status(400).json(response);
      } else if (error.code === 'auth/id-token-expired') {
        const response = {
          code: error.code,
          message:
            'Unauthorized access, your token expired. Get a fresh token from your client and try again',
        };
        res.status(401).json(response);
      } else {
        const response = {
          code: error.code,
          message:
            'Internal Error, check your status code and contact support!',
        };
        res.status(500).json(response);
      }
    }
  }
}

Answer №1

In order to utilize the eslint setting for firebase functions, it is necessary to make adjustments to the functions/.eslintrc.json document by including the following:

"parserOptions": {
   "ecmaVersion": 2017
}, 

Kindly inform me if this method proves effective for you.

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

What is the best way to line up a Material icon and header text side by side?

Currently, I am developing a web-page using Angular Material. In my <mat-table>, I decided to include a <mat-icon> next to the header text. However, upon adding the mat-icon, I noticed that the icon and text were not perfectly aligned. The icon ...

Is it possible to implement typed metaprogramming in TypeScript?

I am in the process of developing a function that takes multiple keys and values as input and should return an object with those keys and their corresponding values. The value types should match the ones provided when calling the function. Currently, the ...

Does anyone have experience using the useRef hook in React?

Can someone help me with this recurring issue: "Property 'value' does not exist on type 'never'" interface InputProps { name: string; icon?: ReactElement; placeholder?: string; } const Input = ({ name, icon: Icon, ...rest }: Inpu ...

I'm looking for ways to incorporate TypeScript definition files (.d.ts) into my AngularJS application without using the reference path. Can anyone provide

I'm interested in leveraging .d.ts files for enhanced intellisense while coding in JavaScript with VScode. Take, for instance, a scenario where I have an Angular JS file called comments.js. Within comments.js, I aim to access the type definitions prov ...

What is the correct way to utilize default props in a Typescript-powered React component?

Recently diving into React, I find myself working on a basic child-component. My goal is to establish default props so that if no specific prop is provided when the component is invoked, it automatically resorts to the preset defaults. Here's what I&a ...

Array behavior subjects are used to store multiple values and emit new

When running the code snippet provided, the result displayed is [object object] instead of the expected [{a,b},{b,c}]. // Service bData : BehaviorSubject<any[]> = new BehaviorSubject<any[]>([]); bDataSubject = this.bData.asObservable(); / ...

Ways to turn off specific ngtsc warnings

Ever since updating my Angular app to version 15, I've been noticing some warnings popping up in both the terminal and Chrome DevTools. Is there a way to turn off or disable these warnings? I keep seeing this warning message about the optional chain o ...

Assign the chosen value to the dropdown list if ngModel is present

I currently have a select field implemented in my Angular component: <select class="form-control" [(ngModel)]="myClient.address && myClient.address.state" name="state" (ngModelChange)="getCitiesByState($event)"> <option class="form-con ...

It appears that Typescript mistakenly interprets a class or type as a value, indicating that "'Classname' is being referred to as a value but used as a type here."

I want to pass an Object of a React.Component as "this" to a Child React.Component in the following way: component 1 file: class Comp1 extends React.Component<...,...> { ... render() { return (<Comp2 comp1={this}/> ...

Disabling the submission button in the absence of any input or data

I am currently experiencing an issue where the submit button is active and displays an error message when clicked without any data. I would like to rectify this situation by disabling the submit button until there is valid data input. < ...

Guide on updating a property key in Firebase real-time database with Angular 7

Is it possible to modify the key of a property in my firebase database that I have been struggling with? ...

Add an <input> element to the innerHTML in Angular 2 using injection

My attempt to insert an input HTML tag using Angular 2 has hit a roadblock. Check out my project below: <div [innerHTML]="inputpdf"></div> Looking at the .ts file: export class FaxSendComponent { inputpdf = '<input type="text" ...

<Click here to navigate to page 2> await whenClicked={navigation.navigate("page_2")} />

Issue with assigning a 'string' to a parameter in TypeScript while trying to navigate to another screen in React Native. Can anyone help with this error? This problem occurs when we want to navigate to another screen using TypeScript in React Na ...

Is it possible to get intellisense for Javascript in Visual Studio Code even without using typings?

Is it possible to have intellisense support in Visual Studio Code for a 3rd party library installed via npm, even if there is no typings file available? I have noticed this feature working in IntelliJ/Webstorm, so I believe it might be feasible. However, ...

react-mock-store: Error - the middleware function is not defined

In my current setup, I am utilizing jest for testing with React and Typescript. import configureStore from "redux-mock-store"; import thunk from "redux-thunk"; const mockStore = configureStore([thunk]); it("should handle fetchCha ...

Node.js app hosted on Azure Functions unable to resolve NPM dependencies

I set up a Node (TypeScript) Azure Function application using the VSCode Azure Function extension. While checking the deployment output, I noticed the following log line: Started postDeployTask "npm install (functions)". Despite this, I couldn&a ...

Verify an ajax response by comparing it to the initial request

Is there a way to use ajax and/or jquery to verify that the response received is for the specific request sent? For clarification, I have a search page divided into two parts: the top section for search criteria and the bottom section for matched results. ...

Backend is currently unable to process the request

Whenever a user clicks on a note in my notes page, a request is supposed to be made to the backend to check if the user is the owner of that particular note. However, for some reason, the request is not being processed at all. The frontend is built using ...

nodemon and ts-node not working as expected, failing to automatically recompile

I have been working on creating a REST API using express+ts-node. Following various online tutorials, I managed to set everything up and when I run the app using npm run dev, it works perfectly fine. However, I am facing an issue where it is not automatica ...

Issue with applying value changes in Timeout on Angular Material components

I'm currently experimenting with Angular, and I seem to be struggling with displaying a fake progress bar using the "angular/material/progress-bar" component. (https://material.angular.io/components/progress-bar/) In my "app.component.html", I have m ...