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.

61 lines
1.6 KiB

  1. import ORM, { DatabaseKind } from '../utilities/ORM'
  2. export const collection = (Model, Service) => async (req, res) => {
  3. const orm = new ORM({
  4. kind: process.env.DATABASE_DIALECT as DatabaseKind,
  5. url: process.env.DATABASE_URL,
  6. })
  7. const repository = orm.getRepository(Model)
  8. const methodHandlers = {
  9. 'GET': Service.getMultiple(repository),
  10. }
  11. const { [req.method as keyof typeof methodHandlers]: handler = null } = methodHandlers
  12. if (handler === null) {
  13. res.statusCode = 415
  14. res.json({ message: 'Method not allowed.' })
  15. return
  16. }
  17. try {
  18. const { status, data, } = await handler(req.query)
  19. res.statusCode = status
  20. res.json(data)
  21. } catch (err) {
  22. const { status, data, } = err
  23. res.statusCode = status
  24. res.json(data)
  25. }
  26. }
  27. export const item = (Model, Service) => async (req, res) => {
  28. const orm = new ORM({
  29. kind: process.env.DATABASE_DIALECT as DatabaseKind,
  30. url: process.env.DATABASE_URL,
  31. })
  32. const repository = orm.getRepository(Model)
  33. const methodHandlers = {
  34. 'GET': Service.getSingle(repository),
  35. 'PUT': Service.save(repository)(req.body),
  36. }
  37. const { [req.method as keyof typeof methodHandlers]: handler = null } = methodHandlers
  38. if (handler === null) {
  39. res.statusCode = 415
  40. res.json({ message: 'Method not allowed.' })
  41. return
  42. }
  43. const { id } = req.query
  44. try {
  45. const { status, data, } = await handler(id)
  46. res.statusCode = status
  47. res.json(data)
  48. } catch (err) {
  49. console.log('ERROR', err)
  50. const { status, data, } = err
  51. res.statusCode = status
  52. res.json(data)
  53. }
  54. }