|
| 1 | +'use strict' |
| 2 | + |
| 3 | +const fp = require('fastify-plugin') |
| 4 | +const sqlite3 = require('sqlite3') |
| 5 | + |
| 6 | +function fastifySqlite (fastify, opts, next) { |
| 7 | + const Sqlite = (opts.verbose === true) |
| 8 | + ? sqlite3.verbose() |
| 9 | + : sqlite3 |
| 10 | + |
| 11 | + const filename = opts.dbFile || ':memory:' |
| 12 | + const mode = opts.mode || (sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE | sqlite3.OPEN_FULLMUTEX) |
| 13 | + |
| 14 | + const db = new Sqlite.Database(filename, mode, (err) => { |
| 15 | + if (err) { |
| 16 | + return next(err) |
| 17 | + } |
| 18 | + |
| 19 | + if (opts.verbose === true) { |
| 20 | + db.on('trace', function (trace) { |
| 21 | + fastify.log.trace({ sql: trace }, 'sqlite verbose trace') |
| 22 | + }) |
| 23 | + } |
| 24 | + |
| 25 | + decorateFastifyInstance(fastify, db, opts, next) |
| 26 | + }) |
| 27 | +} |
| 28 | + |
| 29 | +function decorateFastifyInstance (fastify, db, opts, next) { |
| 30 | + fastify.addHook('onClose', close.bind(db)) |
| 31 | + |
| 32 | + const name = opts.name |
| 33 | + |
| 34 | + if (!name) { |
| 35 | + if (fastify.sqlite) { |
| 36 | + return next(new Error('fastify-sqlite has been already registered')) |
| 37 | + } |
| 38 | + fastify.decorate('sqlite', db) |
| 39 | + } else { |
| 40 | + if (!fastify.sqlite) { |
| 41 | + fastify.decorate('sqlite', Object.create(null)) |
| 42 | + } |
| 43 | + |
| 44 | + if (fastify.sqlite[name]) { |
| 45 | + return next(new Error(`Connection name [${name}] already registered`)) |
| 46 | + } |
| 47 | + |
| 48 | + fastify.sqlite[name] = db |
| 49 | + } |
| 50 | + |
| 51 | + next() |
| 52 | +} |
| 53 | + |
| 54 | +function close (instance, done) { |
| 55 | + this.close(done) |
| 56 | +} |
| 57 | + |
| 58 | +module.exports = fp(fastifySqlite, { |
| 59 | + name: 'fastify-sqlite', |
| 60 | + fastify: '^4.x' |
| 61 | +}) |
| 62 | + |
| 63 | +// let the user access the sqlite3 mode constants eg: sqlite3.OPEN_READONLY |
| 64 | +module.exports.sqlite3 = sqlite3 |
0 commit comments