import { inject, injectable } from "inversify"; import BaseService from "../../service"; import { IService, IResourceMapper, IJsonApiResource, IFindParams } from "../../interfaces"; import { ITag, ITagResource, ITagAssociationResource, tagType, ITagAssociationResponse, ITopic, ITopicResource, ITopicResponse } from "./"; import Mapper from "./mapper"; import TopicMapper from "./topicMapper"; export interface ITagService extends IService { addTagToResource(tag: ITag): Promise; findByResource(id: string, type: string, options?: IFindParams): Promise; deleteAssociation(id: string): void; findTopic(options?: IFindParams): Promise; } @injectable() export default class TagService extends BaseService implements ITagService { resource: string = tagType; mapper: IResourceMapper = new Mapper(); topicMapper: IResourceMapper = new TopicMapper(); public url() { return `${this.host}/tags`; } public tagAssociationUrl() { return `${this.host}/tags/associations`; } public async findByResource(id: string, type: string, options: IFindParams = {}) { const resources = await this.http.fetch( `${this.tagAssociationUrl()}${this.qs({ ...options, resource: "tag_association", tag_type: "tag", target_id: id, target_type: type, })}`, { headers: this.headers(), } ); return this.mapper.map(resources); } public async addTagToResource(tag: ITag): Promise { const resource = await this.http.fetch( this.tagAssociationUrl(), { method: "POST", body: { data: { ...this.mapper.toResource(tag), }, }, headers: this.headers(), } ); tag.associationId = (resource.data).id; return tag; } public async deleteAssociation(id) { const url = `${this.tagAssociationUrl()}/${id}`; await this.http.fetch( url, { method: "DELETE", headers: this.headers(), }); return; } public async findTopic(options?: IFindParams): Promise { const resources = await this.http.fetch( `${this.url()}/topics${this.qs({ ...options, resource: "topic"})}`, { headers: this.headers(), } ); return this.topicMapper.map(resources); } public headers() { return { ...super.headers(), "Accept-Version": "v2", } } }