mercredi 30 mars 2022

JS Method Chaining Controlling Flow

I have created a method in Typescripty which utilizes method chaining to create a simple sql query builder. It implements the basic query methods. What I would like to do is not allow someone to call the offset method for example if they havent called limit previously or calling where twice. I know I can implement something via a map which stores the previously called methods but I was wondering if there is a clean solution to this problem. My current query builder method is

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 a nice way to force the flow of the method chaining?

Aucun commentaire:

Enregistrer un commentaire