1
0

http.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import * as account from './account/api'
  2. import type { Context } from './types'
  3. import express from 'express'
  4. import type { ErrorRequestHandler, NextFunction, Response } from 'express'
  5. export function createExpress(ctx: Context) {
  6. const app = express()
  7. app.use(express.json())
  8. app.use(async (req, res, next) => {
  9. try {
  10. await ctx.auth.verifyRequest(req)
  11. } catch (err) {
  12. ctx.log.warn('Failed to verify request', err)
  13. }
  14. next()
  15. })
  16. const prefix = ctx.config.api.prefix
  17. app.post(`${prefix}/account`, account.createAccount(ctx))
  18. app.get(`${prefix}/account/:id?`, account.getAccount(ctx))
  19. app.put(`${prefix}/account/:id?`, account.updateAccount(ctx))
  20. app.delete(`${prefix}/account/:id?`, account.deleteAccount(ctx))
  21. app.post(`${prefix}/login/account`, account.loginAccount(ctx))
  22. // Handle errors passed to next function
  23. const catchError: ErrorRequestHandler = (err, req, res, next) => {
  24. if (!res.headersSent) {
  25. sendInternalServerError(res, next, { reason: (err as Error).message })
  26. }
  27. ctx.log.error(err)
  28. }
  29. app.use(catchError)
  30. // Log request after handling
  31. app.use((req, res, next) => {
  32. ctx.log.debug(`[${req.socket.remoteAddress}] ${req.method} ${req.url} ${res.statusCode}`)
  33. next()
  34. })
  35. return app
  36. }
  37. export function sendBadRequest(res: Response, next: NextFunction, data?: Record<string, unknown>) {
  38. res.status(400).send({ message: 'Bad Request', ...data })
  39. next()
  40. }
  41. export function sendForbidden(res: Response, next: NextFunction, data?: Record<string, unknown>) {
  42. res.status(403).send({ message: 'Forbidden', ...data })
  43. next()
  44. }
  45. export function sendInternalServerError(res: Response, next: NextFunction, data?: Record<string, unknown>) {
  46. res.status(500).send({ message: 'Internal Server Error', ...data })
  47. next()
  48. }
  49. export function sendNotFound(res: Response, next: NextFunction, data?: Record<string, unknown>) {
  50. res.status(404).send({ message: 'Not Found', ...data })
  51. next()
  52. }
  53. export function sendUnauthorized(res: Response, next: NextFunction, data?: Record<string, unknown>) {
  54. res.status(401).send({ message: 'Unauthorized', ...data })
  55. next()
  56. }