import { inject, injectable } from "inversify"; import { IJsonApiResource, IJsonApiRelationships } from "../../interfaces"; import Mapper from "../../mapper"; import * as TYPES from "../../types"; import Tag, { tagType, tagAssociationType, ITag, ITagResource, ITagRelationships } from "./"; import {ITagAssociationResource} from "../tagAssociation/index"; @injectable() export class PoiMapper extends Mapper { @inject(TYPES.Bookmark) model: ITag; toModel(resource: ITagResource | ITagAssociationResource, included: IJsonApiResource[] = []): ITag { const model = new Tag(); if (resource.type === tagType) { this.mapFromTag(model, resource as ITagResource, included); } else { this.mapFromTagAssociation(model, resource as ITagAssociationResource); } return model; } private mapFromTagAssociation(model: Tag, resource: ITagAssociationResource) { model.associationId = resource.id; model.name = resource.attributes.label; const tag = (resource.relationships["tag"].data); if (tag) { model.id = tag.id; } const target = (resource.relationships["target"].data); model.targetId = target.id; model.targetType = target.type; } private mapFromTag(model: Tag, resource: ITagResource, included: IJsonApiResource<{}, IJsonApiRelationships>[]) { model.id = resource.id; model.name = resource.attributes.name; const relationships = (resource.relationships)["tag-associations"]; if (relationships.data) { const associationRelationships = Array.isArray(relationships.data) ? relationships.data : [relationships.data]; const associationRel = associationRelationships[0]; model.associationId = associationRel.id; const association = included.find((i) => i.id === associationRel.id && i.type === tagAssociationType); if (association) { const target = (association.relationships.target.data); model.targetId = target.id; model.targetType = target.type; } } } toResource(model: ITag): ITagResource { const resource = { id: model.associationId, type: tagType, attributes: { name: model.name, }, relationships: {}, }; resource.relationships = { target: { data: { type: model.targetType, id: model.targetId } }, tag: { data: { type: tagType, id: model.id, } } }; return resource; } } export default PoiMapper;