在两种方法之间共享代码的最佳方法是什么

时间:2018-04-11 10:04:30

标签: javascript knex.js software-quality

我想知道在javascript中这两种方法之间共享代码的最佳解决方案是什么:

gsort --version

谢谢

1 个答案:

答案 0 :(得分:1)

您可以通过将其返回类型更改为扩展Bluebird的promise接口的knex getAllActiveRooms来重用QueryBuilder。 您将失去RoomType[]承诺有效内容类型,因为它扩展了Bluebird<any>

来自knex的最新类型定义(QueryBuilder extends ChainableInterface):

interface QueryBuilder extends QueryInterface, ChainableInterface {
        or: QueryBuilder;
        and: QueryBuilder;

        //TODO: Promise?
        columnInfo(column?: string): Bluebird<ColumnInfo>;

        forUpdate(): QueryBuilder;
        forShare(): QueryBuilder;

        toSQL(): Sql;

        on(event: string, callback: Function): QueryBuilder;
}

interface ChainableInterface extends Bluebird<any> {
        toQuery(): string;
        options(options: any): QueryBuilder;
        stream(callback: (readable: stream.PassThrough) => any): Bluebird<any>;
        stream(options?: { [key: string]: any }): stream.PassThrough;
        stream(options: { [key: string]: any }, callback: (readable: stream.PassThrough) => any): Bluebird<any>;
        pipe(writable: any): stream.PassThrough;
        exec(callback: Function): QueryBuilder;
}

async getAllActiveRooms(ctx: ?ContextType): QueryBuilder {
    //log getAllActiveRooms
    return this.i.knex('users_rooms')
        .transacting(ctx ? ctx.transaction : null)
        .leftJoin('rooms', 'users_rooms.roomId', 'rooms.id')
        .select('rooms.*')
        .where('active', true);
}
async getActiveRoomsBySessionId(ctx: ?ContextType, sessionId: number): Promise<RoomType[]> {
    //log getAllActiveRooms
    return this.getAllActiveRooms(ctx)
        .andWhere('sessionId',sessionId)
}