|
| 1 | +import { All, Request, Response } from '@nestjs/common' |
| 2 | +import { Throttle } from '@nestjs/throttler' |
| 3 | +import { ApiController } from '~/common/decorators/api-controller.decorator' |
| 4 | +import { HTTPDecorators } from '~/common/decorators/http.decorator' |
| 5 | +import { IsAuthenticated } from '~/common/decorators/role.decorator' |
| 6 | +import { BizException } from '~/common/exceptions/biz.exception' |
| 7 | +import { ErrorCodeEnum } from '~/constants/error-code.constant' |
| 8 | +import type { FastifyReply, FastifyRequest } from 'fastify' |
| 9 | +import { createMockedContextResponse } from '../serverless/mock-response.util' |
| 10 | +import { ServerlessService } from '../serverless/serverless.service' |
| 11 | +import type { SnippetModel } from './snippet.model' |
| 12 | +import { SnippetService } from './snippet.service' |
| 13 | + |
| 14 | +const MAX_PREFIX_DEPTH = 10 |
| 15 | + |
| 16 | +@ApiController('s') |
| 17 | +export class SnippetRouteController { |
| 18 | + constructor( |
| 19 | + private readonly snippetService: SnippetService, |
| 20 | + private readonly serverlessService: ServerlessService, |
| 21 | + ) {} |
| 22 | + |
| 23 | + @All('*') |
| 24 | + @Throttle({ |
| 25 | + default: { |
| 26 | + limit: 100, |
| 27 | + ttl: 5000, |
| 28 | + }, |
| 29 | + }) |
| 30 | + @HTTPDecorators.Bypass |
| 31 | + async handleCustomPath( |
| 32 | + @IsAuthenticated() isAuthenticated: boolean, |
| 33 | + @Request() req: FastifyRequest, |
| 34 | + @Response() reply: FastifyReply, |
| 35 | + ) { |
| 36 | + const rawPath = req.url |
| 37 | + const sPrefixIndex = rawPath.indexOf('/s') |
| 38 | + const subPath = rawPath.slice(Math.max(0, sPrefixIndex + 2)) |
| 39 | + const path = subPath.replaceAll(/^\/+|\/+$/g, '') |
| 40 | + |
| 41 | + const method = req.method.toUpperCase() |
| 42 | + |
| 43 | + // 1. Exact match — data type snippet |
| 44 | + const dataSnippet = await this.snippetService.getSnippetByCustomPath(path) |
| 45 | + |
| 46 | + if (dataSnippet) { |
| 47 | + if (dataSnippet.private && !isAuthenticated) { |
| 48 | + throw new BizException(ErrorCodeEnum.SnippetPrivate) |
| 49 | + } |
| 50 | + |
| 51 | + // check cache |
| 52 | + let cached: string | null = null |
| 53 | + if (isAuthenticated) { |
| 54 | + cached = |
| 55 | + ( |
| 56 | + await Promise.all( |
| 57 | + (['public', 'private'] as const).map((type) => |
| 58 | + this.snippetService.getCachedSnippetByCustomPath(path, type), |
| 59 | + ), |
| 60 | + ) |
| 61 | + ).find(Boolean) || null |
| 62 | + } else { |
| 63 | + cached = await this.snippetService.getCachedSnippetByCustomPath( |
| 64 | + path, |
| 65 | + 'public', |
| 66 | + ) |
| 67 | + } |
| 68 | + |
| 69 | + if (cached) { |
| 70 | + const json = JSON.safeParse(cached) |
| 71 | + return reply.send(json || cached) |
| 72 | + } |
| 73 | + |
| 74 | + const attached = await this.snippetService.attachSnippet(dataSnippet) |
| 75 | + await this.snippetService.cacheSnippetByCustomPath( |
| 76 | + path, |
| 77 | + !!attached.private, |
| 78 | + attached.data, |
| 79 | + ) |
| 80 | + return reply.send(attached.data) |
| 81 | + } |
| 82 | + |
| 83 | + // 2. Exact match — function type snippet |
| 84 | + const fnSnippet = await this.snippetService.getFunctionSnippetByCustomPath( |
| 85 | + path, |
| 86 | + method, |
| 87 | + ) |
| 88 | + if (fnSnippet) { |
| 89 | + return this.executeFunction(fnSnippet, isAuthenticated, req, reply) |
| 90 | + } |
| 91 | + |
| 92 | + // 3. Prefix match for function type (extra path info) |
| 93 | + const segments = path.split('/') |
| 94 | + const candidatePaths: string[] = [] |
| 95 | + for ( |
| 96 | + let i = segments.length - 1; |
| 97 | + i >= 1 && candidatePaths.length < MAX_PREFIX_DEPTH; |
| 98 | + i-- |
| 99 | + ) { |
| 100 | + candidatePaths.push(segments.slice(0, i).join('/')) |
| 101 | + } |
| 102 | + |
| 103 | + if (candidatePaths.length > 0) { |
| 104 | + const prefixSnippet = |
| 105 | + await this.snippetService.getFunctionSnippetByCustomPathPrefix( |
| 106 | + candidatePaths, |
| 107 | + method, |
| 108 | + ) |
| 109 | + if (prefixSnippet) { |
| 110 | + return this.executeFunction(prefixSnippet, isAuthenticated, req, reply) |
| 111 | + } |
| 112 | + } |
| 113 | + |
| 114 | + throw new BizException(ErrorCodeEnum.SnippetNotFound) |
| 115 | + } |
| 116 | + |
| 117 | + private async executeFunction( |
| 118 | + snippet: SnippetModel, |
| 119 | + isAuthenticated: boolean, |
| 120 | + req: FastifyRequest, |
| 121 | + reply: FastifyReply, |
| 122 | + ) { |
| 123 | + if (!snippet.enable) { |
| 124 | + throw new BizException( |
| 125 | + ErrorCodeEnum.InvalidParameter, |
| 126 | + 'serverless function is not enabled', |
| 127 | + ) |
| 128 | + } |
| 129 | + |
| 130 | + if (snippet.private && !isAuthenticated) { |
| 131 | + throw new BizException(ErrorCodeEnum.ServerlessNoPermission) |
| 132 | + } |
| 133 | + |
| 134 | + const result = |
| 135 | + await this.serverlessService.injectContextIntoServerlessFunctionAndCall( |
| 136 | + snippet, |
| 137 | + { req, res: createMockedContextResponse(reply), isAuthenticated }, |
| 138 | + ) |
| 139 | + |
| 140 | + if (!reply.sent) { |
| 141 | + return reply.send(result) |
| 142 | + } |
| 143 | + } |
| 144 | +} |
0 commit comments