32 lines
985 B
TypeScript
32 lines
985 B
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import * as shortid from 'shortid';
|
|
import { DnsService } from '../dns/dns.service';
|
|
import { HttpException, HttpStatus } from '@nestjs/common';
|
|
|
|
|
|
@Injectable()
|
|
export class UrlShortenerService {
|
|
|
|
private urlMap = new Map<string, string>();
|
|
|
|
constructor(private readonly dnsService: DnsService) {}
|
|
|
|
async generateShortUrl(originalUrl: string): Promise<string> {
|
|
if (!originalUrl) {
|
|
throw new HttpException('URL is required', HttpStatus.BAD_REQUEST);
|
|
}
|
|
const isValid = await this.dnsService.isValidUrl(originalUrl);
|
|
if (!isValid) {
|
|
throw new HttpException('URL is invalid', HttpStatus.BAD_REQUEST);
|
|
}
|
|
const shortUrl = "tiny." + shortid.generate() + ".com";
|
|
this.urlMap.set(shortUrl, originalUrl);
|
|
return shortUrl;
|
|
}
|
|
|
|
getOriginalUrl(shortUrl: string): string | undefined {
|
|
let url: string | undefined = this.urlMap.get(shortUrl);
|
|
if (url) return url;
|
|
return undefined;
|
|
}
|
|
} |