【发布时间】:2020-12-09 23:50:51
【问题描述】:
我正在学习使用 typescript 来构建 API,我现在遇到了两个问题。首先,我有一个有点通用的 PostController 类,它可以接受实现 PostMethod 接口的用例,例如
export interface PostMethod {
add: (req: Request, res: Response) => Promise<any> // not sure if it should be returning any
}
就是接口,通用控制器长这样。
export class PostController implements PostMethod {
constructor(public postMethod: any) {}
async add(req: Request, res: Response) {
let { ...incomingHttpBody } = req.body
console.log('body', incomingHttpBody)
console.log(this.postMethod)
type Source = {
ip: string
browser: string | string[] | undefined
referrer: string | string[]
}
let source = {} as Source
source.ip = req.ip
source.browser = req.headers['User-Agent']
if (req.headers.Referer) {
source.referrer = req.headers.Referer
}
const newItem = await this.postMethod({ source, ...incomingHttpBody })
return apiResponse({
status: true,
statusCode: 201,
message: 'Resource created successfully',
data: [newItem]
})
}
}
然后,我可以像这样使用PostController 类
...
const postMethod = new AddUser(UsersDb).addUser
export const postUser = new PostController(postMethod)
...
AddUser 类看起来像这样,
export class AddUser {
constructor(public usersDb: UserDatabase) {}
async addUser(userInfo: IUser) {
console.log({...userInfo})
const exists = await this.usersDb.findByEmail(userInfo.email)
if (exists) {
throw new UniqueConstraintError('Email address')
}
const user = new UserFactory(userInfo)
user.makeUser()
const { email, ...details } = user.user
const newUser = await this.usersDb.insert({ email, ...details })
const id = newUser.user._id
await createWallet(id)
// await publisher(id.toString(), 'newuser.verify')
// await consumer('verify_queue', verifyUser, '*.verify')
return newUser
}
}
当我执行 req.body 的 console.log 时,我得到了传入的 body,但我不断得到 TypeError: Cannot read property 'postMethod' of undefined。我也不确定如何注释构造函数。我不知道我做错了什么,当我 console.log postUser 时,我确实看到函数作为参数传递到控制台,但是当我尝试发送请求时,它失败了。
请帮忙,谢谢。
【问题讨论】:
标签: javascript node.js typescript express mongoose