forked from calzoneman/sync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilestore.js
78 lines (70 loc) · 2.37 KB
/
filestore.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
import Promise from 'bluebird';
import { stat } from 'fs';
import * as fs from 'graceful-fs';
import path from 'path';
import { ChannelStateSizeError } from '../errors';
const readFileAsync = Promise.promisify(fs.readFile);
const writeFileAsync = Promise.promisify(fs.writeFile);
const readdirAsync = Promise.promisify(fs.readdir);
const statAsync = Promise.promisify(stat);
const SIZE_LIMIT = 1048576;
const CHANDUMP_DIR = path.resolve(__dirname, '..', '..', 'chandump');
export class FileStore {
filenameForChannel(channelName) {
return path.join(CHANDUMP_DIR, channelName);
}
load(id, channelName) {
const filename = this.filenameForChannel(channelName);
return statAsync(filename).then(stats => {
if (stats.size > SIZE_LIMIT) {
return Promise.reject(
new ChannelStateSizeError(
'Channel state file is too large',
{
limit: SIZE_LIMIT,
actual: stats.size
}
)
);
} else {
return readFileAsync(filename);
}
}).then(fileContents => {
try {
return JSON.parse(fileContents);
} catch (e) {
return Promise.reject(new Error('Channel state file is not valid JSON: ' + e));
}
});
}
async save(id, channelName, data) {
let original;
try {
original = await this.load(id, channelName);
} catch (error) {
if (error.code !== 'ENOENT') {
throw error;
} else {
original = {};
}
}
Object.keys(data).forEach(key => {
original[key] = data[key];
});
const filename = this.filenameForChannel(channelName);
const fileContents = new Buffer(JSON.stringify(original), 'utf8');
if (fileContents.length > SIZE_LIMIT) {
throw new ChannelStateSizeError(
'Channel state size is too large',
{
limit: SIZE_LIMIT,
actual: fileContents.length
}
);
}
return await writeFileAsync(filename, fileContents);
}
listChannels() {
return readdirAsync(CHANDUMP_DIR);
}
}