返回 AiToEarn
api-key.controller.ts
根目录 / project / aitoearn-backend / apps / aitoearn-server / src / core / api-key / api-key.controller.ts
1 import { Body, Controller, Delete, Get, Param, Post } from '@nestjs/common'
2 import { ApiTags } from '@nestjs/swagger'
3 import { GetToken, TokenInfo } from '@yikart/aitoearn-auth'
4 import { ApiDoc, ParseObjectIdPipe } from '@yikart/common'
5 import { CreateApiKeyDto } from './api-key.dto'
6 import { ApiKeyService } from './api-key.service'
7 import { ApiKeyCreatedVo, ApiKeyItemVo } from './api-key.vo'
8
9 @ApiTags('Auth/API-Key')
10 @Controller('/api-key')
11 export class ApiKeyController {
12 constructor(private readonly apiKeyService: ApiKeyService) {}
13
14 @ApiDoc({
15 summary: '创建 API Key',
16 description: '生成新的 API Key,明文仅返回一次',
17 body: CreateApiKeyDto.schema,
18 response: ApiKeyCreatedVo,
19 })
20 @Post('/create')
21 async create(
22 @GetToken() token: TokenInfo,
23 @Body() dto: CreateApiKeyDto,
24 ): Promise<ApiKeyCreatedVo> {
25 const result = await this.apiKeyService.create(token.id, dto.name)
26 return ApiKeyCreatedVo.create(result)
27 }
28
29 @ApiDoc({
30 summary: '获取 API Key 列表',
31 response: [ApiKeyItemVo],
32 })
33 @Get('/list')
34 async list(
35 @GetToken() token: TokenInfo,
36 ): Promise<ApiKeyItemVo[]> {
37 const keys = await this.apiKeyService.listByUserId(token.id)
38 return keys.map(k => ApiKeyItemVo.create({
39 id: k.id,
40 name: k.name,
41 lastUsedAt: k.lastUsedAt ?? null,
42 createdAt: k.createdAt,
43 }))
44 }
45
46 @ApiDoc({
47 summary: '删除 API Key',
48 })
49 @Delete('/:id')
50 async delete(
51 @GetToken() token: TokenInfo,
52 @Param('id', ParseObjectIdPipe) id: string,
53 ): Promise<void> {
54 await this.apiKeyService.deleteByIdAndUserId(id, token.id)
55 }
56 }
57
57 lines TYPESCRIPT