URL 단축기 만들기 - 9. 리다이렉트를 위한 컨트롤러 만들기
이번엔 드디어...! 본 기능인 리다이렉트 기능을 만들어 볼거에요. 그럼 바로 시작해볼게요.
컨트롤러 생성
nest g co urls
컨트롤러 작성
import { Controller, Get, Param, Redirect } from '@nestjs/common'
import { UrlsService } from './urls.service'
@Controller()
export class UrlsController {
constructor(private urlsService: UrlsService) {}
@Get('/:slug')
@Redirect()
async handle(@Param('slug') slug: string) {
const link = await this.urlsService.findUrlBySlug(slug)
return {
url: link.url,
statusCode: 302,
}
}
}
여기에서 /:slug
에서의 :slug
는 파라미터 이름이에요. handle의 @Param
데코레이터에서 가져와서 쓰고 있고요. 이 slug를 이용해서 url 단축을 처리할 거에요. findUrlBySlug
에서는 단축링크가 존재하지 않으면 알아서 NotFoundException
을 던지기 때문에 따로 처리해주진 않았어요. 일단 여기까지 쓰면 작동은 잘 할거에요. 그럼 이제 테스트코드를 써볼게요.
테스트코드 작성
import { Test, TestingModule } from '@nestjs/testing'
import { DatabaseModule } from 'src/database/database.module'
import { UrlsController } from './urls.controller'
import { UrlsService } from './urls.service'
describe('UrlsController', () => {
let controller: UrlsController
let svc: UrlsService
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [UrlsController],
providers: [UrlsService],
imports: [DatabaseModule],
}).compile()
controller = module.get<UrlsController>(UrlsController)
svc = module.get<UrlsService>(UrlsService)
})
it('should be defined', () => {
expect(controller).toBeDefined()
})
let slug: string
it('create url for test', async () => {
slug = (await svc.createUrl('https://google.com')).slug
})
it('fetch undefined slug', async () => {
await expect(controller.handle('0')).rejects.toThrow(
`Cannot find URL with following slug: 0`,
)
})
it('expect redirection', async () => {
await expect(controller.handle(slug)).resolves.toEqual({
statusCode: 302,
url: 'https://google.com',
})
})
afterAll(async () => {
if (slug) {
await svc.deleteUrl(slug)
}
})
})
이 테스트코드에서는 단축링크를 임시로 생성했다가 제거하는 방법을 쓰고있어요.
이렇게 되면 일단 테스트코드 작성까지 끝나네요! 오늘도 소스코드를 올려놓고 갈게요.(항상 같지만....)
GitHub - paringparing/url-shortener: something
something. Contribute to paringparing/url-shortener development by creating an account on GitHub.