diff --git a/src/application/create-app.ts b/src/application/create-app.ts index 0f53e372..f43fd845 100644 --- a/src/application/create-app.ts +++ b/src/application/create-app.ts @@ -14,6 +14,7 @@ import legacyErrors from '../middlewares/erros-middleware' import { generatePreview, reportPreview } from '../reports/controller' import { routes as createEstadoRoutes } from './estado' import { routes as createPaisRoutes } from './pais' +import { routes as createVegetacaoRoutes } from './vegetacao' interface CorsParameters { origins: string[] @@ -55,7 +56,8 @@ export function createApp({ }: Parameters) { const routes: Route[] = [ ...createPaisRoutes(knex), - ...createEstadoRoutes(knex) + ...createEstadoRoutes(knex), + ...createVegetacaoRoutes(knex) ] const application = new ExpressApplication({ logger }) diff --git a/src/application/vegetacao/BuscarVegetacaoController.ts b/src/application/vegetacao/BuscarVegetacaoController.ts new file mode 100644 index 00000000..69376b07 --- /dev/null +++ b/src/application/vegetacao/BuscarVegetacaoController.ts @@ -0,0 +1,41 @@ +import { BuscarVegetacaoPorIdUseCase } from '@/domain/vegetacao/BuscarVegetacaoPorIdUseCase' +import { + HttpRequest, HttpResponse, StatusCode +} from '@/library/http/common' +import { BadRequestError } from '@/library/http/error/BadRequestError' +import { HttpError } from '@/library/http/error/HttpError' +import { InternalServerError } from '@/library/http/error/InternalServerError' +import { NotFoundError } from '@/library/http/error/NotFoundError' +import { NextHandler, RequestHandler } from '@/library/http/Server' + +interface Dependencies { + buscarVegetacaoPorIdUseCase: BuscarVegetacaoPorIdUseCase +} + +export class BuscarVegetacaoController implements RequestHandler { + private readonly buscarVegetacaoPorIdUseCase: BuscarVegetacaoPorIdUseCase + + constructor(dependencies: Dependencies) { + this.buscarVegetacaoPorIdUseCase = dependencies.buscarVegetacaoPorIdUseCase + } + + async handle(request: HttpRequest, _next: NextHandler): Promise { + const { vegetacaoId } = request.params as { vegetacaoId?: string } + + if (vegetacaoId === undefined || vegetacaoId === null || vegetacaoId === '' || !/^\d+$/.test(vegetacaoId)) { + return new BadRequestError({ message: 'vegetacaoId inválido' }) + } + + const result = await this.buscarVegetacaoPorIdUseCase.execute({ id: Number(vegetacaoId) }) + + if (result.left()) { + return new InternalServerError({ message: result.value.message }) + } + + if (!result.value) { + return new NotFoundError({ message: 'Vegetação não encontrada' }) + } + + return { statusCode: StatusCode.Ok, body: result.value } + } +} diff --git a/src/application/vegetacao/ListaVegetacoesController.ts b/src/application/vegetacao/ListaVegetacoesController.ts new file mode 100644 index 00000000..18d05692 --- /dev/null +++ b/src/application/vegetacao/ListaVegetacoesController.ts @@ -0,0 +1,65 @@ +import { ListaVegetacoesUseCase } from '@/domain/vegetacao/ListaVegetacoesUseCase' +import { + HttpRequest, HttpResponse, StatusCode +} from '@/library/http/common' +import { BadRequestError } from '@/library/http/error/BadRequestError' +import { HttpError } from '@/library/http/error/HttpError' +import { InternalServerError } from '@/library/http/error/InternalServerError' +import { NextHandler, RequestHandler } from '@/library/http/Server' + +interface Dependencies { + listaVegetacoesUseCase: ListaVegetacoesUseCase +} + +export class ListaVegetacoesController implements RequestHandler { + private readonly listaVegetacoesUseCase: ListaVegetacoesUseCase + + constructor(dependencies: Dependencies) { + this.listaVegetacoesUseCase = dependencies.listaVegetacoesUseCase + } + + async handle(request: HttpRequest, _next: NextHandler): Promise { + const { nome, order } = request.params as { + nome?: string + order?: string + } + + const parsedOrder = parseOrder(order) + if (parsedOrder instanceof Error) { + return new BadRequestError({ message: parsedOrder.message }) + } + + const result = await this.listaVegetacoesUseCase.execute({ + nome, + order: parsedOrder + }) + + if (result.left()) { + return new InternalServerError({ message: result.value.message }) + } + + return { statusCode: StatusCode.Ok, body: result.value } + } +} + +function parseOrder(order?: string): { column: 'id' | 'nome'; direction: 'asc' | 'desc' } | Error | undefined { + if (!order) return undefined + + const pieces = order.split(':') + if (pieces.length !== 2) { + return new Error('order inválido. Use o formato "id:asc", "id:desc", "nome:asc" ou "nome:desc"') + } + + const [rawColumn, rawDirection] = pieces + const column = rawColumn.trim().toLowerCase() + const direction = rawDirection.trim().toLowerCase() + + if ((column !== 'id' && column !== 'nome') || (direction !== 'asc' && direction !== 'desc')) { + return new Error('order inválido. Use o formato "id:asc", "id:desc", "nome:asc" ou "nome:desc"') + } + + return { + column, + direction + } +} diff --git a/src/application/vegetacao/index.ts b/src/application/vegetacao/index.ts new file mode 100644 index 00000000..e591fe33 --- /dev/null +++ b/src/application/vegetacao/index.ts @@ -0,0 +1,35 @@ +import { type Knex } from 'knex' + +import { BuscarVegetacaoPorIdUseCase } from '@/domain/vegetacao/BuscarVegetacaoPorIdUseCase' +import { ListaVegetacoesUseCase } from '@/domain/vegetacao/ListaVegetacoesUseCase' +import { VegetacaoCollectionKnexAdapter } from '@/infrastructure/VegetacaoCollectionKnexAdapter' +import { Method } from '@/library/http/common' +import { Route } from '@/library/http/Router' + +import { BuscarVegetacaoController } from './BuscarVegetacaoController' +import { ListaVegetacoesController } from './ListaVegetacoesController' + +export function routes(knex: Knex): Route[] { + const vegetacaoCollection = new VegetacaoCollectionKnexAdapter({ knex }) + + return [ + { + handlers: [ + new ListaVegetacoesController({ + listaVegetacoesUseCase: new ListaVegetacoesUseCase({ vegetacaoCollection }) + }) + ], + method: Method.Get, + path: '/v2/vegetacoes' + }, + { + handlers: [ + new BuscarVegetacaoController({ + buscarVegetacaoPorIdUseCase: new BuscarVegetacaoPorIdUseCase({ vegetacaoCollection }) + }) + ], + method: Method.Get, + path: '/v2/vegetacoes/:vegetacaoId' + } + ] +} diff --git a/src/domain/vegetacao/BuscarVegetacaoPorIdUseCase.ts b/src/domain/vegetacao/BuscarVegetacaoPorIdUseCase.ts new file mode 100644 index 00000000..2a855098 --- /dev/null +++ b/src/domain/vegetacao/BuscarVegetacaoPorIdUseCase.ts @@ -0,0 +1,20 @@ +import { Either } from '@/library/either/Either' + +import { Attributes } from './Vegetacao' +import { VegetacaoCollection } from './VegetacaoCollection' + +interface Dependencies { + vegetacaoCollection: VegetacaoCollection +} + +export class BuscarVegetacaoPorIdUseCase { + private readonly vegetacaoCollection: VegetacaoCollection + + constructor(dependencies: Dependencies) { + this.vegetacaoCollection = dependencies.vegetacaoCollection + } + + execute({ id }: { id: number }): Promise> { + return this.vegetacaoCollection.findById(id) + } +} diff --git a/src/domain/vegetacao/ListaVegetacoesUseCase.ts b/src/domain/vegetacao/ListaVegetacoesUseCase.ts new file mode 100644 index 00000000..42165b2d --- /dev/null +++ b/src/domain/vegetacao/ListaVegetacoesUseCase.ts @@ -0,0 +1,20 @@ +import { Either } from '@/library/either/Either' + +import { Attributes } from './Vegetacao' +import { VegetacaoCollection, VegetacaoFilters } from './VegetacaoCollection' + +interface Dependencies { + vegetacaoCollection: VegetacaoCollection +} + +export class ListaVegetacoesUseCase { + private readonly vegetacaoCollection: VegetacaoCollection + + constructor(dependencies: Dependencies) { + this.vegetacaoCollection = dependencies.vegetacaoCollection + } + + execute(filters: VegetacaoFilters): Promise> { + return this.vegetacaoCollection.findAll(filters) + } +} diff --git a/src/domain/vegetacao/Vegetacao.ts b/src/domain/vegetacao/Vegetacao.ts new file mode 100644 index 00000000..824e17e7 --- /dev/null +++ b/src/domain/vegetacao/Vegetacao.ts @@ -0,0 +1,24 @@ +import { Either } from '@/library/either/Either' + +export interface Attributes { + id: number + nome: string +} + +export class Vegetacao { + readonly id: number + readonly nome: string + + private constructor(attributes: Attributes) { + this.id = attributes.id + this.nome = attributes.nome + } + + static create(attributes: Attributes): Either { + if (!attributes.nome.trim()) { + return Either.left(new Error('Nome da vegetação não pode ser vazio')) + } + + return Either.right(new Vegetacao(attributes)) + } +} diff --git a/src/domain/vegetacao/VegetacaoCollection.ts b/src/domain/vegetacao/VegetacaoCollection.ts new file mode 100644 index 00000000..13ab350d --- /dev/null +++ b/src/domain/vegetacao/VegetacaoCollection.ts @@ -0,0 +1,18 @@ +import { Either } from '@/library/either/Either' + +import { Attributes } from './Vegetacao' + +export interface VegetacaoOrder { + column: 'id' | 'nome' + direction: 'asc' | 'desc' +} + +export interface VegetacaoFilters { + nome?: string + order?: VegetacaoOrder +} + +export interface VegetacaoCollection { + findAll(filters: VegetacaoFilters): Promise> + findById(id: number): Promise> +} diff --git a/src/infrastructure/VegetacaoCollectionKnexAdapter.ts b/src/infrastructure/VegetacaoCollectionKnexAdapter.ts new file mode 100644 index 00000000..42de847d --- /dev/null +++ b/src/infrastructure/VegetacaoCollectionKnexAdapter.ts @@ -0,0 +1,46 @@ +import { Knex } from 'knex' + +import { Attributes } from '@/domain/vegetacao/Vegetacao' +import { VegetacaoCollection, VegetacaoFilters } from '@/domain/vegetacao/VegetacaoCollection' +import { Either } from '@/library/either/Either' + +import { CollectionError } from './error/CollectionError' + +interface Dependencies { + knex: Knex +} + +export class VegetacaoCollectionKnexAdapter implements VegetacaoCollection { + private readonly knex: Knex + + constructor(dependencies: Dependencies) { + this.knex = dependencies.knex + } + + async findAll(filters: VegetacaoFilters): Promise> { + try { + const query = this.knex('vegetacoes') + .select(['id', 'nome']) + + if (filters.nome) { + query.whereILike('nome', `%${filters.nome}%`) + } + + const order = filters.order ?? { column: 'id', direction: 'desc' } + query.orderBy(order.column, order.direction) + + return Either.right(await query) + } catch (error) { + return Either.left(new CollectionError({ message: 'Failed to list vegetações', cause: error })) + } + } + + async findById(id: number): Promise> { + try { + const vegetacao = await this.knex('vegetacoes').select(['id', 'nome']).where({ id }).first() + return Either.right(vegetacao ?? null) + } catch (error) { + return Either.left(new CollectionError({ message: 'Failed to find vegetação', cause: error })) + } + } +} diff --git a/test/integration/vegetacao/lista-vegetacoes.test.ts b/test/integration/vegetacao/lista-vegetacoes.test.ts new file mode 100644 index 00000000..9f64d264 --- /dev/null +++ b/test/integration/vegetacao/lista-vegetacoes.test.ts @@ -0,0 +1,129 @@ +import { + afterAll, describe, expect, test +} from 'vitest' + +import { createTestApp } from '../setup/app-factory' + +type Vegetacao = { id: number; nome: string } + +const returning = ['id', 'nome'] as const + +describe('GET /api/v2/vegetacoes', () => { + const { agent, knex } = createTestApp() + + afterAll(() => knex.destroy()) + + test('retorna a lista ordenada por id decrescente como padrão dentro do prefixo do teste', async () => { + const prefix = 'XVEG' + const nomes = [ + `${prefix} Mata Atlântica`, + `${prefix} Restinga`, + `${prefix} Campo` + ] + + const inserted = await knex('vegetacoes') + .insert(nomes.map(nome => ({ nome }))) + .returning(returning) + + try { + const response = await agent.get(`/api/v2/vegetacoes?nome=${prefix}`).expect(200) + const expected = [...inserted].sort((a, b) => b.id - a.id) + expect(response.body).toEqual(expected) + } finally { + await knex('vegetacoes').whereIn('nome', nomes).delete() + } + }) + + test('filtra por nome sem diferenciar maiúsculas e minúsculas', async () => { + const prefix = 'XVEG' + const nomes = [ + `${prefix} Floresta`, + `${prefix} Cerrado`, + `${prefix} Outros` + ] + const inserted = await knex('vegetacoes') + .insert(nomes.map(nome => ({ nome }))) + .returning(returning) + + try { + const response = await agent.get(`/api/v2/vegetacoes?nome=${prefix} floresta`).expect(200) + expect(response.body).toEqual(inserted.filter(item => item.nome === `${prefix} Floresta`)) + } finally { + await knex('vegetacoes').whereIn('nome', nomes).delete() + } + }) + + test('aceita ordenação customizada por nome e id', async () => { + const prefix = 'XVEG' + const nomes = [ + `${prefix} Z`, + `${prefix} A`, + `${prefix} M` + ] + const inserted = await knex('vegetacoes') + .insert(nomes.map(nome => ({ nome }))) + .returning(returning) + + try { + const byNameAsc = await agent.get(`/api/v2/vegetacoes?nome=${prefix}&order=nome:asc`).expect(200) + expect(byNameAsc.body).toEqual([...inserted].sort((a, b) => a.nome.localeCompare(b.nome))) + + const byIdAsc = await agent.get(`/api/v2/vegetacoes?nome=${prefix}&order=id:asc`).expect(200) + expect(byIdAsc.body).toEqual([...inserted].sort((a, b) => a.id - b.id)) + } finally { + await knex('vegetacoes').whereIn('nome', nomes).delete() + } + }) + + test('retorna 400 quando a ordenação é inválida', async () => { + const prefix = 'XVEG' + const nomes = [ + `${prefix} Z`, + `${prefix} A`, + `${prefix} M` + ] + + await knex('vegetacoes').insert(nomes.map(nome => ({ nome }))) + + try { + const response = await agent.get(`/api/v2/vegetacoes?nome=${prefix}&order=foo:bar`).expect(400) + const body = response.body as { error: { message: string } } + expect(body.error.message).toMatch(/inválido|invalid/i) + } finally { + await knex('vegetacoes').whereIn('nome', nomes).delete() + } + }) +}) + +describe('GET /api/v2/vegetacoes/:vegetacaoId', () => { + const { agent, knex } = createTestApp() + + afterAll(() => knex.destroy()) + + test('retorna o registro encontrado', async () => { + const [vegetacao] = await knex('vegetacoes') + .insert({ nome: 'XVEG Vegetação Encontrada' }) + .returning(returning) + + try { + const response = await agent.get(`/api/v2/vegetacoes/${vegetacao.id}`).expect(200) + expect(response.body).toEqual({ id: vegetacao.id, nome: vegetacao.nome }) + } finally { + await knex('vegetacoes').where({ id: vegetacao.id }).delete() + } + }) + + test('retorna 404 para id inexistente', async () => { + const response = await agent.get('/api/v2/vegetacoes/999999').expect(404) + const body = response.body as { error: { message: string } } + + expect(body.error.message).toMatch(/não encontrad[ao]|not found/i) + }) + + test('retorna 400 para id inválido', async () => { + const response = await agent.get('/api/v2/vegetacoes/abc').expect(400) + const body = response.body as { error: { message: string } } + + expect(body.error.message).toMatch(/inválido|invalid/i) + }) +})