create-chuntianxiaozhu
Version:
春天小猪模板工具
74 lines (69 loc) • 1.9 kB
text/typescript
import {
BadRequestException,
Body,
Controller,
Post,
Req,
} from '@nestjs/common';
import { ShortUrlService } from 'api/common/short-url.service';
import { GenerateUrlDto } from './dtos/generate-url.dto';
import { getUid } from 'api/utils/utils';
import { Request } from 'express';
import ShortUniqueId from 'short-unique-id';
import { CustomUrlDto } from './dtos/custom-url.dto';
const { randomUUID } = new ShortUniqueId({ length: 10 });
('shorturl')
export class ShortUrlController {
constructor(private shortUrlService: ShortUrlService) {}
('generate')
async generateAndQueryUrl(
() req: Request,
() generateUrlDto: GenerateUrlDto,
) {
const uid = getUid(req);
const { url } = generateUrlDto;
const shortUrl = await this.shortUrlService.find({
uid,
originUrl: url,
});
if (shortUrl) {
return shortUrl.shortId;
}
let shortUrlId = randomUUID();
const hasShortUrl = await this.shortUrlService.find({
shortId: shortUrlId,
});
if (hasShortUrl) {
shortUrlId = randomUUID();
}
const result = await this.shortUrlService.save({
uid,
originUrl: url,
shortId: shortUrlId,
});
return result.shortId;
}
('custom')
async customUrl(() req: Request, () customUrlDto: CustomUrlDto) {
const uid = getUid(req);
const { url, name } = customUrlDto;
const shortUrl = await this.shortUrlService.find({
uid,
originUrl: url,
});
const hasShortUrl = await this.shortUrlService.find({
shortId: name,
});
if (hasShortUrl) {
throw new BadRequestException('自定义名称已占用,请换一个');
}
if (shortUrl) {
await this.shortUrlService.delete(shortUrl.id);
}
return await this.shortUrlService.save({
uid,
originUrl: url,
shortId: name,
});
}
}