controller.class.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import { logger } from 'infra/logger.ts';
  2. export default class Controller {
  3. constructor(
  4. public path: string,
  5. public method: string,
  6. public handler: (req: Request) => Response | Promise<Response>,
  7. public headers: Record<string, string> = {},
  8. ) {}
  9. public static response = (req: Request, body?: string, json = false) => {
  10. const url = new URL(req.url);
  11. const output = new TextEncoder().encode(body);
  12. const response = new Response(output);
  13. const userName = this.getUser(req);
  14. if (json) {
  15. response.headers.set('Content-Type', 'application/json');
  16. }
  17. logger.info(
  18. `[${req.method}] ${url.pathname} ${
  19. userName ? userName + ' ' : ''
  20. }${response.status} ${output.byteLength}`,
  21. );
  22. return response;
  23. };
  24. public static responseJSON = (req: Request, body?: unknown) => {
  25. return this.response(req, JSON.stringify(body), true);
  26. };
  27. private static getUser = (req: Request): string | undefined => {
  28. const authHeader = req.headers.get('Authorization');
  29. if (authHeader && authHeader.startsWith('Basic ')) {
  30. const base64Credentials = authHeader.slice(6);
  31. const credentials = atob(base64Credentials);
  32. const [userName] = credentials.split(':');
  33. return userName;
  34. }
  35. return;
  36. };
  37. }