我需要在 Nest.js 中將 CRM API 與我的服務集成。不幸的是,他們要求我實作他們的介面以使用自定義持久層,在我的例子中是 Mongo。因為我需要實體化生成的類,所以我不能像往常一樣注入模型,所以我嘗試在類成員變數上使用它。但是,這會導致成員變數未定義的錯誤。
這是我的貓鼬模型:
export type ZohoTokenDocument = ZohoToken & Document;
@Schema({ timestamps: true })
export class ZohoToken {
@Prop()
name: string;
@Prop({ type: String, length: 255, unique: true })
user_mail: string;
@Prop({ type: String, length: 255, unique: true })
client_id: string;
@Prop({ type: String, length: 255 })
refresh_token: string;
@Prop({ type: String, length: 255 })
access_token: string;
@Prop({ type: String, length: 255 })
grant_token: string;
@Prop({ type: String, length: 20 })
expiry_time: string;
}
export const ZohoTokenSchema = SchemaFactory.createForClass(ZohoToken);
這是我根據第 3 方 API 的要求創建的自定義類:
export class ZohoStore implements TokenStore {
@InjectModel(ZohoToken.name)
private readonly tokenModel: Model<ZohoTokenDocument>;
async getToken(user, token): Promise<any> {
const result = await this.tokenModel.findOne({ grant_token: token });
return result;
}
...
在我的服務中,我只是將這個類實體化為new ZohoStore(),它可以正常作業,直到getToken()稍后呼叫該方法。
由此產生的錯誤是:"nullTypeError: Cannot read property 'findOne' of undefined",,這對我來說意味著tokenModel沒有被實體化。知道如何將我的模型注入這個類而不將它放入建構式中,否則我無法使用我的服務中的零引數建構式實體化它嗎?
uj5u.com熱心網友回復:
如果您嘗試使用 Nest DI 系統,那么您將無法自行呼叫new ZohoStore(),因為 Nest 沒有機會實體化ZohoStore的依賴項。
您需要在某些 NestJS 模塊中將其注冊為提供者,然后根據需要檢索由 NestJS 創建的實體。
- https://docs.nestjs.com/providers#property-based-injection
- https://docs.nestjs.com/fundamentals/module-ref#retrieving-instances
- https://docs.nestjs.com/techniques/configuration#using-in-the-maints
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/387144.html
上一篇:不允許使用zod決議的額外屬性
下一篇:如何處理打字稿中的狀態?
