-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathindex.js
447 lines (400 loc) · 10.4 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
'use strict';
const kData = Symbol('data-store');
const fs = require('fs');
const os = require('os');
const path = require('path');
const assert = require('assert');
const utils = require('./utils');
/**
* Module dependencies
*/
const get = require('get-value');
const set = require('set-value');
/**
* Initialize a new `Store` with the given `name`, `options` and `default` data.
*
* ```js
* const store = require('data-store')('abc');
* //=> '~/data-store/a.json'
*
* const store = require('data-store')('abc', { cwd: 'test/fixtures' });
* //=> './test/fixtures/abc.json'
* ```
* @name Store
* @param {String} `name` Store name to use for the basename of the `.json` file.
* @param {object} `options` See all [available options](#options).
* @param {object} `defaults` An object to initialize the store with.
* @api public
*/
class Store {
constructor(name, options = {}, defaults = {}) {
if (typeof name !== 'string') {
defaults = options;
options = name || {};
name = options.name;
}
if (!options.path) {
assert.equal(typeof name, 'string', 'expected store name to be a string');
}
const opts = { debounce: 0, indent: 2, home: os.homedir(), name, ...options };
this.name = opts.name || (opts.path ? utils.stem(opts.path) : 'data-store');
this.path = opts.path || path.join(opts.home, `${this.name}.json`);
this.indent = opts.indent;
this.debounce = opts.debounce;
this.defaults = defaults || opts.default;
this.timeouts = {};
// Allow override of read and write methods
if (typeof options.readParseFile === 'function') {
this.readParseFile = options.readParseFile;
}
if (typeof options.writeFile === 'function') {
this.writeFile = options.writeFile;
}
}
/**
* Assign `value` to `key` and save to the file system. Can be a key-value pair,
* array of objects, or an object.
*
* ```js
* // key, value
* store.set('a', 'b');
* //=> {a: 'b'}
*
* // extend the store with an object
* store.set({a: 'b'});
* //=> {a: 'b'}
* ```
* @name .set
* @param {String} `key`
* @param {any} `val` The value to save to `key`. Must be a valid JSON type: String, Number, Array or Object.
* @return {Object} `Store` for chaining
* @api public
*/
set(key, val) {
if (typeof key === 'string' && typeof val === 'undefined') {
return this.del(key);
}
if (utils.isObject(key)) {
for (const k of Object.keys(key)) {
this.set(k.split(/\\?\./).join('\\.'), key[k]);
}
} else {
assert.equal(typeof key, 'string', 'expected key to be a string');
set(this.data, key, val);
}
this.save();
return this;
}
/**
* Assign `value` to `key` while retaining prior members of `value` if
* `value` is a map. If `value` is not a map, overwrites like `.set`.
*
* ```js
* store.set('a', { b: c });
* //=> {a: { b: c }}
*
* store.merge('a', { d: e });
* //=> {a: { b: c, d: e }}
*
* store.set('a', 'b');
* //=> {a: 'b'}
*
* store.merge('a', { c : 'd' });
* //=> {a: { c : 'd' }}
* ```
*
* @name .merge
* @param {String} `key`
* @param {any} `val` The value to merge to `key`. Must be a valid JSON type: String, Number, Array or Object.
* @return {Object} `Store` for chaining
* @api public
*/
merge(key, val) {
let oldVal = this.get(key);
if (oldVal && typeof oldVal === 'object' && !Array.isArray(oldVal)) {
val = Object.assign(this.get(key), val);
}
return this.set(key, val);
}
/**
* Add the given `value` to the array at `key`. Creates a new array if one
* doesn't exist, and only adds unique values to the array.
*
* ```js
* store.union('a', 'b');
* store.union('a', 'c');
* store.union('a', 'd');
* store.union('a', 'c');
* console.log(store.get('a'));
* //=> ['b', 'c', 'd']
* ```
* @name .union
* @param {String} `key`
* @param {any} `val` The value to union to `key`. Must be a valid JSON type: String, Number, Array or Object.
* @return {Object} `Store` for chaining
* @api public
*/
union(key, ...rest) {
assert.equal(typeof key, 'string', 'expected key to be a string');
const vals = this.get(key);
const values = [].concat(utils.isEmptyPrimitive(vals) ? [] : vals);
this.set(key, utils.unique(utils.flatten(...values, ...rest)));
return this;
}
/**
* Get the stored `value` of `key`.
*
* ```js
* store.set('a', {b: 'c'});
* store.get('a');
* //=> {b: 'c'}
*
* store.get();
* //=> {a: {b: 'c'}}
* ```
* @name .get
* @param {String} `key`
* @return {any} The value to store for `key`.
* @api public
*/
get(key, fallback) {
if (typeof key === 'undefined') {
return this.data;
}
assert.equal(typeof key, 'string', 'expected key to be a string');
const value = get(this.data, key);
if (typeof value === 'undefined') {
return fallback;
}
return value;
}
/**
* Returns `true` if the specified `key` has a value.
*
* ```js
* store.set('a', 42);
* store.set('c', null);
*
* store.has('a'); //=> true
* store.has('c'); //=> true
* store.has('d'); //=> false
* ```
* @name .has
* @param {String} `key`
* @return {Boolean} Returns true if `key` has
* @api public
*/
has(key) {
return typeof this.get(key) !== 'undefined';
}
/**
* Returns `true` if the specified `key` exists.
*
* ```js
* store.set('a', 'b');
* store.set('b', false);
* store.set('c', null);
* store.set('d', true);
* store.set('e', undefined);
*
* store.hasOwn('a'); //=> true
* store.hasOwn('b'); //=> true
* store.hasOwn('c'); //=> true
* store.hasOwn('d'); //=> true
* store.hasOwn('e'); //=> true
* store.hasOwn('foo'); //=> false
* ```
* @name .hasOwn
* @param {String} `key`
* @return {Boolean} Returns true if `key` exists
* @api public
*/
hasOwn(key) {
assert.equal(typeof key, 'string', 'expected key to be a string');
return utils.hasOwn(this.data, key);
}
/**
* Delete one or more properties from the store.
*
* ```js
* store.set('foo.bar', 'baz');
* console.log(store.data); //=> { foo: { bar: 'baz' } }
* store.del('foo.bar');
* console.log(store.data); //=> { foo: {} }
* store.del('foo');
* console.log(store.data); //=> {}
* ```
* @name .del
* @param {String|Array} `keys` One or more properties to delete.
* @api public
*/
del(key) {
if (Array.isArray(key)) {
for (const k of key) {
this.del(k);
}
return this;
}
assert.equal(typeof key, 'string', 'expected key to be a string, use .clear() to delete all properties');
if (utils.del(this.data, key)) {
this.save();
}
return this;
}
/**
* Return a clone of the `store.data` object.
*
* ```js
* console.log(store.clone());
* ```
* @name .clone
* @return {Object}
* @api public
*/
clone() {
return utils.cloneDeep(this.data);
}
/**
* Clear `store.data` to an empty object.
*
* ```js
* store.clear();
* ```
* @name .clear
* @return {undefined}
* @api public
*/
clear() {
this.data = {};
this.save();
}
/**
* Stringify the store. Takes the same arguments as `JSON.stringify`.
*
* ```js
* console.log(store.json(null, 2));
* ```
* @name .json
* @param {Function} `replacer` Replacer function.
* @param {String} `indent` Indentation to use. Default is 2 spaces.
* @return {String}
* @api public
*/
json(replacer = null, indent = this.indent) {
return JSON.stringify(this.data, replacer, indent);
}
/**
* Immediately write the store to the file system. This method should probably
* not be called directly. Unless you are familiar with the inner workings of
* the code it's recommended that you use .save() instead.
*
* ```js
* store.writeFile();
* ```
* @name .writeFile
* @return {undefined}
*/
writeFile() {
utils.mkdir(path.dirname(this.path));
fs.writeFileSync(this.path, this.json(), { mode: 0o0600 });
}
/**
* Calls [.writeFile()](#writefile) to persist the store to the file system,
* after an optional [debounce](#options) period. This method should probably
* not be called directly as it's used internally by other methods.
*
* ```js
* store.save();
* ```
* @name .save
* @return {undefined}
* @api public
*/
save() {
if (!this.debounce) {
return this.writeFile();
}
if (this.timeouts.save) {
clearTimeout(this.timeouts.save);
}
this.timeouts.save = setTimeout(this.writeFile.bind(this), this.debounce);
}
/**
* Delete the store from the file system.
*
* ```js
* store.unlink();
* ```
* @name .unlink
* @return {undefined}
* @api public
*/
unlink() {
clearTimeout(this.timeouts.save);
utils.tryUnlink(this.path);
}
/**
* Read and parse the data from the file system store. This method should
* probably not be called directly. Unless you are familiar with the inner
* workings of the code it's recommended that you use .load() instead.
*
* ```js
* data = store.readPraseFile();
* ```
* @name .readParseFile
* @return {Object}
*/
readParseFile() {
return JSON.parse(fs.readFileSync(this.path));
}
/**
* Load the store.
* @return {Object}
*/
load() {
try {
return (this[kData] = this.readParseFile());
} catch (err) {
if (err.code === 'EACCES') {
err.message += '\ndata-store does not have permission to load this file\n';
throw err;
}
// (re-)initialize if file doesn't exist or is corrupted
if (err.code === 'ENOENT' || err.name === 'SyntaxError') {
this[kData] = {};
return {};
}
}
}
/**
* Getter/setter for the `store.data` object, which holds the values
* that are persisted to the file system.
*
* ```js
* console.log(store.data); //=> {}
* store.data.foo = 'bar';
* console.log(store.get('foo')); //=> 'bar'
* ```
* @name .data
* @return {Object}
*/
set data(data) {
this[kData] = data;
this.save();
}
get data() {
let data = this[kData] || this.load();
if (!this.saved) {
data = { ...this.defaults, ...data };
}
this[kData] = data;
return data;
}
}
/**
* Expose `Store`
*/
module.exports = function(...args) {
return new Store(...args);
};
module.exports.Store = Store;