gpt4 book ai didi

javascript - 在两种方法之间交互代码的最佳方法是什么

转载 作者:行者123 更新时间:2023-12-03 02:06:45 25 4
gpt4 key购买 nike

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

async getAllActiveRooms(ctx: ?ContextType): Promise<RoomType[]> {
//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.i.knex('users_rooms')
.transacting(ctx ? ctx.transaction : null)
.leftJoin('rooms', 'users_rooms.roomId', 'rooms.id')
.select('rooms.*')
.where('active', true)
.andWhere('sessionId',sessionId)
}

谢谢

最佳答案

您可以重复使用getAllActiveRooms通过将其返回类型更改为 knex 的 QueryBuilder它扩展了 Bluebird 的 Promise 接口(interface)。您将失去RoomType[]但 promise 有效负载类型,因为它扩展了 Bluebird<any>

来自 knex 的最新类型定义( QueryBuilder 扩展 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)
}

关于javascript - 在两种方法之间交互代码的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49772178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com