-
Notifications
You must be signed in to change notification settings - Fork 1
/
createMemoryStorage.js
85 lines (69 loc) · 1.74 KB
/
createMemoryStorage.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
// @flow
import fs from 'fs';
import {
NotFoundError,
} from '../errors';
import type {
StorageType,
} from '../types';
type ConfigurationType = {|
+storage?: Object,
|};
const formatUpload = (upload) => {
return {
uid: upload.uid,
uploadLength: upload.uploadLength,
uploadMetadata: upload.uploadMetadata,
uploadOffset: upload.uploadOffset,
};
};
export default (configuration?: ConfigurationType): StorageType => {
const storage = configuration && configuration.storage || {};
const getUpload = (uid) => {
const upload = storage[uid];
if (upload) {
return upload;
}
throw new NotFoundError();
};
const deleteUpload = (uid) => {
// eslint-disable-next-line fp/no-delete
delete storage[uid];
};
return {
createUpload: async (input) => {
storage[input.uid] = {
buffer: Buffer.alloc(input.uploadLength),
uid: input.uid,
uploadLength: input.uploadLength,
uploadMetadata: input.uploadMetadata || {},
uploadOffset: 0,
};
return formatUpload(getUpload(input.uid));
},
delete: (uid) => {
// Triggers error if upload does not exist.
if (getUpload(uid)) {
deleteUpload(uid);
}
},
getUpload: (uid) => {
const upload = getUpload(uid);
if (upload.uploadExpires && Date.now() > upload.uploadExpires) {
deleteUpload(uid);
// Triggers 404 error.
getUpload(uid);
}
return formatUpload(upload);
},
upload: (input) => {
const upload = getUpload(input.uid);
const buffer = fs.readFileSync(input.filePath);
buffer.copy(
upload.buffer,
upload.uploadOffset,
);
upload.uploadOffset += buffer.length;
},
};
};