|
1 | | -// Okay you caught us, it was all fake. But we can't really expect you |
2 | | -// to setup local databases on your machine specifically for a workshop. |
3 | | -// If you did use a third party database driver for an SQL-based |
4 | | -// database, it would probably work a little like this: |
5 | | -// db.query('SELECT ...').then(results => {}) |
| 1 | +import path from 'path' |
| 2 | +import sqlite3 from 'sqlite3' |
6 | 3 |
|
7 | | -const data = [ |
8 | | - { id: 1, name: 'Michael Jackson' }, |
9 | | - { id: 2, name: 'Ryan Florence' }, |
10 | | - { id: 3, name: 'Brad Westfall' }, |
11 | | - { id: 4, name: 'Chance Stickland' }, |
12 | | -] |
| 4 | +const db = new sqlite3.Database(path.resolve(__dirname, 'database.db')) |
13 | 5 |
|
14 | | -export const db = { |
15 | | - query: (sql: string) => { |
16 | | - if (!sql.startsWith('SELECT')) return Promise.reject('Invalid SQL, must start with SELECT') |
17 | | - |
18 | | - const results = data.filter((row) => { |
19 | | - const formatted = sql.toLowerCase().replace(/(`|')/g, '') |
20 | | - if (formatted === 'select * from user') return true |
21 | | - const matches = formatted.match(/id = (\d+)/) |
22 | | - return matches ? row.id === parseInt(matches[1], 10) : false |
| 6 | +export function query(sql: string) { |
| 7 | + return new Promise((resolve, reject) => { |
| 8 | + db.all(sql, (err, rows) => { |
| 9 | + if (err) { |
| 10 | + reject(err.message) |
| 11 | + } else { |
| 12 | + resolve(rows || []) |
| 13 | + } |
23 | 14 | }) |
24 | | - |
25 | | - return Promise.resolve(results) |
26 | | - }, |
| 15 | + }) |
27 | 16 | } |
0 commit comments