首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为typescript中的类型导入变量时出现问题

为typescript中的类型导入变量时出现问题
EN

Stack Overflow用户
提问于 2020-04-22 05:47:41
回答 1查看 28关注 0票数 0

ESLint说来自第一行的请求和响应是未使用的,但是如果我删除了lint表示req.headers.authorization不存在,所以我从函数中导入了它,并且intelissense工作了,但是现在说它是未使用的,我该如何解决这个问题呢?我想说的是,我的函数的this参数的类型是一个请求,并且它们具有授权属性。

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

代码语言:javascript
复制
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);
      }
    }
  }
}
EN

回答 1

Stack Overflow用户

发布于 2020-04-22 18:10:45

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

代码语言:javascript
复制
"parserOptions": {
   "ecmaVersion": 2017
}, 

如果对你有效,请让我知道。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61353849

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档