我正在使用TypeScript和Node开发服务器,并使用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()方法。我已经看到它接受new () => T类型的参数,但是我还没有找到正确使用它的任何方法。
发布于 2020-03-21 10:17:44
如果get model()不需要是private static方法,您可以尝试这样做:
class Model<T> extends Object {
public get model(this: T): T {
return this;
}
}
class Player extends Model<Player> { }
class Topic extends Model<Topic> { }
const player = new Player();
const topic = new Topic();
console.log(player.model instanceof Player);
console.log(topic.model instanceof Topic)https://stackoverflow.com/questions/60782500
复制相似问题