UNPKG

ngx-rickandmorty

Version:

60 lines 2.48 kB
import { inject, Injectable } from '@angular/core'; import { BASE_URL } from './tokens'; import { HttpClient, HttpParams } from '@angular/common/http'; import { of } from 'rxjs'; import { Location as NgLocation } from '@angular/common'; import { Location } from './interfaces/location'; import { Episode } from './interfaces/episode'; import { catchError, map } from 'rxjs/operators'; import { responseFactory } from './helpers/response-factory'; import { Character } from './interfaces/character'; import { coerceArray } from './helpers/coerce-array'; import * as i0 from "@angular/core"; export class ApiService { constructor() { this.baseUrl = inject(BASE_URL); this.http = inject(HttpClient); } ping() { return this.http.get(this.baseUrl); } getEpisode(id) { return this.getEntity('episode', id).pipe(map((rawResponse) => responseFactory(rawResponse, Episode.fromJson))); } getLocation(id) { return this.getEntity('location', id).pipe(map((rawResponse) => responseFactory(rawResponse, Location.fromJson))); } getCharacter(id) { return this.getEntity('character', id).pipe(map((rawResponse) => responseFactory(rawResponse, Character.fromJson))); } getEntity(url, id) { var _a; const [ids, params] = [ this.isId(id) ? coerceArray(id).filter((i) => (i !== null && i !== void 0 ? i : false) !== false) : null, this.isId(id) ? null : id, ]; return this.http .get(NgLocation.joinWithSlash(NgLocation.joinWithSlash(this.baseUrl, url), (_a = ids === null || ids === void 0 ? void 0 : ids.join(',')) !== null && _a !== void 0 ? _a : ''), { params: new HttpParams({ fromObject: params }) }) .pipe(catchError(() => { if (typeof id === 'number' || Array.isArray(id)) { return of([]); } return of({ info: { pages: 0, count: 0, prev: null, next: null }, results: [], }); })); } isId(id) { return typeof id === 'number' || Array.isArray(id); } } ApiService.ɵprov = i0.ɵɵdefineInjectable({ factory: function ApiService_Factory() { return new ApiService(); }, token: ApiService, providedIn: "root" }); ApiService.decorators = [ { type: Injectable, args: [{ providedIn: 'root', },] } ]; //# sourceMappingURL=api.service.js.map