返回 AiToEarn
api-key.service.spec.ts
根目录 / project / aitoearn-backend / apps / aitoearn-server / src / core / api-key / api-key.service.spec.ts
1 import { createHash } from 'node:crypto'
2 import { describe, expect, it, vi } from 'vitest'
3 import { ApiKeyService } from './api-key.service'
4
5 vi.mock('../../config', () => ({
6 config: {
7 apiKey: {
8 prefix: 'ai_',
9 },
10 },
11 }))
12
13 vi.mock('@yikart/mongodb', () => ({
14 ApiKeyRepository: class {},
15 }))
16
17 describe('apiKeyService', () => {
18 it('创建 API Key 时使用配置的前缀并保存明文 key 的 hash', async () => {
19 const createdAt = new Date('2026-06-12T00:00:00.000Z')
20 const apiKeyRepository = {
21 create: vi.fn().mockResolvedValue({
22 id: 'api-key-1',
23 name: 'test key',
24 createdAt,
25 }),
26 }
27 const service = new ApiKeyService(apiKeyRepository as any)
28
29 const result = await service.create('user-1', 'test key')
30
31 expect(result.key).toMatch(/^ai_[0-9A-Za-z]{48}$/)
32 expect(apiKeyRepository.create).toHaveBeenCalledWith({
33 userId: 'user-1',
34 name: 'test key',
35 keyHash: createHash('sha1').update(result.key).digest('hex'),
36 })
37 expect(result).toEqual({
38 id: 'api-key-1',
39 name: 'test key',
40 key: result.key,
41 createdAt,
42 })
43 })
44 })
45
45 lines TYPESCRIPT