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.

79 lines
2.2 KiB

  1. import Model from '../../models/Note'
  2. import * as ColumnTypes from '../../utilities/ColumnTypes'
  3. import * as Response from '../../utilities/Response'
  4. type Note = ColumnTypes.InferModel<typeof Model>
  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<Note>) => async (id: string, idColumnName = 'id') => {
  31. const { content: contentRaw, ...etcBody } = body
  32. const content = contentRaw! ? JSON.stringify(contentRaw) : null
  33. const [dao, created] = await repository.findOrCreate({
  34. where: { [idColumnName]: id },
  35. defaults: {
  36. ...etcBody,
  37. [idColumnName]: id,
  38. content,
  39. },
  40. })
  41. if (created) {
  42. const newInstance = dao.toJSON()
  43. return new Response.Created({
  44. data: {
  45. ...newInstance,
  46. content: newInstance.content ? JSON.parse(newInstance.content) : null,
  47. },
  48. })
  49. }
  50. Object.entries(body).forEach(([key, value]) => {
  51. dao[key] = value
  52. })
  53. dao['content'] = content
  54. dao[idColumnName] = id
  55. const updatedDAO = await dao.save()
  56. const updatedInstance = updatedDAO.toJSON()
  57. return new Response.Saved({
  58. data: {
  59. ...updatedInstance,
  60. content: updatedInstance.content ? JSON.parse(updatedInstance.content) : null,
  61. }
  62. })
  63. }
  64. export const remove = repository => async (id: string) => {
  65. const instanceDAO = await repository.findByPk(id)
  66. if (instanceDAO === null) {
  67. throw new Response.NotFound({ message: 'Not found.' })
  68. }
  69. await instanceDAO.destroy()
  70. return new Response.Destroyed()
  71. }