import { injectable } from "inversify"; import TagAssociation, { ITagAssociation, tagAssociationType, ITagAssociationResource, ITagAssociationRelationships } from "./"; import {IJsonApiRelationship, IJsonApiRelationshipResource, IJsonApiResource, IResourceMapper} from "../../interfaces"; import PartnerActivityMapper from "../partnerActivity/mapper"; import PoiMapper from "../poi/mapper"; import Mapper from "../../mapper"; const mappers = { partner_activity: new PartnerActivityMapper(), poi: new PoiMapper(), }; @injectable() export class TagAssociationMapper extends Mapper { toModel(resource: ITagAssociationResource, included: IJsonApiResource[] = []): ITagAssociation { const model = new TagAssociation(); const attrs = resource.attributes; model.id = resource.id; model.confidenceScore = attrs.confidence_score; model.label = attrs.label; model.score = attrs.score; const tagAttributes = this.getTagAttributes(this.getTagRelationship(resource.relationships)); if (tagAttributes) { model.tag_type = tagAttributes.tag_type; model.tag_id = tagAttributes.tag_id; } if (resource.relationships.target) { const targetResource = resource.relationships.target.data; model.target = this.mapIncluded(targetResource, included); } return model; } toResource(model: ITagAssociation): ITagAssociationResource { const resource: ITagAssociationResource = { id: model.id, type: tagAssociationType, attributes: { confidence_score: model.confidenceScore, label: model.label, score: model.score, }, }; resource.relationships = {}; if (model.target) { resource.relationships.target = { data: { type: model.target.type, id: model.target.id } }; } if (model.tag_type) { resource.relationships[model.tag_type] = { data: { type: model.tag_type, id: model.tag_id, } } } Object.keys(resource.attributes).forEach((key) => { if (typeof resource.attributes[key] === "undefined") { delete resource.attributes[key]; } }); if (Object.keys(resource.relationships).length === 0) { delete resource.relationships; } return resource; } private getTagRelationship(relationships: ITagAssociationRelationships) { const tagRelationships = ["topic", "category", "entity", "tag"]; let tagRelationship = null; for (const relationshipName of tagRelationships) { const relationship = relationships[relationshipName]; if (relationship && typeof relationship.data === "object") { tagRelationship = relationships[relationshipName].data break; } } return tagRelationship; } private getTagAttributes(tagRelationship?: IJsonApiRelationshipResource) { if (tagRelationship) { return { tag_type: tagRelationship.type, tag_id: tagRelationship.id, } } } private mapIncluded(resourceIdentifier: IJsonApiResource, included: any[]) { const resource = included.find((i) => i.type === resourceIdentifier.type && i.id === resourceIdentifier.id); if (!resource) { return resourceIdentifier; } const mapper: IResourceMapper = mappers[resource.type]; return mapper.toModel(resource, included); } } export default TagAssociationMapper;