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.

70 lines
2.0 KiB

  1. import Model from '../../models/Note'
  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 instanceDAO = await repository.findByPk(id)
  7. if (instanceDAO === null) {
  8. throw new Response.NotFound({ message: 'Not found.' })
  9. }
  10. const instance = instanceDAO.toJSON()
  11. return new Response.Retrieved({
  12. data: {
  13. ...instance,
  14. content: instance.content ? JSON.parse(instance.content) : null,
  15. },
  16. })
  17. }
  18. export const getMultiple = repository => async (query: Record<string, unknown>) => {
  19. const instances = await repository.findAll()
  20. return new Response.Retrieved({
  21. data: instances.map(instanceDAO => {
  22. const instance = instanceDAO.toJSON()
  23. return {
  24. ...instance,
  25. content: instance.content ? JSON.parse(instance.content) : null,
  26. }
  27. }),
  28. })
  29. }
  30. export const save = repository => (body: Partial<ModelInstance>) => async (id: string, idColumnName = 'id') => {
  31. const { content: contentRaw, ...etcBody } = body
  32. const content = contentRaw! ? JSON.stringify(contentRaw) : null
  33. console.log('REPOSITORY', repository)
  34. const [dao, created] = await repository.findOrCreate({
  35. where: { [idColumnName]: id },
  36. defaults: {
  37. ...etcBody,
  38. [idColumnName]: id,
  39. content,
  40. },
  41. })
  42. if (created) {
  43. const newInstance = dao.toJSON()
  44. return new Response.Created({
  45. data: {
  46. ...newInstance,
  47. content: newInstance.content ? JSON.parse(newInstance.content) : null,
  48. },
  49. })
  50. }
  51. Object.entries(body).forEach(([key, value]) => {
  52. dao[key] = value
  53. })
  54. dao['content'] = content
  55. dao[idColumnName] = id
  56. const updatedDAO = await dao.save()
  57. const updatedInstance = updatedDAO.toJSON()
  58. return new Response.Saved({
  59. data: {
  60. ...updatedInstance,
  61. content: updatedInstance.content ? JSON.parse(updatedInstance.content) : null,
  62. }
  63. })
  64. }