import { injectable } from "inversify"; import AssociationEntry, { IAssociationEntry, associationEntryType, IAssociationEntryResource } from "./"; import { IJsonApiResource, IResourceMapper } from "../../interfaces"; import Mapper from "../../mapper"; import PoiMapper from "../poi/mapper"; import PartnerActivityMapper from "../partnerActivity/mapper"; import PlaceMapper from "../place/mapper"; import LodgingMapper from "../lodging/mapper"; const mappers = { poi: new PoiMapper(), place: new PlaceMapper(), lodging: new LodgingMapper(), partner_activity: new PartnerActivityMapper(), }; @injectable() export class AssociationEntryMapper extends Mapper { toModel(resource: IAssociationEntryResource, included: IJsonApiResource[] = []): IAssociationEntry { const model = new AssociationEntry(); const attrs = resource.attributes; model.id = resource.id; model.matchesSource = attrs.matches_source; model.createdAt = attrs.created_at; model.updatedAt = attrs.updated_at; if (resource.relationships.target) { const targetResource = resource.relationships.target.data; const target = included.find((i) => i.type === targetResource.type && i.id === targetResource.id); if (target) { const mapper: IResourceMapper = mappers[target.type]; model.target = mapper.toModel(target, included); } else { model.target = resource.relationships.target.data; } } return model; } toResource(model: IAssociationEntry): IAssociationEntryResource { const resource: IAssociationEntryResource = { id: model.id, type: associationEntryType, attributes: { created_at: model.createdAt, matches_source: model.matchesSource, updated_at: model.updatedAt }, }; if (model.target) { resource.relationships = { target: { data: { type: model.target.type, id: model.target.id } } }; } Object.keys(resource.attributes).forEach((key) => { if (typeof resource.attributes[key] === "undefined") { delete resource.attributes[key]; } }); return resource; } } export default AssociationEntryMapper;