-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy patha-query.js
More file actions
44 lines (36 loc) · 865 Bytes
/
a-query.js
File metadata and controls
44 lines (36 loc) · 865 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
'use strict';
class Query {
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}`;
resolve(sql + ' ' + opt);
}
}
// Usage
const main = async () => {
const sql = await new Query('cities')
.where({ country: 10, type: 1 })
.order('population')
.limit(10);
console.log(sql);
};
main();