-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path3-director.js
More file actions
54 lines (45 loc) · 1.13 KB
/
3-director.js
File metadata and controls
54 lines (45 loc) · 1.13 KB
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
46
47
48
49
50
51
52
53
54
'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);
}
}
const queryDirector = (table, { conditions, order, limit }) => {
const query = new QueryBuilder(table);
if (conditions) query.where(conditions);
if (order) query.order(order);
if (limit) query.limit(limit);
return query;
};
// Usage
const main = async () => {
const query = await queryDirector('cities', {
conditions: { country: 10, type: 1 },
order: 'population',
limit: 10,
});
console.log(query);
};
main();