-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
70 lines (52 loc) · 1.52 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
'use strict'
const fp = require('fastify-plugin')
const Orama = require('@orama/orama')
const PersistenceInMemory = require('./lib/persistence/in-memory.js')
const PersistenceInFile = require('./lib/persistence/in-file.js')
const SKIP_METHODS = [
'create'
]
const oramaInternals = Orama.internals
async function fastifyOrama (fastify, options) {
if (fastify.orama) {
throw new Error('fastify-orama is already registered')
}
const {
persistence,
...oramaOptions
} = options
let db
const oramaApi = {
persist: undefined // custom
}
const oramaProxyKeys = Object.keys(Orama)
.filter((key) => typeof Orama[key] === 'function' && !SKIP_METHODS.includes(key))
for (const key of oramaProxyKeys) {
oramaApi[key] = (...args) => Orama[key](db, ...args)
}
if (persistence) {
db = await persistence.restore()
oramaApi.persist = /* async */ function persist () {
return persistence.persist(db)
}
}
if (!db) {
if (!oramaOptions.schema) {
throw new Error('You must provide a schema to create a new database')
}
db = await Orama.create(oramaOptions)
}
function withOrama () {
return this
}
fastify.decorate('orama', oramaApi)
fastify.decorate('withOrama', withOrama)
}
module.exports = fp(fastifyOrama, {
fastify: '4.x',
name: 'fastify-orama'
})
module.exports.fastifyOrama = fastifyOrama
module.exports.PersistenceInMemory = PersistenceInMemory
module.exports.PersistenceInFile = PersistenceInFile
module.exports.oramaInternals = oramaInternals