-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstorage.js
98 lines (83 loc) · 1.83 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
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
/*
* storage.js
*
* storage.js manages different kinds of storage. The Storage class expects a
* settings.storage object. The settings object always contains the 'type'
* attribute. This is used to define the backend (e.g. LocalFileStorage or S3).
*
* Example:
* new Storage({'type': 'LocalFileStorage'})
*/
var fs = require('fs');
var settings = require('./settings');
/*
* Storage
*
* storage object parameter:
* {
* 'type': 'LocalFileStorage',
* etc.
* }
*/
class Storage {
constructor(storage) {
try {
this.storage = eval(`new ${storage.type}(storage)`);
} catch (error) {
throw(new Error(`Storage class ${storage.type} does not exist`));
}
}
open(file) {
return this.storage.open(file);
}
save(file, content) {
return this.storage.save(file, content);
}
exists(file) {
return this.storage.exists(file);
}
delete(file) {
return this.storage.delete(file);
}
}
/*
* LocalFileStorage
*
* config object parameter:
* {
* 'location': '/tmp'
* }
*/
class LocalFileStorage {
constructor(config) {
this.location = config.location;
}
open(file) {
if (typeof file == 'undefined') {
throw(new Error('No file specified.'));
}
const fileLocation = `${this.location}/${file}`;
if (this.exists(fileLocation)) {
return fs.createReadStream(fileLocation);
}
throw `Unable to open ${fileLocation}.`
}
exists(file) {
return fs.existsSync(file);
}
save(file, content) {
if (typeof file == 'undefined') {
throw(new Error('No file specified.'));
}
const fileLocation = `${this.location}/${file}`;
fs.writeFileSync(fileLocation, content);
}
delete(file) {
fs.unlink(file, error => {
if (error) {
throw error;
}
})
}
}
module.exports = new Storage(settings.storage)