-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstorage.js
70 lines (54 loc) · 1.23 KB
/
storage.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 fs = require( 'fs' );
class Storage {
constructor( fileName, initialData ) {
this.fileName = fileName;
this.data = initialData
}
save() {
return new Promise( ( resolve, reject ) => {
fs.writeFile( __dirname + '/' + this.fileName, JSON.stringify( this.data ), 'utf8', ( error ) => {
if ( error ) {
return reject( error );
}
resolve();
} );
} )
}
}
class StorageRepository {
/**
* @param {String} location Location of repositories
*/
constructor( location ) {
// TODO: node6 add default parameter
if ( !location ) {
location = '../data/';
}
this._location = location;
this._storageRepository = {};
}
createStorage( name, initialState ) {
// TODO: node6 add default parameter
if ( !initialState ) {
initialState = {}
}
const fileName = this._location + name + '.json';
let data;
try {
data = require( fileName );
} catch ( err ) {
data = initialState;
}
const storage = new Storage( fileName, data );
this._storageRepository[ name ] = storage;
return storage;
}
hasStorage( name ) {
return !!this._storageRepository[ name ];
}
getStorage( name ) {
return this._storageRepository[ name ];
}
}
module.exports = StorageRepository;