What strategies can be implemented to effectively share code between these two methods?

Is there a way to consolidate code shared between these two JavaScript methods?

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)
}

Any suggestions or advice would be greatly appreciated. Thank you

Answer №1

To utilize the method getAllActiveRooms, you can modify its return type to Knex's QueryBuilder, which inherits from Bluebird's promise interface. However, note that by doing so, you will no longer have the payload type of RoomType[] since it extends Bluebird<any>.

In Knex's most recent type definition (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)
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unraveling a date field from JSON with AngularJS filtering

Extracting data from JSON file shows /Date(1435837792000+0000)/ How can I format the date to appear as Oct 29, 2010 9:10:23 AM? ...

Checking the authenticity of Javascript Objects containing date values

What is the best way to validate a JavaScript Object that includes date fields? While there are JSON validators such as tv4 that can check the format of string dates, our business logic operates with JavaScript Date instances which these validators do not ...

What is the best way to send two mongoose find queries to the correct GET route?

I am facing an issue with my app where I have two separate routes using app.get to render "/" and fetch data from two different MongoDB collections using mongoose find{} methods. I also have corresponding post routes that redirect the data entered in forms ...

Ways to resolve eslint typedef error when using angular reactive forms with form.value

I am facing an issue with my formGroup and how I initialized it. Whenever I try to retrieve the complete form value using form.value, I encounter an eslint error related to typecasting. userForm = new FormGroup<user>({ name: new FormControl<st ...

Formik state is mysteriously reverting field values to their default state

I've encountered an issue with my form and song state while trying to add a new field called "appleMusicId". Unfortunately, every time I add this field, it seems to reset the values of timeDescription and sceneDescription. I've spent hours tryin ...

What is the method for displaying map tooltips by default rather than on mouseover?

Currently, I have a script set up to display a map with two markers. Whenever I hover over one of the markers, a popup tooltip appears with location information. My question is, how can I make the information appear by default without needing to hover ov ...

Adjusting canvas size to match content dimensions

I posed a similar inquiry and it was categorized as a duplicate even though the suggested duplicate did not provide an answer to my question. Edit: The purported duplicate was [stackoverflow.com/questions/17211920/make-canvas-height-auto][1] I am utilizi ...

The most effective method for modifying a prop in VueJS without altering the parent's data

In the main Vue component, there is an object named user. If I pass this user object as a prop to a child component: <child :user="user"></child> When updating user.name in the child component, the changes also reflect in the parent componen ...

AngularJS attempting to conceal the popup menu upon clicking outside of the designated area

My HTML structure looks like this: <div> <a href="" ng-click="$scope.show_menu = !$scope.show_menu">Options</a> <div class="options_box" ng-show="$scope.show_menu"> <button>Option1</button> ... ...

Having issues with the background-image style not displaying correctly in the header of an

Trying to update the "background-image:" of a CSS class upon button click. JQuery: $(function() { $('button').on('click', function() { $('.masthead2').css('background-image', 'url("../img/whitehead ...

Attempting to dispatch data from Vue.js event bus

I am attempting to increase the count of quotes by one and also add the text from a textarea to an array. While the text is successfully added to the array, the number of quotes always remains zero. I have tried combining the two actions in one method as w ...

The directive binding value is accurate, however it is failing to return a true result

The behavior of a custom directive is puzzling me. When I directly pass in a value, it works fine. However, if I bind the value to a variable, it doesn't work as expected. Interestingly, when I use console.log to show the value, it appears to be corre ...

The complete height of the website is concealed by the mobile toolbar/menu

I encountered a perplexing issue regarding the responsive resizing of a website on mobile devices. The problem arises when the full height extends over the toolbar/menu, unless the user manually hides the toolbar. Is there a way to dynamically resize the ...

Utilizing Vue.js to compare two arrays and verify if the results are identical

I am in the process of developing a theater app that requires me to work with JSON data consisting of two arrays: Sections and Groups. While I have successfully loaded both arrays into my Vue app, I now need to compare them to find matches. The first array ...

arrange elements by their relationship with parents and children using typescript and angular

Here is a list that needs to be sorted by parent and child relationships: 0: {id: 7, name: "333", code: "333", type: 3, hasParent: true, parentId: 4} 1: {id: 6, name: "dfgdfg", code: "dfgdfg", type: 3, hasParent: false, parentId: null} 2: {id: 5, name: ...

A guide on using Sinon to mock a custom $http transform

Exploring the proper method for mocking an http post with a custom transform in Angular using the Sinon mocking framework. In my CoffeeScript Sinon unit test setup, I define mocks like this: beforeEach module(($provide) -> mockHttp = {} $provide.value ...

Tips on utilizing the Material Ui Select input property?

Trying to understand why material-ui's InputBase is functional while regular HTML input is not. The documentation defines the input prop as follows: An Input element; does not have to be a material-ui specific Input. Successful example: import Sele ...

Building a JSON-powered navigation bar with Bootstrap 4

Looking to create a custom navigation bar using Bootstrap 4 and populate it with items from a JSON file. Despite researching various methods, there seems to be limited resources available on this topic. Any assistance or guidance would be greatly appreciat ...

changing web pages into PDF format

I need to convert HTML to PDF on a Linux system and integrate this functionality into a web application. Can you suggest any tools that are capable of doing this? Are there any other tools I should consider for this task? So far, I have attempted the foll ...

Employ ImageMagic in a synchronous manner

Consider utilizing imagemagick Required to use imagemagick in a synchronous manner. Meaning the following code should execute only after the image conversion is complete (regardless of any errors). The only solution I can see involves using deasync: co ...