| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- import { logger } from 'infra/logger.ts';
- export default class Controller {
- constructor(
- public path: string,
- public method: string,
- public handler: (req: Request) => Response | Promise<Response>,
- public headers: Record<string, string> = {},
- ) {}
- public static response = (req: Request, body?: string, json = false) => {
- const url = new URL(req.url);
- const output = new TextEncoder().encode(body);
- const response = new Response(output);
- const userName = this.getUser(req);
- if (json) {
- response.headers.set('Content-Type', 'application/json');
- }
- logger.info(
- `[${req.method}] ${url.pathname} ${
- userName ? userName + ' ' : ''
- }${response.status} ${output.byteLength}`,
- );
- return response;
- };
- public static responseJSON = (req: Request, body?: unknown) => {
- return this.response(req, JSON.stringify(body), true);
- };
- private static getUser = (req: Request): string | undefined => {
- const authHeader = req.headers.get('Authorization');
- if (authHeader && authHeader.startsWith('Basic ')) {
- const base64Credentials = authHeader.slice(6);
- const credentials = atob(base64Credentials);
- const [userName] = credentials.split(':');
- return userName;
- }
- return;
- };
- }
|