Controlling the flow with JS method chaining

I've devised a TypeScript method that employs method chaining to craft a simple SQL query builder. It includes the essential query methods. I want to restrict users from calling the offset method, for instance, if they haven't previously called limit or have called where twice. While I know I can utilize a map to track the previously invoked methods, I'm curious if there's a more streamlined solution to this dilemma. Below is my current query builder method:

public qb = () =>
{
    let query = this.SELECT;
    const api = {
        where: (key: string, value: number|string) =>
        {
            query = sql`${query} WHERE ${sql.identifier([key])} = ${value}`;
            return api;
        },
        and: (key: string, value: number|string) =>
        {
            query = sql`${query} AND ${sql.identifier([key])} = ${value}`;
            return api;
        },
        orderBy: (key: string, order: 'ASC'|'DESC') =>
        {
            query = sql`${query} ORDER BY ${sql.identifier([key])} ${order}`;
            return api;
        },
        limit: (limit: number) =>
        {
            query = sql`${query} LIMIT ${limit}`;
            return api;
        },
        offset: (offset: number) =>
        {
            query = sql`${query} OFFSET ${offset}`;
            return api;
        },
        get: async () => this.rowMapper(await this.database.query(query)),
    };
    return api;
};

Is there an elegant way to control the flow of method chaining?

Answer â„–1

After thorough consideration, I have come up with a solution that involves the creation of multiple objects containing various methods. Admittedly, this approach may not be the most elegant one, but it was the best I could come up with given the circumstances.

public qb = () =>
{
    let query = this.SELECT;

    const get = async () => this.rowMapper(await this.database.query(query));
    const limit = (_limit: number) =>
    {
        query = sql`${query} LIMIT ${_limit}`;
        return {
            offset: (offset: number) =>
            {
                query = sql`${query} OFFSET ${offset}`;
                return { get };
            },
            get,
        };
    };

    const api2 = {
        and: (key: string, value: number|string) =>
        {
            query = sql`${query} AND ${sql.identifier([key])} = ${value}`;
            return api2;
        },
        orderBy: (key: string, order: 'ASC'|'DESC') =>
        {
            query = sql`${query} ORDER BY ${sql.identifier([key])} ${order}`;
            return {
                limit,
                get,
            };
        },
        limit,
        get,
    };
    const api = {
        where: (key: string, value: number|string) =>
        {
            query = sql`${query} WHERE ${sql.identifier([key])} = ${value}`;
            return api2;
        },

    };
    return api;
};

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

How can I utilize JavaScript to generate a dynamic value in a URL and then submit it through a form?

One of my clients has requested the ability to send out unique URLs to their customers in order to track which links are being utilized. Despite my suggestion to use Google Analytics for this purpose, they have specifically asked to avoid it. Their reques ...

Steps for adjusting the structure of an array of objects according to the ParentID

I need to reorganize an array of objects based on a field called ParentID. Here is an example dataset: var JsonVal = "data": { "Factorid": 197325, "orders": [ { ...

What causes the React Query cache to be cleared upon page reload?

Hi there, I am new to Next.js and React Query. I would really appreciate any help or advice. I apologize for any mistakes in my English language skills. Currently, I am using Next.js v12 and React Query v3, along with the React Query DevTools. On one of ...

The Fusion of JavaScript Frameworks

Is it considered poor practice for a seasoned developer to build a web application using multiple JS frameworks? For instance, when incorporating AngularJS into a project, and certain tasks could be more efficiently achieved with JQuery, should one opt fo ...

The tooltip feature is malfunctioning

The content: <table class="table table-hover"> <?php foreach ($query as $row){ echo '<tr ><td > <label class="checkbox"> '.form_checkbox('delete[]', $row['link']).anchor("site ...

What is the process of adding an array into a JSON object using the set() function in Firebase?

I am trying to add a new item to my firebase database with a specific JSON object structure: var newItem = { 'address': "Кабанбай батыр, 53", 'cityId': 1, 'courierName': "МаР...

To send a form without navigating away from the current page

I have been struggling to create an online HTML form that can submit data to the local database without redirecting the page to the /formfill URL. Despite my efforts, I have not been successful so far. Below is my backend node.js code: // require('./ ...

Log in using your Google credentials within an AngularJS application

I recently went through a tutorial on integrating Google sign-in with my AngularJS app. Following the tutorial instructions, I added the Google button in the following manner: First, I included the meta tag in the head section: <meta name="google-sign ...

Changes made to attribute values through Ajax success function are not immediately reflected and require a manual page refresh to take effect

Whenever I attempt to rename my object using an Ajax request triggered by a click event, followed by updating its element's attribute with the new name in the success function, I encounter a partial issue. Upon inspecting the element on Chrome, post- ...

An issue occurred: Promise was not caught and resulted in an error stating that no routes can be matched for the URL segment 'executions/190'

My current project involves developing the front end by mocking the back-end using the expressjs library. Within my project, I have a file called data.json which stores objects like the following: "singleExecutions":[ {"executionId":190, "label":"exe ...

Is it more efficient to have multiple Angular HTTP interceptor files or a single large file of interceptors when it comes to request speed

I'm a beginner with Angular and I'm currently exploring the use of HTTP interceptors. I am contemplating whether it is better to combine multiple interceptors, such as setting headers' token, cache-control, content-type in a single file, or ...

Finding the index of a column based on a continuous sequence of values can be achieved by following these

Consider this sequence of numbers representing components on a page: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 Every set of 3 numbers makes up a page, with indexing restarting for each new page. Essentially, it follo ...

Differences Between Angular 2 Reactive Forms and Template Forms

We are embarking on a new Angular 2 project and are deliberating on whether to opt for Reactive Forms or Template Forms. If you want to learn more, you can refer to this article: https://angular.io/guide/reactive-forms From what I understand, the main adv ...

What is the best way to utilize a JavaScript variable as a background within an inline style sheet?

I have a fun project for this evening - I am trying to make my website load a different background image every time the page is refreshed. Earlier on in this project, I managed to make the background interact with window size and screen resolution similar ...

Warning issued by npm during compilation: The template string expression is unexpected as there should be no curly braces in the

Getting an npm warning during compiling (Unexpected template string expression no-template-curly-in-string) import React from 'react'; const Card = ({name, email, id }) => { return ( <div className='tc bg-light-green dib b ...

Using JavaScript to access session data from the view in CodeIgniter

Working with CodeIgniter 2.0 Framework In my current project, I am facing a challenge where I need to access session data set up in the model from the view. Below is the code snippet that I have been testing within my view: <script type='text/ja ...

Unusual escape_javascript quirk witnessed in Ruby on Rails

Once the ajax method is called, the escape_javascript function starts outputting </div> </div> </div> for each rendered item. Despite thoroughly checking all closing tags multiple times, I can't seem to identify any errors. Could thi ...

Whenever I attempt to test the get all route, I encounter the error message "TypeError: Cannot read property '1' of null"

I'm currently working on developing a login system. When attempting to retrieve all users from my MySQL database in order to test the system, I encountered an error that reads: TypeError: Cannot read property '1' of null at firstchar (E: ...

Is it possible to transmit the survey findings through a telegram?

Just finished creating a survey using the platform . Here are the results: Data format: {"question1":["item1"],"question2":["item2"],"question3":["item2"],"question4":["item2" ...

Setting up TypeScript in an Angular 2 project and integrating Facebook login

Currently, I am in the process of familiarizing myself with Angular 2 and typescript. Although things have been going smoothly so far, I have hit a roadblock while attempting to implement a Facebook login message. In my search for a solution, I stumbled up ...