|
12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- import Model from '../../models/Folder'
- import Instance from '../utilities/Instance'
- import * as Response from '../utilities/Response'
- type ModelInstance = Instance<typeof Model.rawAttributes>
-
- 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,
- })
- }
-
- export const getMultiple = repository => async (query: Record<string, unknown>) => {
- const instances = await repository.findAll()
- return new Response.Retrieved({
- data: instances,
- })
- }
-
- export const save = repository => (body: Partial<ModelInstance>) => 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()
- })
- }
-
- Object.entries(body).forEach(([key, value]) => {
- newInstance[key] = value
- })
- newInstance[idColumnName] = id
- const updatedInstance = await newInstance.save()
- return new Response.Saved({
- data: updatedInstance.toJSON()
- })
- }
|