S T*_*X K 6 typescript typeorm
我需要一些帮助。我使用 typeorm 创建 User 实体,并且想在 Customer 类中覆盖 toResponseObject 以更改返回属性,但是当我写入完成时,错误发生为“Type '{ userName: string; firstName: string; lastName: string; email: string; address : Address; token: string; }' 缺少类型“User”中的以下属性:password、hasPassword、toResponObject、comparePassword” 我想这意味着我应该返回所有用户属性,但我不想返回所有属性。我应该怎么办?
用户实体.ts
import {PrimaryColumn, Column, BeforeInsert} from "typeorm";
import * as bcrypt from 'bcryptjs'
import * as jwt from 'jsonwebtoken'
export abstract class User {
@PrimaryColumn()
userName: string;
@Column()
password: string;
@Column()
firstName: string;
@Column()
lastName: string;
@Column()
email: string;
@BeforeInsert()
async hasPassword(){
this.password = await bcrypt.hash(this.password,10)
}
async toResponObject(showToken:boolean = true){
const {userName,firstName,lastName,email,token} = this
const responseObject = {userName,firstName,lastName,email,token}
if(showToken){
responseObject.token = token
}
return responseObject
}
async comparePassword(attemp:string){
return await bcrypt.compare(attemp,this.password)
}
protected get token(){
const {userName,password} = this
return jwt.sign({userName,password},process.env.SECRETKEY,{expiresIn:'7d'})
}
}
Run Code Online (Sandbox Code Playgroud)
客户实体.ts
import { Pet } from "../pet/pet.entity";
import { Address } from "../address/address.entity";
import { Order } from "../order/order.entity";
import { Feedback } from "../feedback/feedback.entity";
import { User } from "../user/user.entity";
import { Entity, Column, ManyToOne, OneToMany } from "typeorm";
@Entity()
export class Customer extends User {
@Column()
phoneNumber: string;
@OneToMany(type => Pet,pet => pet.owner)
pets: Pet[];
@ManyToOne(type => Address)
address: Address;
@OneToMany(type => Order,order => order.customer)
orders: Order[];
@OneToMany(type => Feedback,feedbacks => feedbacks.customer)
feedbacks: Feedback[];
async toResponObject(showToken:boolean = true):Promise<User>{
const {userName,firstName,lastName,email,address,token} = this
const responseObject = {userName,firstName,lastName,email,address,token}
if(showToken){
responseObject.token = token
}
return responseObject // error ocuurs at this line
}
}
Run Code Online (Sandbox Code Playgroud)
除了危险的评论之外,您还可以使用以下命令返回部分用户
async toResponObject(showToken:boolean = true):Promise<Partial<User>> {
//...
}
Run Code Online (Sandbox Code Playgroud)
这样您就不必定义新对象并且仍然可以获得所需的输出。
| 归档时间: |
|
| 查看次数: |
11868 次 |
| 最近记录: |