-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathworker-factory.js
73 lines (60 loc) · 1.46 KB
/
worker-factory.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
'use strict'
const DB_WORKER_ACTIONS = require(
'./db-worker-actions/db-worker-actions.const'
)
module.exports = (executeAction) => {
const { workerData, parentPort } = require('worker_threads')
const Database = require('better-sqlite3')
const _connect = (args) => {
const {
dbPath = './sqlite-db.db',
readonly = false,
fileMustExist = false,
timeout = 5000,
verbose = false
} = args
return new Database(
dbPath,
{
readonly,
fileMustExist,
timeout,
...(verbose ? { verbose: console.log } : {})
}
)
}
const _serializeError = (err) => {
if (!(err instanceof Error)) {
return err
}
return Object.keys(err).reduce((obj, key) => {
obj[key] = err[key]
return obj
}, {
name: err.name,
message: err.message,
stack: err.stack,
isError: true
})
}
const db = _connect(workerData)
parentPort.on('message', (args) => {
try {
const { action } = args
if (!(db instanceof Database)) {
throw new Error('ERR_DB_HAS_NOT_BEEN_INITIALIZED')
}
if (!action) {
throw new Error('ERR_ACTION_HAS_NOT_BEEN_PASSED')
}
const result = executeAction(db, args)
if (action === DB_WORKER_ACTIONS.CLOSE_DB) {
return
}
parentPort.postMessage({ result })
} catch (e) {
const err = _serializeError(e)
parentPort.postMessage({ err })
}
})
}