@@ -35,13 +35,15 @@ Below is an example of how to use it with [Node.js](https://nodejs.org), [Expres
35
35
``` js
36
36
import express from ' express' ;
37
37
import Promise from ' bluebird' ;
38
- import db from ' sqlite' ;
38
+ import sqlite from ' sqlite' ;
39
39
40
40
const app = express ();
41
41
const port = process .env .PORT || 3000 ;
42
+ const dbPromise = sqlite .open (' ./database.sqlite' , { Promise }));
42
43
43
44
app .get (' /post/:id' , async (req , res , next ) => {
44
45
try {
46
+ const db = await dbPromise;
45
47
const [post , categories ] = await Promise .all ([
46
48
db .get (' SELECT * FROM Post WHERE id = ?' , req .params .id ),
47
49
db .all (' SELECT * FROM Category' );
@@ -52,20 +54,15 @@ app.get('/post/:id', async (req, res, next) => {
52
54
}
53
55
});
54
56
55
- Promise .resolve ()
56
- // First, try connect to the database
57
- .then (() => db .open (' ./database.sqlite' , { Promise }))
58
- .catch (err => console .error (err .stack ))
59
- // Finally, launch Node.js app
60
- .finally (() => app .listen (port));
57
+ app .listen (port);
61
58
```
62
59
63
60
### Cached DB Driver
64
61
65
62
If you want to enable the [ database object cache] ( https://github.com/mapbox/node-sqlite3/wiki/Caching )
66
63
67
- ```
68
- db .open('./database.sqlite', { cached: true }))
64
+ ``` js
65
+ sqlite .open (' ./database.sqlite' , { cached: true }))
69
66
```
70
67
71
68
### Migrations
@@ -104,25 +101,23 @@ DROP INDEX Post_ix_categoryId;
104
101
``` js
105
102
import express from ' express' ;
106
103
import Promise from ' bluebird' ;
107
- import db from ' sqlite' ;
104
+ import sqlite from ' sqlite' ;
108
105
109
106
const app = express ();
110
107
const port = process .env .PORT || 3000 ;
111
108
109
+ const dbPromise = Promise .resolve ()
110
+ .then (() => sqlite .open (' ./database.sqlite' , { Promise }))
111
+ .then (db => db .migrate ({ force: ' last' }));
112
+
112
113
app .use (/* app routes */ );
113
114
114
- Promise .resolve ()
115
- // First, try connect to the database and update its schema to the latest version
116
- .then (() => db .open (' ./database.sqlite' , { Promise }))
117
- .then (() => db .migrate ({ force: ' last' }))
118
- .catch (err => console .error (err .stack ))
119
- // Finally, launch Node.js app
120
- .finally (() => app .listen (port));
115
+ app .listen (port);
121
116
```
122
117
123
118
** NOTE** : For the development environment, while working on the database schema, you may want to set
124
119
` force: 'last' ` (default ` false ` ) that will force the migration API to rollback and re-apply the
125
- latest migration over again each time when Node.js app launches.
120
+ latest migration over again each time when Node.js app launches.
126
121
127
122
128
123
### Multiple Connections
0 commit comments