Added last changed in generic service

This commit is contained in:
Adina Țeudan 2021-11-18 16:57:03 +02:00
parent 4242cd442b
commit 1408f81f2b

View File

@ -1,8 +1,8 @@
import { HttpClient, HttpEvent, HttpParams } from '@angular/common/http';
import { Injector } from '@angular/core';
import { Observable } from 'rxjs';
import { CustomHttpUrlEncodingCodec, List, RequiredParam, Validate } from '../utils';
import { HeadersConfiguration } from '../utils/headers-configuration';
import { CustomHttpUrlEncodingCodec, HeadersConfiguration, List, RequiredParam, Validate } from '../utils';
import { map, tap } from 'rxjs/operators';
export interface HeaderOptions {
readonly authorization?: boolean;
@ -21,23 +21,35 @@ export interface QueryParam {
*/
export abstract class GenericService<I> {
protected readonly _http = this._injector.get(HttpClient);
private _lastCheckedForChanges = '0';
protected constructor(protected readonly _injector: Injector, protected readonly _defaultModelPath: string) {}
protected get _hasChanges$(): Observable<boolean> {
return this._post<{ value: boolean }>({ since: this._lastCheckedForChanges }, `${this._defaultModelPath}/changes`).pipe(
map(res => res.value),
tap(() => this._updateLastChanged()),
);
}
get<T = I[]>(): Observable<T>;
// eslint-disable-next-line @typescript-eslint/unified-signatures
get<T = I>(id: string, ...args: unknown[]): Observable<T>;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
get<T>(id?: string, ...args: unknown[]): Observable<T> {
return id ? this._getOne<T>([id]) : this.getAll<T>();
}
getAll<R = I[]>(modelPath = this._defaultModelPath, queryParams?: List<QueryParam>): Observable<R> {
return this._http.get<R>(`/${encodeURI(modelPath)}`, {
headers: HeadersConfiguration.getHeaders({ contentType: false }),
observe: 'body',
params: this._queryParams(queryParams),
});
return this._http
.get<R>(`/${encodeURI(modelPath)}`, {
headers: HeadersConfiguration.getHeaders({ contentType: false }),
observe: 'body',
params: this._queryParams(queryParams),
})
.pipe(tap(() => this._updateLastChanged()));
}
@Validate()
@ -64,8 +76,7 @@ export abstract class GenericService<I> {
formParams.append('file', data);
}
// TODO: Fix getHeaders()?
const headers = HeadersConfiguration.getHeaders().delete('content-type');
const headers = HeadersConfiguration.getHeaders({ contentType: false });
return this._http.post<R>(`/${encodeURI(modelPath)}`, formParams, {
headers,
@ -125,4 +136,8 @@ export abstract class GenericService<I> {
return queryParameters;
}
protected _updateLastChanged(): void {
this._lastCheckedForChanges = new Date().toISOString();
}
}