2024/11/16

Implement a Current Language Decorator in NestJS

再Nestjs要取得當前Request語系可以透過Decorator去取得
import { createParamDecorator, ExecutionContext } from '@nestjs/common'
import { Request } from 'express'

/**
 * 取得語系
 * @param data {unknown}
 * @example
 * @Controller('users')
 * export class UserController {
 *   @Get('profile')
 *   getProfile(@CurrentUser() userId: number) {
 *     return { userId };
 *   }
 * }
 *
 * // 與其他guard結合使用
 * @Controller('users')
 * export class UserController {
 *   @UseGuards(JwtAuthGuard)
 *   @Get('profile')
 *   getProfile(@CurrentUser() userId: number) {
 *     return { userId };
 *   }
 * }
 */
export const Lang = createParamDecorator(
    /**
     * Factory
     * @param data {unknown}
     * @param ctx {ExecutionContext}
     * @return {string}
     */
    (data: unknown, ctx: ExecutionContext): string => {
        //取得Http上下文
        const httpContext = ctx.switchToHttp()
        // 取得Request
        const request: Request = httpContext.getRequest()
        // 回傳語系 找不到就預設台灣
        return (request?.headers?.lang as string) || 'zh-TW'
    }
)