Skip to content

Instantly share code, notes, and snippets.

@killreal17
Created August 27, 2020 22:18
Show Gist options
  • Save killreal17/f76d138c40c56fde5d89fb82fe3c5ba4 to your computer and use it in GitHub Desktop.
Save killreal17/f76d138c40c56fde5d89fb82fe3c5ba4 to your computer and use it in GitHub Desktop.
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())
/*
Что мне нравится:
Очень гибко - если тебе не нравится одна функция, просто перепиши ее
Не смотришь на лишнее - не собираешь непонятный объект со странными полями
Составление запроса и выполнение запроса не завязанны друг на друге
Что мне не нравится
Из-за гибкости нет стандарта
Не приятно читать
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment