-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathgithubObjectStorage.ts
More file actions
239 lines (187 loc) · 7.91 KB
/
githubObjectStorage.ts
File metadata and controls
239 lines (187 loc) · 7.91 KB
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
import * as Utils from "@paperbits/common";
import * as Objects from "@paperbits/common/objects";
import { Bag } from "@paperbits/common/bag";
import { IObjectStorage, Operator, OrderDirection, Query } from "@paperbits/common/persistence";
import { IGithubClient } from "./IGithubClient";
import { IGithubTreeItem } from "./IGithubTreeItem";
import { ISettingsProvider } from "@paperbits/common/configuration";
export class GithubObjectStorage implements IObjectStorage {
private loadDataPromise: Promise<Object>;
protected storageDataObject: Object;
private splitter: string = "/";
private pathToData: string;
constructor(
private readonly settingsProvider: ISettingsProvider,
private readonly githubClient: IGithubClient
) { }
protected async getData(): Promise<Object> {
if (this.loadDataPromise) {
return this.loadDataPromise;
}
this.loadDataPromise = new Promise<Object>(async (resolve) => {
const githubSettings = await this.settingsProvider.getSetting("github");
this.pathToData = githubSettings["pathToData"];
const response = await this.githubClient.getFileContent(this.pathToData);
this.storageDataObject = JSON.parse(atob(response.content));
resolve(this.storageDataObject);
});
return this.loadDataPromise;
}
public async addObject(path: string, dataObject: Object): Promise<void> {
if (path) {
const pathParts = path.split(this.splitter);
const mainNode = pathParts[0];
if (pathParts.length === 1 || (pathParts.length === 2 && !pathParts[1])) {
this.storageDataObject[mainNode] = dataObject;
}
else {
if (!this.storageDataObject.hasOwnProperty(mainNode)) {
this.storageDataObject[mainNode] = {};
}
this.storageDataObject[mainNode][pathParts[1]] = dataObject;
}
}
else {
Object.keys(dataObject).forEach(prop => {
const obj = dataObject[prop];
const pathParts = prop.split(this.splitter);
const mainNode = pathParts[0];
if (pathParts.length === 1 || (pathParts.length === 2 && !pathParts[1])) {
this.storageDataObject[mainNode] = obj;
}
else {
if (!this.storageDataObject.hasOwnProperty(mainNode)) {
this.storageDataObject[mainNode] = {};
}
this.storageDataObject[mainNode][pathParts[1]] = obj;
}
});
}
}
public async getObject<T>(path: string): Promise<T> {
const data = await this.getData();
return Objects.getObjectAt(path, Objects.clone(data));
}
public async deleteObject(path: string): Promise<void> {
if (!path) {
return;
}
Objects.deleteNodeAt(path, this.storageDataObject);
}
public async updateObject<T>(path: string, dataObject: T): Promise<void> {
if (!path) {
return;
}
const clone: any = Objects.clone(dataObject);
Objects.setValue(path, this.storageDataObject, clone);
Objects.cleanupObject(clone); // Ensure all "undefined" are cleaned up
}
public async searchObjects<T>(path: string, query: Query<T>): Promise<Bag<T>> {
const searchResultObject: Bag<T> = {};
const data = await this.getData();
if (!data) {
return searchResultObject;
}
const searchObj = Objects.getObjectAt(path, data);
if (!searchObj) {
return {};
}
let collection = Object.values(searchObj);
if (query) {
if (query.filters.length > 0) {
collection = collection.filter(x => {
let meetsCriteria = true;
for (const filter of query.filters) {
let left = Objects.getObjectAt<any>(filter.left, x);
let right = filter.right;
if (left === undefined) {
meetsCriteria = false;
continue;
}
if (typeof left === "string") {
left = left.toUpperCase();
}
if (typeof right === "string") {
right = right.toUpperCase();
}
const operator = filter.operator;
switch (operator) {
case Operator.contains:
if (left && !left.includes(right)) {
meetsCriteria = false;
}
break;
case Operator.equals:
if (left !== right) {
meetsCriteria = false;
}
break;
default:
throw new Error("Cannot translate operator into Firebase Realtime Database query.");
}
}
return meetsCriteria;
});
}
if (query.orderingBy) {
const property = query.orderingBy;
collection = collection.sort((x, y) => {
const a = Objects.getObjectAt<any>(property, x);
const b = Objects.getObjectAt<any>(property, y);
const modifier = query.orderDirection === OrderDirection.accending ? 1 : -1;
if (a > b) {
return modifier;
}
if (a < b) {
return -modifier;
}
return 0;
});
}
}
collection.forEach(item => {
const segments = item.key.split("/");
const key = segments[1];
Objects.setValue(key, searchResultObject, item);
Objects.cleanupObject(item); // Ensure all "undefined" are cleaned up
});
return searchResultObject;
}
private async createChangesTree(): Promise<IGithubTreeItem[]> {
const newTree = new Array<IGithubTreeItem>();
const content = Utils.stringToUnit8Array(JSON.stringify(this.storageDataObject));
const response = await this.githubClient.createBlob(this.pathToData, content);
const newTreeItem: IGithubTreeItem = {
path: this.pathToData,
sha: response.sha
};
newTree.push(newTreeItem);
return newTree;
}
public async saveChanges(delta: Object): Promise<void> {
const saveTasks = [];
const keys = [];
Object.keys(delta).map(key => {
const firstLevelObject = delta[key];
Object.keys(firstLevelObject).forEach(subkey => {
keys.push(`${key}/${subkey}`);
});
});
keys.forEach(key => {
const changeObject = Objects.getObjectAt(key, delta);
if (changeObject) {
saveTasks.push(this.updateObject(key, changeObject));
}
else {
saveTasks.push(this.deleteObject(key));
}
});
await Promise.all(saveTasks);
const newTree = await this.createChangesTree();
const lastCommit = await this.githubClient.getLatestCommit();
const tree = await this.githubClient.createTree(lastCommit.tree.sha, newTree);
const message = `Updating website content.`;
const commit = await this.githubClient.createCommit(lastCommit.sha, tree.sha, message);
await this.githubClient.updateReference("master", commit.sha);
}
}