|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const MOCK_DATASET = [ |
| 4 | + { name: 'Rome', population: 2761632, country: 10, type: 1 }, |
| 5 | + { name: 'Milan', population: 1371498, country: 10, type: 1 }, |
| 6 | + { name: 'Naples', population: 914758, country: 10, type: 1 }, |
| 7 | + { name: 'Turin', population: 848885, country: 10, type: 1 }, |
| 8 | + { name: 'Palermo', population: 630828, country: 10, type: 1 }, |
| 9 | + { name: 'Genoa', population: 560688, country: 10, type: 1 }, |
| 10 | + { name: 'Bologna', population: 392203, country: 10, type: 1 }, |
| 11 | + { name: 'Florence', population: 367150, country: 10, type: 1 }, |
| 12 | + { name: 'Bari', population: 316140, country: 10, type: 1 }, |
| 13 | + { name: 'Catania', population: 298324, country: 10, type: 1 }, |
| 14 | +]; |
| 15 | + |
| 16 | +const MOCK_TIMEOUT = 1000; |
| 17 | + |
| 18 | +class Query { |
| 19 | + constructor(table) { |
| 20 | + this.options = { table, fields: ['*'], where: {} }; |
| 21 | + } |
| 22 | + |
| 23 | + where(conditions) { |
| 24 | + Object.assign(this.options.where, conditions); |
| 25 | + return this; |
| 26 | + } |
| 27 | + |
| 28 | + order(field) { |
| 29 | + this.options.order = field; |
| 30 | + return this; |
| 31 | + } |
| 32 | + |
| 33 | + limit(count) { |
| 34 | + this.options.limit = count; |
| 35 | + return this; |
| 36 | + } |
| 37 | + |
| 38 | + then(resolve) { |
| 39 | + const { table, fields, where, limit, order } = this.options; |
| 40 | + const cond = Object.entries(where).map((e) => e.join('=')).join(' AND '); |
| 41 | + const sql = `SELECT ${fields} FROM ${table} WHERE ${cond}`; |
| 42 | + const opt = `ORDER BY ${order} LIMIT ${limit}`; |
| 43 | + const query = sql + ' ' + opt; |
| 44 | + return new Promise((fulfill) => { |
| 45 | + setTimeout(() => { |
| 46 | + const result = { query, dataset: MOCK_DATASET }; |
| 47 | + fulfill(resolve(result)); |
| 48 | + }, MOCK_TIMEOUT); |
| 49 | + }); |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +// Usage |
| 54 | + |
| 55 | +(async () => { |
| 56 | + |
| 57 | + const cities = await new Query('cities') |
| 58 | + .where({ country: 10, type: 1 }) |
| 59 | + .order('population') |
| 60 | + .limit(10) |
| 61 | + .then((result) => { |
| 62 | + const projection = new Map(); |
| 63 | + for (const record of result.dataset) { |
| 64 | + const { name, population } = record; |
| 65 | + projection.set(name, population); |
| 66 | + } |
| 67 | + return projection; |
| 68 | + }); |
| 69 | + |
| 70 | + console.log(cities); |
| 71 | + |
| 72 | +})(); |
0 commit comments