/
index.js
86 lines (66 loc) · 1.58 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
84
85
86
'use strict';
const debug = require('debug')('th.storage');
const path = require('path');
const mkdirp = require('mkdirp');
const AppDirectory = require('appdirectory');
const lmdb = require('node-lmdb');
const id = require('../utils/id');
/**
* Simple key/value storage system that supports multi-process access.
*/
class Storage {
constructor(path) {
debug('Opening storage at ' + path);
mkdirp.sync(path);
this._env = new lmdb.Env();
this._env.open({
path: path,
});
this._db = this._env.openDbi({
name: 'shared',
create: true
});
}
put(path, data) {
data = JSON.stringify(data);
var tx = this._env.beginTxn();
tx.putString(this._db, path, data);
tx.commit();
}
get(path) {
var tx = this._env.beginTxn();
var data = tx.getString(this._db, path);
tx.commit();
try {
return data ? JSON.parse(data) : null;
} catch(ex) {
return null;
}
}
sub(path) {
return new SubStorage(this, path);
}
}
class SubStorage {
constructor(storage, path) {
this._storage = storage;
this._path = path;
}
put(path, data) {
return this._storage.put(this._path + '/' + path, data);
}
get(path) {
return this._storage.get(this._path + '/' + path);
}
}
const dirs = new AppDirectory('tinkerhub');
const dbPath = path.join(dirs.userData(), 'db');
const storage = new Storage(dbPath);
storage.machineId = storage.get('th:machine');
if(! storage.machineId) {
storage.machineId = id();
storage.put('th:machine', storage.machineId);
}
module.exports = storage;
module.exports.appdata = dirs.userData();
module.exports.configdir = dirs.userConfig();