Commit 55624abd authored by Guillaume Perréal's avatar Guillaume Perréal
Browse files

Début de mise en place de la partie Typescript.

parent f7383beb
/vendor
/composer.lock
/dist
/node_modules
.php_cs.*cache
.idea
File suppressed by a .gitattributes entry or the file's encoding is unsupported.
{
"name": "irstea-ng-model",
"version": "1.0.0",
"description": "Runtime libray for the composer package irstea/ng-model-generator-bundle.",
"main": "dist/index.js",
"directories": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git@gitlab-ssh.irstea.fr:pole-is/bundles/ng-model-generator-bundle.git"
},
"keywords": [
"angular",
"api-platform"
],
"author": "Irstea - pôle IS",
"license": "LGPL-3.0-or-later",
"peerDependencies": {
"@angular/common": "^7.2.9",
"@angular/core": "^7.2.9"
},
"dependencies": {
"lodash": "^4.17.11",
"rxjs": "^6.4.0",
"rxjs-etc": "^9.4.0"
},
"devDependencies": {
"@angular/common": "^7.2.9",
"@angular/core": "^7.2.9",
"irstea-typescript-config": "^1.0.3",
"prettier": "^1.16.4",
"prettier-tslint": "^0.4.2",
"rxjs-marbles": "^5.0.0",
"rxjs-tslint-rules": "^4.18.2",
"tslint": "^5.14.0",
"tslint-config-prettier": "^1.18.0",
"tslint-plugin-prettier": "^2.0.1",
"typescript": "^3.3.3333",
"zone.js": "~0.8.26"
}
}
import { HttpHeaderResponse } from '@angular/common/http';
import { inject, TestBed } from '@angular/core/testing';
import * as _ from 'lodash';
import { forkJoin, Observable } from 'rxjs';
import { catchError, map, mergeMap } from 'rxjs/operators';
import { MarbleTestScheduler } from '../../../testing/marbles';
import { Collection, IRI, IRI_PROPERTY, Resource } from '../../shared/models';
import { safeForkJoin } from '../../shared/rxjs';
import { IRIMismatchError, MissingIRIError, ResourceCache, ValueHolder } from './cache.service';
describe('cache.service', () => {
interface MyResource extends Resource {
readonly '@id': IRI<MyResource>;
readonly '@type': 'MyResource';
value: string;
value2?: string;
}
function iri(x: string): IRI<MyResource> {
return x as any;
}
const MY_IRI = iri('/bla/a');
const OTHER_IRI = iri('/bla/B');
const VALUES: { [name: string]: MyResource } = {
a: { '@id': MY_IRI, '@type': 'MyResource', value: 'foo' },
b: { '@id': MY_IRI, '@type': 'MyResource', value: 'bar' },
c: { '@id': MY_IRI, '@type': 'MyResource', value: 'bar', value2: 'quz' },
d: { '@id': OTHER_IRI, '@type': 'MyResource', value: 'zig' },
};
let scheduler: MarbleTestScheduler<any>;
beforeEach(() => {
scheduler = MarbleTestScheduler.create(VALUES, 'error');
});
describe('ValueHolder', () => {
let holder: ValueHolder<any>;
beforeEach(() => {
holder = new ValueHolder<MyResource>(iri('/bla/a'));
});
it('should be created', () => {
expect(holder).toBeTruthy();
});
describe('.set()', () => {
function testSet({ value, error, SET_M }: any) {
scheduler.withError(error).run(({ expectObservable }) => {
expectObservable(holder.set(value)).toBe(SET_M);
});
}
it('should provide the value', () =>
testSet({
value: VALUES.a,
SET_M: '(a|)',
}));
it(`should refuse value without ${IRI_PROPERTY}`, () =>
testSet({
value: {},
error: new MissingIRIError(),
SET_M: '#',
}));
it('should refuse value with different @id', () =>
testSet({
value: { '@id': iri('bar') },
error: new IRIMismatchError(MY_IRI, iri('bar')),
SET_M: '#',
}));
it('should always points to the same instance', () => {
forkJoin(holder.set(VALUES.a), holder.set(VALUES.b)).subscribe(([a, b]: MyResource[]) => {
expect(a).toBe(b);
});
});
});
describe('.update()', () => {
it('should provide the value from the server', () =>
scheduler.run(({ cold, expectObservable }) => {
const REQ_M = '---a|';
const UPD_M = '--(a|) ';
const request$ = cold(REQ_M);
expectObservable(holder.update(request$)).toBe(UPD_M);
}));
it('should cancel pending requests', () => {
const LOCAL_VALUES = {
a: VALUES.a,
b: VALUES.b,
j: [VALUES.b, VALUES.b],
};
const REQ1_M = '---a|';
const REQ2_M = 'b| ';
const UPDA_M = '(j|) ';
const REQ1_S = '(^!) ';
const REQ2_S = '(^!) ';
scheduler.withValues(LOCAL_VALUES).run(({ cold, expectObservable, expectSubscriptions }) => {
const request1$ = cold(REQ1_M);
const request2$ = cold(REQ2_M);
expectObservable(
safeForkJoin([
//
holder.update(request1$),
holder.update(request2$),
])
).toBe(UPDA_M);
expectSubscriptions(request1$.subscriptions).toBe(REQ1_S);
expectSubscriptions(request2$.subscriptions).toBe(REQ2_S);
});
});
it('should propagate errors', () =>
scheduler.run(({ cold, expectObservable }) => {
const REQ_M = '#';
const UPD_M = '#';
const request$ = cold(REQ_M);
expectObservable(holder.update(request$)).toBe(UPD_M);
}));
it('should restart on errors', () =>
scheduler.run(({ cold, expectObservable }) => {
const REQ1_M = '#';
const UPD1_M = '#';
const obs$ = holder.update(cold(REQ1_M));
expectObservable(obs$).toBe(UPD1_M);
const REQ2_M = '-a|';
const UPD2_M = '-a|';
const obs2$ = holder.update(cold(REQ2_M));
expectObservable(obs2$).toBe(UPD2_M);
}));
});
describe('.listen()', () => {
function testListen({ REQUEST_M, LISTEN_M, initial }: any) {
scheduler.run(({ cold, expectObservable }) => {
if (initial) {
holder.set(initial);
}
expectObservable(holder.listen(() => cold(REQUEST_M))).toBe(LISTEN_M);
});
}
it('should provide the value', () =>
testListen({
initial: VALUES.a,
REQUEST_M: /**/ ' ',
LISTEN_M: /***/ '(a|)',
}));
it('should cache the value', () =>
testListen({
initial: VALUES.a,
REQUEST_M: /**/ 'b| ',
LISTEN_M: /***/ '(a|)',
}));
it('should propagate errors', () =>
testListen({
REQUEST_M: /**/ '#',
LISTEN_M: /***/ '#',
}));
});
it('.invalidate() should cause the value to be requested again', () =>
scheduler.run(({ cold, expectObservable }) => {
const REQUEST_M = /**/ '(a|)';
const LISTEN_M = /***/ '(a|)';
const requestFactory = jasmine.createSpy('requestFactory');
requestFactory.and.returnValue(cold(REQUEST_M));
return holder
.set(VALUES.a)
.toPromise()
.then(() => holder.invalidate())
.then(() => expectObservable(holder.listen(requestFactory)).toBe(LISTEN_M))
.then(() => expect(requestFactory).toHaveBeenCalled());
}));
});
describe('ResourceCache', () => {
beforeEach(() =>
TestBed.configureTestingModule({
providers: [ResourceCache],
})
);
it('should be created', inject([ResourceCache], (service: ResourceCache) => {
expect(service).toBeDefined();
}));
describe('.get()', () => {
it('should provide the value', inject([ResourceCache], (service: ResourceCache) =>
scheduler.run(({ cold, expectObservable }) => {
const getQuery$ = cold('a|');
expectObservable(service.get(MY_IRI, () => getQuery$)).toBe('(a|)');
})
));
it('should cache the value', inject([ResourceCache], (service: ResourceCache) =>
scheduler.run(({ cold, expectObservable }) => {
const getQuery$ = cold('a|');
const getQuery2$ = cold('b|');
// tslint:disable-next-line:rxjs-finnish
const queries$ = cold('ab|', { a: getQuery$, b: getQuery2$ });
expectObservable(queries$.pipe(mergeMap(query$ => service.get(MY_IRI, () => query$)))).toBe('aa|');
})
));
it('should propagate errors', inject([ResourceCache], (service: ResourceCache) =>
scheduler.run(({ cold, expectObservable }) => {
const getQuery$ = cold('#');
expectObservable(service.get(MY_IRI, () => getQuery$)).toBe('#');
})
));
});
describe('.put()', () => {
it('should provide the value', inject([ResourceCache], (service: ResourceCache) => {
const putRequest$ = scheduler.createColdObservable('a|');
scheduler.expectObservable(service.put(MY_IRI, putRequest$)).toBe('a|');
}));
it('should not cache the value', inject([ResourceCache], (service: ResourceCache) =>
scheduler.run(({ cold, expectObservable }) => {
const putRequest$ = cold('a|');
const putRequest2$ = cold('b|');
// tslint:disable-next-line:rxjs-finnish
const requests$ = cold('ab|', { a: putRequest$, b: putRequest2$ });
expectObservable(
requests$.pipe(
mergeMap((request$: Observable<MyResource>) => service.put(MY_IRI, request$)),
map(x => _.clone(x))
)
).toBe('ab|');
})
));
it('should propagate errors', inject([ResourceCache], (service: ResourceCache) =>
scheduler.run(({ cold, expectObservable }) => {
const putRequest$ = cold('#');
expectObservable(service.put(MY_IRI, putRequest$)).toBe('#');
})
));
});
describe('.post()', () => {
it('should provide the value', inject([ResourceCache], (service: ResourceCache) =>
scheduler.run(({ cold, expectObservable }) => {
const postRequest$ = cold('a|');
expectObservable(service.post(postRequest$)).toBe('a|');
})
));
it('should propagate errors', inject([ResourceCache], (service: ResourceCache) =>
scheduler.run(({ cold, expectObservable }) => {
const postRequest$ = cold('#');
expectObservable(service.post(postRequest$)).toBe('#');
})
));
});
describe('.delete()', () => {
it('should clear the cache on successful fetch', inject([ResourceCache], (service: ResourceCache) => {
const response = new HttpHeaderResponse({ status: 200 });
const values = { r: response, a: VALUES.a, b: VALUES.b };
const sched = scheduler.withValues(values);
sched.run(async ({ cold, expectObservable }) => {
await service.get(MY_IRI, () => cold('a|')).toPromise();
await service.delete(MY_IRI, cold('r|')).toPromise();
return expectObservable(service.get(MY_IRI, () => cold('b|'))).toBe('(b|)');
});
}));
it('should propagate errors', inject([ResourceCache], (service: ResourceCache) =>
scheduler.run(({ cold, expectObservable }) => {
const deleteRequest$ = cold('#');
expectObservable(service.delete(MY_IRI, deleteRequest$)).toBe('#');
})
));
it('should not clear the cache on error', inject([ResourceCache], (service: ResourceCache) => {
const error = new HttpHeaderResponse({ status: 500 });
const values = { a: VALUES.a, b: VALUES.b, e: error };
scheduler
.withValues(values)
.withError(error)
.run(async ({ cold, expectObservable }) => {
await service.get(MY_IRI, () => cold('a|')).toPromise();
await service
.delete(MY_IRI, cold('#'))
.pipe(catchError(e => e))
.toPromise();
return expectObservable(service.get(MY_IRI, () => cold('b|'))).toBe('(a|)');
});
}));
});
describe('.getAll()', () => {
it('should provide the returned value', inject([ResourceCache], (service: ResourceCache) => {
const values = {
a: { 'hydra:member': [VALUES.a, VALUES.d], 'hydra:totalItems': 2 },
};
scheduler.withValues(values).run(({ cold, expectObservable }) => {
const getAllRequest$ = cold('a|');
expectObservable(service.getAll(getAllRequest$)).toBe('a|');
});
}));
it('should nicely handle empty collections', inject([ResourceCache], (service: ResourceCache) => {
const values = {
a: { 'hydra:member': [] as any, 'hydra:totalItems': 0 },
};
scheduler.withValues(values).run(({ cold, expectObservable }) => {
const getAllRequest$ = cold('a|');
expectObservable(service.getAll(getAllRequest$)).toBe('a|');
});
}));
it('should propagate errors', inject([ResourceCache], (service: ResourceCache) =>
scheduler.run(({ cold, expectObservable }) => {
const getAllRequest$ = cold<Collection<MyResource>>('#');
expectObservable(service.getAll(getAllRequest$)).toBe('#');
})
));
it('should populate the cache', inject([ResourceCache], (service: ResourceCache) => {
const values = {
a: VALUES.a,
b: VALUES.d,
h: {
'hydra:member': [VALUES.a, VALUES.d],
'hydra:totalItems': 2,
},
};
scheduler.withValues(values).run(({ cold, expectObservable }) => {
const getAllRequest$ = cold('h|');
const getRequest$ = cold('b|');
const requests$ = cold<() => Observable<any>>('ab|', {
a: () => service.getAll(getAllRequest$),
b: () => service.get(MY_IRI, () => getRequest$),
});
expectObservable(requests$.pipe(mergeMap((sendRequest: () => Observable<any>) => sendRequest()))).toBe('ha|');
});
}));
});
});
});
import { HttpResponseBase } from '@angular/common/http';
import * as _ from 'lodash';
import { Observable, of, race, Subject, throwError } from 'rxjs';
import { map, switchMap, take, tap } from 'rxjs/operators';
import {
AbstractResourceCache,
Collection,
COLLECTION_MEMBERS,
getCollectionMembers,
IRI,
IRI_PROPERTY,
Resource,
} from '../../shared/models';
import { safeForkJoin } from '../../shared/rxjs';
export class APICacheError extends Error {}
export class MissingIRIError extends APICacheError {
public constructor() {
super(`resource must have an ${IRI_PROPERTY} property`);
}
}
export class IRIMismatchError extends APICacheError {
public constructor(expected: any, actual: any) {
super(`${IRI_PROPERTY}s mismatch: ${actual} !== ${expected}`);
}
}
/**
* ValueHolder gère les requêtes d'une seule ressource.
*
* @internal
*/
export class ValueHolder<R extends Resource> {
private readonly value$ = new Subject<R>();
private readonly value = {} as R;
private version = 0;
constructor(private readonly iri: IRI<R>) {}
public set(value: R): Observable<R> {
if (!(IRI_PROPERTY in value)) {
return throwError(new MissingIRIError());
}
if (value[IRI_PROPERTY] !== this.iri) {
return throwError(new IRIMismatchError(this.iri, value[IRI_PROPERTY]));
}
_.assign(this.value, value);
_(this.value)
.keys()
.difference(_.keys(value))
.forEach(key => delete this.value[key]);
this.version++;
this.value$.next(this.value);
return of(this.value);
}
public listen(queryFactory: () => Observable<R>): Observable<R> {
if (this.version > 0) {
return of(this.value);
}
return this.update(queryFactory());
}
public update(request$: Observable<R>): Observable<R> {
return race(this.value$.pipe(take(1)), request$.pipe(switchMap((item: R) => this.set(item))));
}
public invalidate(): void {
this.version = 0;
}
public delete(): void {
this.value$.complete();
}
}
/**
* Implémentation d'un cache de resource.
*
* Cette implémentation met en place une queue de requête ainsi qu'un observable pour chaque ressource.
*
* La queue de requête permet de mettre à jour une ressource en cache. switchMap est utilisé pour prendre en compte
* les valeurs des dernières requêtes.
*
* L'Observable s'assure de retourner toujours la même référence d'objet tout au long de la vie
* de la ressource dans le cache, il permet aussi de faire suivre tout mise à jour à d'eventuels subscribers.
*/
export class ResourceCache extends AbstractResourceCache {
private readonly holders = new Map<IRI<Resource>, ValueHolder<Resource>>();
/**
* Retourne la ressource identifiée par l'IRI donné.
*
* Effectue une requête si on le connait pas.
*/
public get<R extends Resource>(iri: IRI<R>, requestFactory: () => Observable<R>): Observable<R> {
return this.getHolder(iri).listen(requestFactory);
}
/**
* Envoie une requête de mise à jour puis met à jour le cache avec la réponse du serveur.
*/
public put<R extends Resource>(iri: IRI<R>, query$: Observable<R>): Observable<R> {
return this.getHolder(iri).update(query$);
}
/**
* Envoie une requête de création puis met à jour le chache avec la réponse.
*/
public post<R extends Resource>(query$: Observable<R>): Observable<R> {
return query$.pipe(switchMap(item => this.received(item)));
}
/**
* Supprime une ressource sur le serveur puis en cache.
*/
public delete<R extends Resource>(iri: IRI<R>, query$: Observable<HttpResponseBase>): Observable<HttpResponseBase> {
return query$.pipe(
tap(() => {
if (!this.holders.has(iri)) {
return;
}
this.holders.get(iri).delete();
this.holders.delete(iri);
})
);
}
/**
* Fait une requête pour plusieurs ressources puis les mets en cache.
*/
public getAll<R extends Resource>(query$: Observable<Collection<R>>): Observable<Collection<R>> {
return query$.pipe(
switchMap((coll: Collection<R>) => {
const members = getCollectionMembers(coll);
const memberObservables$ = members.map(item => this.received(item));
return safeForkJoin(memberObservables$).pipe(
map(items => Object.assign({} as Collection<R>, coll, { [COLLECTION_MEMBERS]: items }))
);
})
);
}
/**
* Invalide la valeur d'une IRI pour forcer une mise-à-jour.
*/
public invalidate<R extends Resource>(iri: IRI<R>): void {
if (!this.holders.has(iri)) {
return;
}
this.holders.get(iri).invalidate();
}
/**
* Retourne le ValueHolder d'une IRI, ou le crée si nécessaire.
*/
private getHolder<R extends Resource>(iri: IRI<R>): ValueHolder<R> {
let holder = this.holders.get(iri) as ValueHolder<R>;
if (!holder) {
holder = new ValueHolder<R>(iri);
this.holders.set(iri, holder);
}
return holder;
}