import FolderModel from '../../models/Folder' import * as ColumnTypes from '../../utilities/ColumnTypes' import * as Response from '../../utilities/Response' type Folder = ColumnTypes.InferModel export const getSingle = repository => async (id: string) => { const instance = await repository.findByPk(id) if (instance === null) { throw new Response.NotFound({ message: 'Not found.' }) } return new Response.Retrieved({ data: instance.toJSON() as Folder, }) } export const getMultiple = repository => async (query?: Record) => { const fetchMethod = async query => { if (query) { return repository.findWhere({ attributes: query, }) } return repository.findAll() } const instances = await fetchMethod(query) return new Response.Retrieved({ data: instances.map(i => i.toJSON()), }) } export const save = repository => (body: Partial) => async (id: string, idColumnName = 'id') => { const [newInstance, created] = await repository.findOrCreate({ where: { [idColumnName]: id }, defaults: { ...body, [idColumnName]: id, }, }) if (created) { return new Response.Created({ data: newInstance.toJSON() as Folder }) } Object.entries(body).forEach(([key, value]) => { newInstance[key] = value }) newInstance[idColumnName] = id const updatedInstance = await newInstance.save() return new Response.Saved({ data: updatedInstance.toJSON() as Folder }) } export const remove = repository => async (id: string) => { const instanceDAO = repository.findByPk(id) if (instanceDAO === null) { throw new Response.NotFound({ message: 'Not found.' }) } await instanceDAO.destroy() return new Response.Destroyed() }