|
| 1 | +import { isRecord } from '@aws-lambda-powertools/commons/typeutils'; |
| 2 | +import { |
| 3 | + getStringFromEnv, |
| 4 | + isDevMode, |
| 5 | +} from '@aws-lambda-powertools/commons/utils/env'; |
| 6 | +import type { GenericLogger } from '../types/appsync-events.js'; |
| 7 | +import type { |
| 8 | + RouteHandler, |
| 9 | + RouteOptions, |
| 10 | + RouterOptions, |
| 11 | +} from '../types/rest.js'; |
| 12 | + |
| 13 | +abstract class BaseRouter { |
| 14 | + protected context: Record<string, unknown>; // TODO: should this be a map instead? |
| 15 | + /** |
| 16 | + * A logger instance to be used for logging debug, warning, and error messages. |
| 17 | + * |
| 18 | + * When no logger is provided, we'll only log warnings and errors using the global `console` object. |
| 19 | + */ |
| 20 | + protected readonly logger: Pick<GenericLogger, 'debug' | 'warn' | 'error'>; |
| 21 | + /** |
| 22 | + * Whether the router is running in development mode. |
| 23 | + */ |
| 24 | + protected readonly isDev: boolean = false; |
| 25 | + |
| 26 | + public constructor(options?: RouterOptions) { |
| 27 | + this.context = {}; |
| 28 | + const alcLogLevel = getStringFromEnv({ |
| 29 | + key: 'AWS_LAMBDA_LOG_LEVEL', |
| 30 | + defaultValue: '', |
| 31 | + }); |
| 32 | + this.logger = options?.logger ?? { |
| 33 | + debug: alcLogLevel === 'DEBUG' ? console.debug : () => undefined, |
| 34 | + error: console.error, |
| 35 | + warn: console.warn, |
| 36 | + }; |
| 37 | + this.isDev = isDevMode(); |
| 38 | + } |
| 39 | + |
| 40 | + public abstract route(handler: RouteHandler, options: RouteOptions): void; |
| 41 | + |
| 42 | + public get(path: string, handler: RouteHandler, options?: RouteOptions): void; |
| 43 | + public get(path: string, options?: RouteOptions): MethodDecorator; |
| 44 | + public get( |
| 45 | + path: string, |
| 46 | + handler?: RouteHandler | RouteOptions, |
| 47 | + options?: RouteOptions |
| 48 | + ): MethodDecorator | undefined { |
| 49 | + if (handler && typeof handler === 'function') { |
| 50 | + this.route(handler, { |
| 51 | + ...(options || {}), |
| 52 | + method: 'GET', |
| 53 | + path, |
| 54 | + }); |
| 55 | + return; |
| 56 | + } |
| 57 | + |
| 58 | + return (_target, _propertyKey, descriptor: PropertyDescriptor) => { |
| 59 | + const routeOptions = isRecord(handler) ? handler : options; |
| 60 | + this.route(descriptor.value, { |
| 61 | + ...(routeOptions || {}), |
| 62 | + method: 'GET', |
| 63 | + path, |
| 64 | + }); |
| 65 | + return descriptor; |
| 66 | + }; |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +export { BaseRouter }; |
0 commit comments