Monorepo containing core modules of Zeichen.
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.7 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. 'DELETE': Service.remove(repository)
  37. }
  38. const { [req.method as keyof typeof methodHandlers]: handler = null } = methodHandlers
  39. if (handler === null) {
  40. res.statusCode = 415
  41. res.json({ message: 'Method not allowed.' })
  42. return
  43. }
  44. const { id } = req.query
  45. try {
  46. const { status, data, } = await handler(id)
  47. res.statusCode = status
  48. if (data) {
  49. res.json(data)
  50. return
  51. }
  52. res.end()
  53. } catch (err) {
  54. console.log('ERROR', err)
  55. const { status, data, } = err
  56. res.statusCode = status
  57. res.json(data)
  58. }
  59. }