Skip to content

Commit

Permalink
Merge pull request #45 from LinusU/readme
Browse files Browse the repository at this point in the history
Move away from global db object in readme
  • Loading branch information
Theo Gravity authored Nov 15, 2017
2 parents 9d6f3c1 + 9a87112 commit 96764e2
Showing 1 changed file with 13 additions and 18 deletions.
31 changes: 13 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,15 @@ Below is an example of how to use it with [Node.js](https://nodejs.org), [Expres
```js
import express from 'express';
import Promise from 'bluebird';
import db from 'sqlite';
import sqlite from 'sqlite';

const app = express();
const port = process.env.PORT || 3000;
const dbPromise = sqlite.open('./database.sqlite', { Promise }));

app.get('/post/:id', async (req, res, next) => {
try {
const db = await dbPromise;
const [post, categories] = await Promise.all([
db.get('SELECT * FROM Post WHERE id = ?', req.params.id),
db.all('SELECT * FROM Category');
Expand All @@ -52,20 +54,15 @@ app.get('/post/:id', async (req, res, next) => {
}
});

Promise.resolve()
// First, try connect to the database
.then(() => db.open('./database.sqlite', { Promise }))
.catch(err => console.error(err.stack))
// Finally, launch Node.js app
.finally(() => app.listen(port));
app.listen(port);
```

### Cached DB Driver

If you want to enable the [database object cache](https://github.com/mapbox/node-sqlite3/wiki/Caching)

```
db.open('./database.sqlite', { cached: true }))
```js
sqlite.open('./database.sqlite', { cached: true }))
```

### Migrations
Expand Down Expand Up @@ -104,25 +101,23 @@ DROP INDEX Post_ix_categoryId;
```js
import express from 'express';
import Promise from 'bluebird';
import db from 'sqlite';
import sqlite from 'sqlite';

const app = express();
const port = process.env.PORT || 3000;

const dbPromise = Promise.resolve()
.then(() => sqlite.open('./database.sqlite', { Promise }))
.then(db => db.migrate({ force: 'last' }));

app.use(/* app routes */);

Promise.resolve()
// First, try connect to the database and update its schema to the latest version
.then(() => db.open('./database.sqlite', { Promise }))
.then(() => db.migrate({ force: 'last' }))
.catch(err => console.error(err.stack))
// Finally, launch Node.js app
.finally(() => app.listen(port));
app.listen(port);
```

**NOTE**: For the development environment, while working on the database schema, you may want to set
`force: 'last'` (default `false`) that will force the migration API to rollback and re-apply the
latest migration over again each time when Node.js app launches.
latest migration over again each time when Node.js app launches.


### Multiple Connections
Expand Down

0 comments on commit 96764e2

Please sign in to comment.