我正在使用 TypeScript 和 Node JS 开发服务器,并且正在使用 Typegoose 库将类映射到 MongoDB 文档中。
我有以下两个课程:
import { prop, getModelForClass, DocumentType, ReturnModelType, Typegoose } from '@typegoose/typegoose';
export default class Mode {
// ...various attributes
@prop() name?: string;
private document?: DocumentType<Mode>;
public get id(this: Mode): number {
if (this.document)
return this.document._id;
else throw new Error('Looking for id on non-mapped Mode on database');
}
private static get model(): ReturnModelType<typeof Mode> {
return getModelForClass(Mode);
}
private static attachDocument(document: DocumentType<Mode> | null): Mode | null {
const instance: Mode | null = document as Mode | null;
if (instance && document)
instance.document = document;
return instance;
}
// other methods...
}
import { prop, getModelForClass, DocumentType, ReturnModelType, Typegoose } from '@typegoose/typegoose';
export default class Player {
// ...various attributes
@prop() nickname: string;
private document?: DocumentType<Player>;
public get id(this: Player): number {
if (this.document)
return this.document._id;
else throw new Error('Looking for id on non-mapped Player on database');
}
private static get model(): ReturnModelType<typeof Player> {
return getModelForClass(Player);
}
private static query(document: DocumentType<Player> | null): Player | null {
const instance: Player | null = document as Player | null;
if (instance && document)
instance.document = document;
return instance;
}
// other methods...
}
很容易注意到有类似定义的方法id()
:model()
和attachDocument()
。我需要这些方法来抽象 Typegoose 的行为以及对服务器其余部分的查询执行。有没有办法定义一个超类,以便它们可以从这个超类中删除和继承这三个Mode
方法Player
?
我在想这样的事情:
export default class Model<T> extends Typegoose {
protected document: DocumentType<T>;
public get id(this: T): number {
if (this.document)
return this.document._id;
else throw new Error('Looking for id on non-mapped object on database');
}
private static get model(): ReturnModelType<typeof T> {
return getModelForClass(T);
}
private static attachDocument(document: DocumentType<T> | null): T | null {
const instance: T | null = document as T | null;
if (instance && document)
instance.document = document;
return instance;
}
}
export class Player extends Model<Player> { /* ... */ }
export class Mode extends Model<Mode> { /* ... */ }
但是,这似乎不可行,因为我不能将 T 作为参数传递给getModelForClass()
方法。我已经看到它接受 type 的参数new () => T
,但我还没有找到任何正确使用它的方法。