import { inject, injectable } from "inversify"; import * as pluralize from "pluralize"; import * as TYPES from "./types"; import Base from "./base"; import { IResourceMapper, IHttpClient, IFindParams, IJsonApiResponse, IJsonApiResource } from "./interfaces"; import { createFilters, createIncludes, createFindByIdUrl } from "./jsonApiUtils"; @injectable() export default abstract class BaseService extends Base { constructor(accessToken) { super(accessToken); } public async find(options: IFindParams = {}): Promise { const response = await this.http.fetch>( `${this.url(options)}${this.qs(options)}`, { ...options, headers: this.headers(), }); const parsed = this.parse(response); return parsed; } public async update(attributes: T) { const resource = this.mapper.toResource(attributes); Object.keys(resource.attributes).forEach((key) => (typeof resource.attributes[key] === "undefined") && delete resource.attributes[key] ); const response = await this.http.fetch>(`${this.url()}/${resource.id}`, { method: "PATCH", body: { data: resource, }, headers: this.headers(), }); return this.parse(response); } public async create(attributes: T) { const resource = this.mapper.toResource(attributes); Object.keys(resource.attributes).forEach((key) => (typeof resource.attributes[key] === "undefined") && delete resource.attributes[key] ); const response = await this.http.fetch>(`${this.url()}`, { method: "POST", body: { data: resource, }, headers: this.headers(), }); return this.parse(response); } public async findById(id: string | string[], options: IFindParams = {}): Promise { let baseUrl = typeof id === "string" ? `${this.url(options)}/${id}` : this.url(options); let url = createFindByIdUrl(baseUrl, id, { ...options, resource: this.resource, }); const response = await this.http.fetch>( url, { ...options, headers: this.headers(), }); if (Array.isArray(response.data)) { return this.parse(response); } return this.parse(response); } public async destroy(id: string, options: IFindParams = {}) { const url = `${this.url(options)}/${id}`; const response = await this.http.fetch>( url, { method: "DELETE", headers: this.headers(), }); return; } }