-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathservice.ts
More file actions
384 lines (323 loc) 路 14.1 KB
/
Copy pathservice.ts
File metadata and controls
384 lines (323 loc) 路 14.1 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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
import { map } from 'rxjs/operators';
import { Core } from './core';
import { IBuildedParamsCollection } from './interfaces/params-collection';
import { Base } from './services/base';
import { Resource } from './resource';
import { PathBuilder } from './services/path-builder';
import { Converter } from './services/converter';
import { CacheMemory } from './services/cachememory';
import { IParamsCollection, IParamsResource, IAttributes } from './interfaces';
import { DocumentCollection } from './document-collection';
import { isLive, relationshipsAreBuilded } from './common';
import { Observable, BehaviorSubject, Subject } from 'rxjs';
import { ICacheableDocumentResource, IDocumentResource } from './interfaces/data-object';
import { PathCollectionBuilder } from './services/path-collection-builder';
import { IDataCollection, ICacheableDataCollection } from './interfaces/data-collection';
import { ClonedResource } from './cloned-resource';
export class Service<R extends Resource = Resource> {
public type: string;
public resource: typeof Resource = Resource;
public collections_ttl: number;
protected path: string; // without slashes
public constructor() {
setTimeout(() => this.register());
}
/*
Register service on Core
@return true if the resource don't exist and registered ok
*/
public register(): Service<R> | false {
if (Core.me === null) {
throw new Error('Error: you are trying register `' + this.type + '` before inject JsonapiCore somewhere, almost one time.');
}
return Core.me.registerService<R>(this);
}
/**
* @deprecated since 2.2.0. Use new() method.
*/
public newResource(): R {
return this.new();
}
public newCollection(): DocumentCollection<R> {
return new DocumentCollection();
}
public new(): R {
let resource: Resource = new this.resource();
resource.type = this.type;
// issue #36: just if service is not registered yet.
this.getService();
resource.reset();
return <R>resource;
}
public getPrePath(): string {
return '';
}
public getPath(): string {
return this.path || this.type;
}
public getClone(id: string, params: IParamsResource = {}): Observable<ClonedResource<R>> {
return this.get(id, params).pipe(
map((resource: R) => {
// return resource.clone();
return new ClonedResource(resource);
})
);
}
// if you change this logic, maybe you need to change all()
public get(id: string, params: IParamsResource = {}): Observable<R> {
params = { ...Base.ParamsResource, ...params };
let path: PathBuilder = new PathBuilder();
path.applyParams(this, params);
path.appendPath(id);
let resource: R = this.getOrCreateResource(id);
resource.setLoaded(false);
let subject: BehaviorSubject<R> = new BehaviorSubject<R>(resource);
if (Object.keys(params.fields || []).length > 0) {
// memory/store cache doesnt support fields
this.getGetFromServer(path, resource, subject);
} else if (isLive(resource, params.ttl) && relationshipsAreBuilded(resource, params.include || [])) {
// data on memory and its live
resource.setLoaded(true);
setTimeout(() => subject.complete(), 0);
} else if (resource.cache_last_update === 0) {
// we dont have any data on memory
this.getGetFromLocal(params, path, resource)
.then(() => {
subject.next(resource);
setTimeout(() => subject.complete(), 0);
})
.catch(() => {
resource.setLoaded(false);
this.getGetFromServer(path, resource, subject);
});
} else {
this.getGetFromServer(path, resource, subject);
}
return subject.asObservable();
}
// if you change this logic, maybe you need to change getAllFromLocal()
private async getGetFromLocal(params: IParamsCollection = {}, path: PathBuilder, resource: R): Promise<void> {
// STORE
if (!Core.injectedServices.json_ripper.enabled) {
throw new Error('We cant handle this request');
}
resource.setLoaded(false);
// STORE (individual)
let success: ICacheableDocumentResource = await Core.injectedServices.json_ripper.getResourceByResource(resource, path.includes);
resource.fill(success);
resource.setSource('store');
// when fields is set, get resource form server
if (isLive(resource, params.ttl)) {
resource.setLoadedAndPropagate(true);
// resource.setBuildedAndPropagate(true);
return;
}
throw new Error('Resource is dead!');
}
// if you change this logic, maybe you need to change getAllFromServer()
protected getGetFromServer(path: any, resource: R, subject: Subject<R>): void {
Core.get(path.get()).subscribe(
success => {
resource.fill(<IDocumentResource>success);
resource.cache_last_update = Date.now();
resource.setLoadedAndPropagate(true);
resource.setSourceAndPropagate('server');
// this.getService().cachememory.setResource(resource, true);
Core.injectedServices.json_ripper.saveResource(resource, path.includes);
subject.next(resource);
setTimeout(() => subject.complete(), 0);
},
error => {
resource.setLoadedAndPropagate(true);
subject.next(resource);
subject.error(error);
}
);
}
public getService<T extends Service<R>>(): T {
return <T>(Converter.getService(this.type) || this.register());
}
public getOrCreateCollection(path: PathCollectionBuilder): DocumentCollection<R> {
const service: Service<R> = this.getService();
const collection: DocumentCollection<R> = <DocumentCollection<R>>(
CacheMemory.getInstance().getOrCreateCollection(path.getForCache())
);
collection.ttl = service.collections_ttl;
if (collection.source !== 'new') {
collection.source = 'memory';
}
return collection;
}
public getOrCreateResource(id: string): R {
let service: Service = Converter.getServiceOrFail(this.type);
let resource: R;
resource = <R>CacheMemory.getInstance().getResource(this.type, id);
if (resource === null) {
resource = <R>service.new();
resource.id = id;
CacheMemory.getInstance().setResource(resource, false);
}
if (resource.source !== 'new') {
resource.source = 'memory';
}
return resource;
}
public createResource(id: string): R {
let service: Service = Converter.getServiceOrFail(this.type);
let resource: Resource = service.new();
resource.id = id;
CacheMemory.getInstance().setResource(resource, false);
return <R>resource;
}
/**
* deprecated since 2.2
*/
public async clearCacheMemory(): Promise<boolean> {
return this.clearCache();
}
public async clearCache(): Promise<boolean> {
let path: PathBuilder = new PathBuilder();
path.applyParams(this);
// @todo this code is repeated on core.clearCache()
CacheMemory.getInstance().deprecateCollections(path.getForCache());
return Core.injectedServices.json_ripper.deprecateCollection(path.getForCache()).then(() => true);
}
public parseToServer(attributes: IAttributes): void {
/* */
}
public parseFromServer(attributes: IAttributes): void {
/* */
}
public delete(id: string, params?: Object): Observable<void> {
params = { ...{}, ...Base.ParamsResource, ...params };
// http request
let path: PathBuilder = new PathBuilder();
path.applyParams(this, params);
path.appendPath(id);
let subject: Subject<void> = new Subject<void>();
Core.delete(path.get()).subscribe(
success => {
CacheMemory.getInstance().removeResource(this.type, id);
subject.next();
subject.complete();
},
error => {
subject.error(error);
}
);
return subject.asObservable();
}
// if you change this logic, maybe you need to change get()
public all(params: IParamsCollection = {}): Observable<DocumentCollection<R>> {
let builded_params: IBuildedParamsCollection = { ...Base.ParamsCollection, ...params };
if (!builded_params.ttl && builded_params.ttl !== 0) {
builded_params.ttl = this.collections_ttl;
}
let path: PathCollectionBuilder = new PathCollectionBuilder();
path.applyParams(this, builded_params);
let temporary_collection: DocumentCollection<R> = this.getOrCreateCollection(path);
// eslint-disable-next-line id-blacklist
temporary_collection.page.number = builded_params.page.number * 1;
let subject: BehaviorSubject<DocumentCollection<R>> = new BehaviorSubject<DocumentCollection<R>>(temporary_collection);
if (Object.keys(builded_params.fields).length > 0) {
// memory/store cache dont suppont fields
this.getAllFromServer(path, builded_params, temporary_collection, subject);
} else if (isLive(temporary_collection, builded_params.ttl)) {
// data on memory and its live
setTimeout(() => subject.complete(), 0);
} else if (temporary_collection.cache_last_update === 0) {
// we dont have any data on memory
temporary_collection.source = 'new';
this.getAllFromLocal(builded_params, path, temporary_collection)
.then(() => {
subject.next(temporary_collection);
setTimeout(() => {
subject.complete();
}, 0);
})
.catch(() => {
temporary_collection.setLoaded(false);
this.getAllFromServer(path, builded_params, temporary_collection, subject);
});
} else {
this.getAllFromServer(path, builded_params, temporary_collection, subject);
}
return subject.asObservable();
}
// if you change this logic, maybe you need to change getGetFromLocal()
private async getAllFromLocal(
params: IParamsCollection = {},
path: PathCollectionBuilder,
temporary_collection: DocumentCollection<R>
): Promise<void> {
// STORE
if (!Core.injectedServices.json_ripper.enabled) {
throw new Error('We cant handle this request');
}
temporary_collection.setLoaded(false);
let success: ICacheableDataCollection;
if (params.store_cache_method === 'compact') {
// STORE (compact)
success = await Core.injectedServices.JsonapiStoreService.getDataObject('collection', path.getForCache() + '.compact');
} else {
// STORE (individual)
success = await Core.injectedServices.json_ripper.getCollection(path.getForCache(), path.includes);
}
temporary_collection.fill(success);
temporary_collection.setSourceAndPropagate('store');
// when fields is set, get resource form server
if (isLive(temporary_collection, params.ttl)) {
temporary_collection.setLoadedAndPropagate(true);
temporary_collection.setBuildedAndPropagate(true);
return;
}
throw new Error('Collection is dead!');
}
// if you change this logic, maybe you need to change getGetFromServer()
protected getAllFromServer(
path: PathBuilder,
params: IParamsCollection,
temporary_collection: DocumentCollection<R>,
subject: BehaviorSubject<DocumentCollection<R>>
): void {
temporary_collection.setLoaded(false);
let old_time = Date.now()
Core.get(path.get()).subscribe(
success => {
console.log('Tiempo de espera en el metodo all ---->', (Date.now() - old_time))
// this create a new ID for every resource (for caching proposes)
// for example, two URL return same objects but with different attributes
if (params.cachehash) {
Object.keys(success.data).forEach((key): void => {
let resource: any = success.data[key];
// eslint-disable-next-line
resource.id = resource.id + params.cachehash;
});
}
temporary_collection.fill(<IDataCollection>success);
temporary_collection.cache_last_update = Date.now();
temporary_collection.setCacheLastUpdateAndPropagate();
temporary_collection.setSourceAndPropagate('server');
temporary_collection.setLoadedAndPropagate(true);
// this.getService().cachememory.setCollection(path.getForCache(), temporary_collection);
if (Core.injectedServices.json_ripper.enabled) {
Core.injectedServices.json_ripper.saveCollection(path.getForCache(), temporary_collection, path.includes);
if (params.store_cache_method === 'compact') {
// @todo migrate to dexie
Core.injectedServices.JsonapiStoreService.saveCollection(
path.getForCache() + '.compact',
<ICacheableDataCollection>success
);
}
}
subject.next(temporary_collection);
setTimeout(() => subject.complete(), 0);
},
error => {
temporary_collection.setLoadedAndPropagate(true);
subject.next(temporary_collection);
subject.error(error);
}
);
}
}