Skip to content

Instantly share code, notes, and snippets.

@killreal17
Created August 27, 2020 22:18

Revisions

  1. killreal17 created this gist Aug 27, 2020.
    68 changes: 68 additions & 0 deletions index.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,68 @@
    class Query {
    body: string;
    constructor () {
    this.body = '<type>'
    };
    pipe (...args) {
    this.body = args.reduce((acc, arg) => {
    return acc.replace(arg.tag, arg.body)
    }, this.body);
    return this;
    }
    fork () {
    return this.body.replace(new RegExp('<\\w*>'), '')
    }
    }

    const select = (fields) => {
    return {
    tag: '<type>',
    body: `select ${fields} <from>`
    }
    }

    const from = (table) => {
    return {
    tag: '<from>',
    body: `from ${table} <join>`
    }
    }

    const join = (
    table,
    leftKey,
    rigthKey,
    ) => {
    return {
    tag: '<join>',
    body: `inner join ${table} ${leftKey} = ${rigthKey} <join>`
    }
    }

    const q = new Query()

    //Условный запрос, в котором соединяются две таблицы

    console.log(q.pipe(
    select([
    'user.name',
    'user.country',
    'session.id'
    ]),
    from('user'),
    join(
    'session',
    'user.id',
    'session.id'
    )
    ).fork())

    /*
    Что мне нравится:
    Очень гибко - если тебе не нравится одна функция, просто перепиши ее
    Не смотришь на лишнее - не собираешь непонятный объект со странными полями
    Составление запроса и выполнение запроса не завязанны друг на друге
    Что мне не нравится
    Из-за гибкости нет стандарта
    Не приятно читать
    */