【问题标题】:instantiating object returns an error after export default in typescript在打字稿中导出默认值后实例化对象返回错误
【发布时间】:2019-08-07 09:33:03
【问题描述】:

我有一个模型目录:

models/
-- index.ts
-- basemodel.ts
-- auth.ts
-- validator.ts

在所有模型中,只有 auth.ts 继承了 basemodel

models/index.ts

export { default as BaseModel } from './basemodel.ts';
export { default as Auth } from './auth.ts';
export { default as Validator } from './validator.ts';

models/basemodel.ts

import { firestore } from 'firebase-admin';

export default abstract class BaseModel {
  private _collection: firestore.Firestore;

  get collection(): firestore.Firestore {
    return this._collection
  }

  constructor() {
    this._collection = firestore().collection(
      this.constructor.name.toLowerCase()
    )
  }


  //... more codes
}

models/auth.ts

import { BaseModel } from '.';

export default new (class Auth extends BaseModel)()

现在我在 middleware/input-validator.ts

中创建了一个文件
import * as joi from 'joi';
import { Validator } from '../models';

export default (schema) => (req, res, next) => {
  const result = new Validator(schema,  req.body, //... callback codes removed)

  //.. if result true then next() else throw response err
}

现在当我尝试提供 函数(I am using firebase function with TS)

它返回一个错误:

Cannot read property 'firestore' of undefined

现在我尝试删除 auth.ts 中的 new,如下所示:

models/auth.ts

import { BaseModel } from '.';

export default class Auth extends BaseModel {};

并尝试serve 并且成功了;

现在我的问题是,它是怎么发生的?

我试图检查堆栈跟踪,但它指出base modelfirestore to be undefined

这是模块中的陷阱还是 typescript 或 es6 中的其他东西(或缺少它)?

这也是我的tsconfig

{
  "compilerOptions": {
    "module": "commonjs",
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "outDir": "lib",
    "sourceMap": true,
    "strict": true,
    "target": "es2017",
    "resolveJsonModule": true
  },
  "compileOnSave": true,
  "include": ["src"],
  "exclude": ["node_modules"]
}

编辑

我忘了添加要调用身份验证的服务。

services/auth-service.ts

import { Auth } from '../models';

export default class AuthService {
   constructor() { 
     this.model = Auth;
   }
}

现在它在帖子中使用

import * as AuthService from './services';

app.post("/login", (req, res) => { 
 const { email, password } = req.body;

 new AuthService().login(email, password)

 //.. create token and respond with token
})

【问题讨论】:

  • Auth 的导入在哪里?
  • @T.J.Crowder。它已在名为AuthService 的类中使用,该类又用于登录
  • 您说过更改auth.ts 导出的内容会改变问题。所以我们需要查看导入它的代码来了解它是如何被使用的。

标签: javascript node.js typescript firebase-admin


【解决方案1】:

对于 Admin SDK 的导入无效。

import { firestore } from 'firebase-admin';

必须是:

import * as admin from 'firebase-admin'

admin.initializeApp();
const firestore = admin.firestore();

Import only used bits from firebase-admin when using Typescript in Cloud Functions

【讨论】:

    猜你喜欢
    • 2018-08-14
    • 2017-02-06
    • 2016-01-23
    • 2016-02-10
    • 2019-12-11
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 2018-04-17
    相关资源
    最近更新 更多