【发布时间】: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 model 是firestore 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