|
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- import FolderModel from '../../models/Folder'
- import * as ColumnTypes from '../../utilities/ColumnTypes'
- import * as Response from '../../utilities/Response'
-
- type Folder = ColumnTypes.InferModel<typeof FolderModel>
-
- 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<string, unknown>) => {
- const fetchMethod = async query => {
- if (query) {
- return repository.findWhere({
- attributes: query,
- })
- }
- return repository.findAll()
- }
- const instances = await fetchMethod(query)
- return new Response.Retrieved<Folder[]>({
- data: instances.map(i => i.toJSON()),
- })
- }
-
- export const save = repository => (body: Partial<Folder>) => 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()
- }
|