forked from Eomm/fastify-sqlite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
83 lines (66 loc) · 1.9 KB
/
index.js
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
'use strict'
const fp = require('fastify-plugin')
const sqlite3 = require('sqlite3')
const { open } = require('sqlite')
function fastifySqlite (fastify, opts, next) {
const Sqlite = (opts.verbose === true)
? sqlite3.verbose()
: sqlite3
const filename = opts.dbFile || ':memory:'
const mode = opts.mode || (sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE | sqlite3.OPEN_FULLMUTEX)
if (opts.promiseApi === true) {
open({
filename,
mode,
driver: Sqlite.Database
}).then(setupDatabase, setupDatabase)
} else {
// eslint-disable-next-line
new Sqlite.Database(filename, mode, setupDatabase)
}
function setupDatabase (err) {
if (err && err instanceof Error) {
return next(err)
}
const db = err || this
if (opts.verbose === true) {
db.on('trace', function (trace) {
fastify.log.trace({ sql: trace }, 'sqlite verbose trace')
})
}
decorateFastifyInstance(fastify, db, opts, next)
}
}
function decorateFastifyInstance (fastify, db, opts, next) {
fastify.addHook('onClose', close.bind(db))
const name = opts.name
if (!name) {
if (fastify.sqlite) {
return next(new Error('fastify-sqlite has been already registered'))
}
fastify.decorate('sqlite', db)
} else {
if (!fastify.sqlite) {
fastify.decorate('sqlite', Object.create(null))
}
if (fastify.sqlite[name]) {
return next(new Error(`Connection name [${name}] already registered`))
}
fastify.sqlite[name] = db
}
next()
}
function close (instance, done) {
const isProm = this.close(done)
if (isProm?.then) {
isProm.then(done, done)
}
}
module.exports = fp(fastifySqlite, {
name: 'fastify-sqlite',
fastify: '^4.x'
})
module.exports.default = fastifySqlite
module.exports.fastifySqlite = fastifySqlite
// let the user access the sqlite3 mode constants eg: sqlite3.OPEN_READONLY
module.exports.sqlite3 = sqlite3