|
- import Model from '../../models/Note'
- import * as ColumnTypes from '../../utilities/ColumnTypes'
- import * as Response from '../../utilities/Response'
-
- type Note = ColumnTypes.InferModel<typeof Model>
-
- export const getSingle = repository => async (id: string) => {
- const instanceDAO = await repository.findByPk(id)
- if (instanceDAO === null) {
- throw new Response.NotFound({ message: 'Not found.' })
- }
- const instance = instanceDAO.toJSON()
- return new Response.Retrieved({
- data: {
- ...instance,
- content: instance.content ? JSON.parse(instance.content) : null,
- },
- })
- }
-
- export const getMultiple = repository => async (query: Record<string, unknown>) => {
- const instances = await repository.findAll()
- return new Response.Retrieved({
- data: instances.map(instanceDAO => {
- const instance = instanceDAO.toJSON()
- return {
- ...instance,
- content: instance.content ? JSON.parse(instance.content) : null,
- }
- }),
- })
- }
-
- export const save = repository => (body: Partial<Note>) => async (id: string, idColumnName = 'id') => {
- const { content: contentRaw, ...etcBody } = body
- const content = contentRaw! ? JSON.stringify(contentRaw) : null
- const [dao, created] = await repository.findOrCreate({
- where: { [idColumnName]: id },
- defaults: {
- ...etcBody,
- [idColumnName]: id,
- content,
- },
- })
-
- if (created) {
- const newInstance = dao.toJSON()
- return new Response.Created({
- data: {
- ...newInstance,
- content: newInstance.content ? JSON.parse(newInstance.content) : null,
- },
- })
- }
-
- Object.entries(body).forEach(([key, value]) => {
- dao[key] = value
- })
- dao['content'] = content
- dao[idColumnName] = id
- const updatedDAO = await dao.save()
- const updatedInstance = updatedDAO.toJSON()
- return new Response.Saved({
- data: {
- ...updatedInstance,
- content: updatedInstance.content ? JSON.parse(updatedInstance.content) : null,
- }
- })
- }
-
- export const remove = repository => async (id: string) => {
- const instanceDAO = await repository.findByPk(id)
- if (instanceDAO === null) {
- throw new Response.NotFound({ message: 'Not found.' })
- }
- await instanceDAO.destroy()
- return new Response.Destroyed()
- }
|