import { inject, injectable } from "inversify"; import Bookmark, { IBookmark, bookmarkEntryType, IBookmarkEntryResource } from "../bookmark"; import BookmarkList, { IBookmarkList, IBookmarkListAttributes, IBookmarkListResource, bookmarkListType } from "../bookmarkList"; import { IJsonApiResource, IJsonApiResponse } from "../../interfaces"; import Mapper from "../../mapper"; import BookmarkMapper from "../bookmark/bookmarkMapper"; import * as TYPES from "../../types"; @injectable() export class BookmarkListMapper extends Mapper { @inject(TYPES.Bookmark) model: IBookmark; bookmarkMapper = new BookmarkMapper(); toModel(resource: IBookmarkListResource, included: IJsonApiResource[] = []): IBookmarkList { const model = new BookmarkList(); model.id = resource.id; model.entries = included.filter((i) => i.type === bookmarkEntryType) .filter((i) => { const isArray = Array.isArray(resource.relationships.entries.data); const entries = ((isArray ? resource.relationships.entries.data : resource.relationships.entries.data && [resource.relationships.entries.data])); if (entries) { return entries.some(e => e.id === i.id); } return false; }) .map((b: IBookmarkEntryResource) => { return this.bookmarkMapper.toModel(b, included); }); model.name = resource.attributes.name; model.visibility = resource.attributes.visibility; model.source = resource.attributes.source; model.updatedAt = new Date(resource.attributes.updated_at); model.insertedAt = new Date(resource.attributes.inserted_at); model.extra = resource.attributes.extra; model.expectedEntriesCount = resource.attributes.entries_count; return model; } toResource(model: IBookmarkList): IBookmarkListResource { const resource = { id: model.id, type: bookmarkListType, attributes: { name: model.name, visibility: model.visibility, source: model.source, extra: model.extra, }, }; Object.keys(resource.attributes).forEach((key) => { if (typeof resource.attributes[key] === "undefined") { delete resource.attributes[key]; } }); return resource; } } export default BookmarkListMapper;