Monorepo containing core modules of Zeichen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.2 KiB

  1. import Model from '../../models/Folder'
  2. import Instance from '../utilities/Instance'
  3. import * as Response from '../utilities/Response'
  4. type ModelInstance = Instance<typeof Model.rawAttributes>
  5. export const getSingle = repository => async (id: string) => {
  6. const instance = await repository.findByPk(id)
  7. if (instance === null) {
  8. throw new Response.NotFound({ message: 'Not found.' })
  9. }
  10. return new Response.Retrieved({
  11. data: instance,
  12. })
  13. }
  14. export const getMultiple = repository => async (query: Record<string, unknown>) => {
  15. const instances = await repository.findAll()
  16. return new Response.Retrieved({
  17. data: instances,
  18. })
  19. }
  20. export const save = repository => (body: Partial<ModelInstance>) => async (id: string, idColumnName = 'id') => {
  21. const [newInstance, created] = await repository.findOrCreate({
  22. where: { [idColumnName]: id },
  23. defaults: {
  24. ...body,
  25. [idColumnName]: id,
  26. },
  27. })
  28. if (created) {
  29. return new Response.Created({
  30. data: newInstance.toJSON()
  31. })
  32. }
  33. Object.entries(body).forEach(([key, value]) => {
  34. newInstance[key] = value
  35. })
  36. newInstance[idColumnName] = id
  37. const updatedInstance = await newInstance.save()
  38. return new Response.Saved({
  39. data: updatedInstance.toJSON()
  40. })
  41. }