-
Notifications
You must be signed in to change notification settings - Fork 3
/
file.ts
258 lines (239 loc) · 6.15 KB
/
file.ts
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
import * as fs from "fs";
import * as path from "path";
import { CoreModel, FilterAttributes } from "../models/coremodel";
import { JSONUtils } from "../utils/serializers";
import { Store, StoreFindResult, StoreNotFoundError, StoreParameters } from "./store";
import { WebdaQL } from "./webdaql/query";
class FileStoreParameters extends StoreParameters {
/**
* Local path where to store all `json` files
*/
folder: string;
/**
* Parameter sent to JSON.stringify when storing the json
*/
beautify?: string | number;
/**
* Disable memory cache
*
* Useful if several process update storage files
*
* @default false
*/
noCache?: boolean;
}
/**
* Simple file storage of object
*
* Storage structure
* /folder/{uuid}
*
*
* Parameters:
* folder: to store to
*
* @category CoreServices
* @WebdaModda
*/
class FileStore<T extends CoreModel, K extends FileStoreParameters = FileStoreParameters> extends Store<T, K> {
static EXTENSION = ".json";
/**
* Load the parameters for a service
*/
loadParameters(params: any): FileStoreParameters {
return new FileStoreParameters(params, this);
}
/**
* Create the storage folder if does not exist
*/
computeParameters() {
super.computeParameters();
if (!fs.existsSync(this.parameters.folder)) {
fs.mkdirSync(this.parameters.folder);
}
}
/**
* Get the file path of an object
* @param uid of the object
* @returns
*/
file(uid) {
return `${this.parameters.folder}/${uid}${FileStore.EXTENSION}`;
}
/**
* @override
*/
async _exists(uid) {
return fs.existsSync(this.file(uid));
}
/**
* @override
*/
async find(query: WebdaQL.Query): Promise<StoreFindResult<T>> {
const files = fs
.readdirSync(this.parameters.folder)
.filter(file => {
return !fs.statSync(path.join(this.parameters.folder, file)).isDirectory();
})
.map(f => f.substring(0, f.length - FileStore.EXTENSION.length))
.sort();
return this.simulateFind(query, files);
}
/**
* @override
*/
async _save(object: T) {
fs.writeFileSync(
this.file(object.getUuid()),
JSON.stringify(object.toStoredJSON(), undefined, this.parameters.beautify)
);
return object;
}
/**
* @inheritdoc
*/
async _upsertItemToCollection(
uid: string,
prop: string,
item: any,
index: number,
itemWriteCondition: any,
itemWriteConditionField: string,
updateDate: Date
) {
try {
// Need to keep sync to avoid conflicts
return await this.simulateUpsertItemToCollection(
this.initModel(JSONUtils.loadFile(this.file(uid))),
<FilterAttributes<T, any[]>>prop,
item,
updateDate,
index,
itemWriteCondition,
itemWriteConditionField
);
} catch (err) {
throw new StoreNotFoundError(uid, this.getName());
}
}
/**
* @inheritdoc
*/
async _removeAttribute(uuid: string, attribute: string, writeCondition?: any, writeConditionField?: string) {
let res = await this._get(uuid, true);
this.checkUpdateCondition(res, <keyof T>writeConditionField, writeCondition);
delete res[attribute];
await this._save(res);
}
/**
* @inheritdoc
*/
async _deleteItemFromCollection(
uid: string,
prop: string,
index: number,
itemWriteCondition: any,
itemWriteConditionField: string,
updateDate: Date
) {
let res = await this._get(uid, true);
this.checkCollectionUpdateCondition(
res,
<FilterAttributes<T, any[]>>prop,
<keyof T>itemWriteConditionField,
itemWriteCondition,
index
);
res[prop].splice(index, 1);
res._lastUpdate = updateDate;
return this._save(res);
}
/**
* @inheritdoc
*/
async _delete(uid: string) {
const filePath = this.file(uid);
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
}
}
/**
* @inheritdoc
*/
async _patch(object: any, uid: string, writeCondition?: any, writeConditionField?: string): Promise<any> {
let stored = await this._get(uid, true);
this.checkUpdateCondition(stored, <keyof T>writeConditionField, writeCondition);
for (let prop in object) {
stored[prop] = object[prop];
}
return this._save(stored);
}
/**
* @override
*/
async _update(object: any, uid: string, writeCondition?: any, writeConditionField?: string): Promise<any> {
let stored = await this._get(uid, true);
this.checkUpdateCondition(stored, <keyof T>writeConditionField, writeCondition);
return this._save(this.initModel(object));
}
/**
* @override
*/
async getAll(uids?: string[]): Promise<any> {
if (!uids) {
uids = [];
let files = fs.readdirSync(this.parameters.folder);
for (let file in files) {
uids.push(files[file].substring(0, files[file].length - FileStore.EXTENSION.length));
}
}
let result = [];
for (let i in uids) {
let model = this._get(uids[i]);
result.push(model);
}
return (await Promise.all(result)).filter(f => f !== undefined);
}
/**
* @override
*/
async _get(uid: string, raiseIfNotFound: boolean = false): Promise<T> {
let res = await this.exists(uid);
if (res) {
let data = JSON.parse(fs.readFileSync(this.file(uid)).toString());
if (data.__type !== this._modelType && this.parameters.strict) {
return undefined;
}
return this.initModel(data);
} else if (raiseIfNotFound) {
throw new StoreNotFoundError(uid, this.getName());
}
}
/**
* @override
*/
async _incrementAttributes(
uid: string,
params: { property: string; value: number }[],
updateDate: Date
): Promise<any> {
let stored = await this._get(uid, true);
params.forEach(({ property: prop, value }) => {
if (stored[prop] === undefined) {
stored[prop] = 0;
}
stored._lastUpdate = updateDate;
stored[prop] += value;
});
stored._lastUpdate = updateDate;
return this._save(stored);
}
/**
* @override
*/
async __clean(): Promise<void> {
// This is only during test
(await import("fs-extra")).emptyDirSync(this.parameters.folder);
}
}
export { FileStore };