-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path2-query-builder.js
More file actions
45 lines (37 loc) · 908 Bytes
/
2-query-builder.js
File metadata and controls
45 lines (37 loc) · 908 Bytes
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
'use strict';
class QueryBuilder {
constructor(table) {
this.options = { table, fields: ['*'], where: {} };
}
where(conditions) {
Object.assign(this.options.where, conditions);
return this;
}
order(field) {
this.options.order = field;
return this;
}
limit(count) {
this.options.limit = count;
return this;
}
then(resolve) {
const { table, fields, where, limit, order } = this.options;
const cond = Object.entries(where)
.map((e) => e.join('='))
.join(' AND ');
const sql = `SELECT ${fields} FROM ${table} WHERE ${cond}`;
const opt = `ORDER BY ${order} LIMIT ${limit}`;
const query = sql + ' ' + opt;
resolve(query);
}
}
// Usage
const main = async () => {
const query = await new QueryBuilder('cities')
.where({ country: 10, type: 1 })
.order('population')
.limit(10);
console.log(query);
};
main();