-
Notifications
You must be signed in to change notification settings - Fork 21
/
index.ts
216 lines (182 loc) · 6.68 KB
/
index.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
/*
* Wire
* Copyright (C) 2018 Wire Swiss GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
*/
import {CRUDEngine, error as StoreEngineError} from '@wireapp/store-engine';
import * as fs from 'bro-fs';
import * as path from 'path';
export interface FileSystemEngineOptions {
fileExtension: string;
size: number;
type: number;
}
const TEN_MEGABYTES = 1024 * 1024 * 10;
export class FileSystemEngine implements CRUDEngine {
public storeName = '';
private autoIncrementedPrimaryKey: number = 1;
private config: FileSystemEngineOptions = {
fileExtension: '.dat',
size: TEN_MEGABYTES,
type: typeof window === 'undefined' ? 0 : window.TEMPORARY,
};
constructor() {}
async isSupported(): Promise<void> {
if (typeof window === 'undefined' || !fs.isSupported()) {
const message = `File and Directory Entries API is not available on your platform.`;
throw new StoreEngineError.UnsupportedError(message);
}
}
async init(storeName = '', options?: FileSystemEngineOptions): Promise<FileSystem> {
await this.isSupported();
this.config = {...this.config, ...options};
this.storeName = storeName;
const fileSystem: FileSystem = await fs.init({type: this.config.type, bytes: this.config.size});
await fs.mkdir(this.storeName);
return fileSystem;
}
public async clearTables(): Promise<void> {
const files = await fs.readdir(this.storeName);
const tableNames = files.map(file => path.join(this.storeName, file.name));
await Promise.all(tableNames.map(tableName => this.deleteAll(tableName)));
}
private createDirectoryPath(tableName: string): string {
return `${this.storeName}/${tableName}`;
}
private createFilePath<PrimaryKey = string>(tableName: string, primaryKey: PrimaryKey): string {
const directory = this.createDirectoryPath(tableName);
return `${directory}/${primaryKey}${this.config.fileExtension}`;
}
async create<EntityType = Object, PrimaryKey = string>(
tableName: string,
primaryKey: PrimaryKey,
entity: EntityType,
): Promise<PrimaryKey> {
if (!entity) {
const message = `Record "${primaryKey}" cannot be saved in "${tableName}" because it's "undefined" or "null".`;
throw new StoreEngineError.RecordTypeError(message);
}
if (primaryKey === undefined) {
primaryKey = (this.autoIncrementedPrimaryKey as unknown) as PrimaryKey;
this.autoIncrementedPrimaryKey += 1;
}
const filePath = this.createFilePath(tableName, primaryKey);
const isExistent = await fs.exists(filePath);
if (isExistent) {
const message = `Record "${primaryKey}" already exists in "${tableName}". You need to delete the record first if you want to overwrite it.`;
throw new StoreEngineError.RecordAlreadyExistsError(message);
} else {
let data: string;
try {
data = JSON.stringify(entity);
} catch (error) {
data = String(entity);
}
await fs.writeFile(filePath, data);
return primaryKey;
}
}
async delete<PrimaryKey = string>(tableName: string, primaryKey: PrimaryKey): Promise<PrimaryKey> {
const filePath = this.createFilePath(tableName, primaryKey);
await fs.unlink(filePath);
return primaryKey;
}
async deleteAll(tableName: string): Promise<boolean> {
const primaryKeys = await this.readAllPrimaryKeys(tableName);
const promises = primaryKeys.map(primaryKey => this.delete(tableName, primaryKey));
try {
await Promise.all(promises);
return true;
} catch (error) {
return false;
}
}
async read<EntityType = Object, PrimaryKey = string>(tableName: string, primaryKey: PrimaryKey): Promise<EntityType> {
const filePath = this.createFilePath(tableName, primaryKey);
let data: string;
try {
data = await fs.readFile(filePath, {type: 'Text'});
} catch (error) {
const message = `Record "${primaryKey}" in "${tableName}" could not be found.`;
throw new StoreEngineError.RecordNotFoundError(message);
}
try {
const parsed = JSON.parse(data);
return parsed;
} catch (error) {
return data as any;
}
}
async readAll<T>(tableName: string): Promise<T[]> {
const primaryKeys = await this.readAllPrimaryKeys(tableName);
const promises: Promise<T>[] = [];
for (const primaryKey of primaryKeys) {
promises.push(this.read(tableName, primaryKey));
}
return Promise.all(promises);
}
async readAllPrimaryKeys(tableName: string): Promise<string[]> {
const directoryPath = this.createDirectoryPath(tableName);
let entries: FileEntry[];
try {
entries = await fs.readdir(directoryPath, {deep: true});
} catch (error) {
entries = [];
}
const names = entries.map((entry: FileEntry) => `${entry.name}`);
const primaryKeys: string[] = [];
for (const name of names.sort()) {
const nameWithoutExtension = name.substr(0, name.indexOf('.'));
primaryKeys.push(nameWithoutExtension);
}
return primaryKeys;
}
async update<PrimaryKey = string, ChangesType = Object>(
tableName: string,
primaryKey: PrimaryKey,
changes: ChangesType,
): Promise<PrimaryKey> {
const filePath = this.createFilePath(tableName, primaryKey);
let record = await this.read(tableName, primaryKey);
if (typeof record === 'string') {
record = JSON.parse(record);
}
const updatedRecord: Object = {...record, ...changes};
const updatedRecord_1 = JSON.stringify(updatedRecord);
await fs.writeFile(filePath, updatedRecord_1);
return primaryKey;
}
async purge(): Promise<void> {
await fs.rmdir(this.storeName);
}
async updateOrCreate<PrimaryKey = string, ChangesType = Object>(
tableName: string,
primaryKey: PrimaryKey,
changes: ChangesType,
): Promise<PrimaryKey> {
let internalPrimaryKey;
try {
internalPrimaryKey = await this.update(tableName, primaryKey, changes);
} catch (error) {
if (error instanceof StoreEngineError.RecordNotFoundError) {
internalPrimaryKey = await this.create(tableName, primaryKey, changes);
} else {
throw error;
}
}
return internalPrimaryKey;
}
}