-
Notifications
You must be signed in to change notification settings - Fork 19
/
db-registry.js
104 lines (91 loc) · 2.35 KB
/
db-registry.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
'use strict';
/**
* @module service/db-registry
*/
const os = require('os');
const mkdirp = require('mkdirp');
const url = require('url');
const path = require('path');
const pify = require('pify');
const cloneDeep = require('lodash/cloneDeep');
const common = require('coinstac-common');
const pouchDBAdapterMemory = require('pouchdb-adapter-memory');
const pouchDbAdapterLevelDB = require('pouchdb-adapter-leveldb');
const DB_REGISTRY_DEFAULTS = {
isRemote: true,
localStores: null,
pouchConfig: {},
remote: {
db: {
protocol: 'http',
hostname: 'localhost',
port: 5984,
},
},
remoteStoresSyncOut: null,
verbose: true,
};
module.exports = {
instance: null,
/**
* get db directory.
* @returns {string}
*/
getDBPath() {
return path.join(
os.tmpdir(),
'coinstac-server-core',
'dbs'
);
},
/**
* get DBRegistry instance
* @returns {DBRegistry}
*/
get() {
/* istanbul ignore next */
if (!this.instance) {
throw new Error('dbRegistry must be configured before retrieval');
}
return this.instance;
},
/**
* initializes dbRegistry singleton.
* @returns {Promise} resolves to DBRegistry instance
*/
init(opts) {
// Unfortunately necessary for sinon spying
const dbRegistryFactory = common.services.dbRegistry;
const config = opts ? cloneDeep(opts) : {};
const dbRegistryOptions = cloneDeep(DB_REGISTRY_DEFAULTS);
if (config.dbUrl) {
dbRegistryOptions.remote.db = url.parse(config.dbUrl);
}
if (config.inMemory) {
dbRegistryFactory.DBRegistry.Pouchy.plugin(pouchDBAdapterMemory);
dbRegistryOptions.pouchConfig.adapter = 'memory';
} else {
dbRegistryFactory.DBRegistry.Pouchy.plugin(pouchDbAdapterLevelDB);
dbRegistryOptions.pouchConfig.adapter = 'leveldb';
}
dbRegistryOptions.path = this.getDBPath();
this.instance = dbRegistryFactory(dbRegistryOptions);
return this.upsertDBDir().then(() => this.get());
},
/**
* upsert db dir.
* @returns {Promise} resolves with db-directory
*/
upsertDBDir() {
return pify(mkdirp)(this.getDBPath());
},
/**
* removes singleton registry instance. old instances is garbage
* collected
* @returns {undefined}
*/
teardown() {
// @note - the pool is responsible for actual db `destroy`ing
delete this.instance;
},
};