forked from johnpapa/angular-ngrx-data
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathentity-data.service.ts
79 lines (71 loc) · 2.48 KB
/
entity-data.service.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
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { EntityAction } from '../actions/entity-action';
import { DefaultDataServiceFactory } from './default-data.service';
import { HttpUrlGenerator } from './http-url-generator';
import { QueryParams } from './interfaces';
import { Update } from '../utils/ngrx-entity-models';
/** A service that performs REST-like HTTP data operations */
export interface EntityCollectionDataService<T> {
readonly name: string;
add(entity: T): Observable<T>;
delete(id: number | string): Observable<number | string>;
getAll(): Observable<T[]>;
getById(id: any): Observable<T>;
getWithQuery(params: QueryParams | string): Observable<T[]>;
update(update: Update<T>): Observable<T>;
}
@Injectable()
export class EntityDataService {
protected services: { [name: string]: EntityCollectionDataService<any> } = {};
// TODO: Optionally inject specialized entity data services
// for those that aren't derived from BaseDataService.
constructor(protected defaultDataServiceFactory: DefaultDataServiceFactory) {}
/**
* Get (or create) a data service for entity type
* @param entityName - the name of the type
*
* Examples:
* getService('Hero'); // data service for Heroes, untyped
* getService<Hero>('Hero'); // data service for Heroes, typed as Hero
*/
getService<T>(entityName: string): EntityCollectionDataService<T> {
entityName = entityName.trim();
let service = this.services[entityName];
if (!service) {
service = this.defaultDataServiceFactory.create(entityName);
this.services[entityName] = service;
}
return service;
}
/**
* Register an EntityCollectionDataService for an entity type
* @param entityName - the name of the entity type
* @param service - data service for that entity type
*
* Examples:
* registerService('Hero', myHeroDataService);
* registerService('Villain', myVillainDataService);
*/
registerService<T>(
entityName: string,
service: EntityCollectionDataService<T>
) {
this.services[entityName.trim()] = service;
}
/**
* Register a batch of data services.
* @param services - data services to merge into existing services
*
* Examples:
* registerServices({
* Hero: myHeroDataService,
* Villain: myVillainDataService
* });
*/
registerServices(services: {
[name: string]: EntityCollectionDataService<any>;
}) {
this.services = { ...this.services, ...services };
}
}