Наследовать от родительского класса, расширяющего Type goose и содержащего методы stati c type-speci c - PullRequest
0 голосов
/ 21 марта 2020

Я занимаюсь разработкой сервера с использованием TypeScript и Node JS и использую библиотеку Type goose для отображения классов в документы 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(). Мне нужны эти методы, чтобы абстрагировать поведение типа goose и выполнение запросов к остальному серверу. Есть ли способ определить суперкласс, чтобы эти три метода могли быть удалены из 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, но я не нашел способа правильно использовать это.

1 Ответ

0 голосов
/ 21 марта 2020

Если 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)
...