【问题标题】:Problem importing variables for types in typescript为打字稿中的类型导入变量的问题
【发布时间】:2020-04-21 21:47:41
【问题描述】:

ESLint 说第一行的 Request 和 Response 未使用,但如果我删除 lint 说 req.headers.authorization 不存在,所以我从函数导入然后 intelissense 工作,但现在说它未使用,怎么能我解决这个?我想说我的函数的这个参数的类型是请求,他们有授权属性。

顺便说一下,我使用的是单例模式,这个函数将被调用,并在云函数中传递 req 和 res 参数

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);
      }
    }
  }
}

【问题讨论】:

    标签: typescript firebase import request google-cloud-functions


    【解决方案1】:

    如果您对 firebase 函数使用 eslint 选项,则需要编辑 functions/.eslintrc.json 文件并添加以下内容:

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

    如果它适合你,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-11
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      • 2020-03-28
      • 1970-01-01
      • 2020-11-22
      相关资源
      最近更新 更多