返回 AiToEarn
short-link.service.ts
根目录 / project / aitoearn-backend / apps / aitoearn-server / src / core / short-link / short-link.service.ts
1 import crypto from 'node:crypto'
2 import { Injectable, Logger } from '@nestjs/common'
3 import { AppException, ResponseCode } from '@yikart/common'
4 import { ServerRedisService } from '../../common/redis'
5 import { config } from '../../config'
6
7 @Injectable()
8 export class ShortLinkService {
9 private readonly logger = new Logger(ShortLinkService.name)
10
11 constructor(
12 private readonly redisService: ServerRedisService,
13 ) {}
14
15 private generateCode(length = 8): string {
16 const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
17 const randomBytes = crypto.randomBytes(length)
18 let result = ''
19 for (let i = 0; i < length; i++) {
20 result += chars[randomBytes[i] % chars.length]
21 }
22 return result
23 }
24
25 async create(originalUrl: string): Promise<string> {
26 const code = this.generateCode()
27
28 await this.redisService.saveShortLink(code, originalUrl)
29
30 return `${config.channel.shortLink.baseUrl}${code}`
31 }
32
33 async getByCode(code: string): Promise<string> {
34 const originalUrl = await this.redisService.getShortLink(code)
35
36 if (!originalUrl) {
37 throw new AppException(ResponseCode.ShortLinkNotFound)
38 }
39
40 return originalUrl
41 }
42 }
43
43 lines TYPESCRIPT