feat: initial API Ubigeo Peru - INEI 2025 + países del mundo
This commit is contained in:
BIN
src/.DS_Store
vendored
Normal file
BIN
src/.DS_Store
vendored
Normal file
Binary file not shown.
22
src/app.controller.spec.ts
Normal file
22
src/app.controller.spec.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AppController } from './app.controller';
|
||||
import { AppService } from './app.service';
|
||||
|
||||
describe('AppController', () => {
|
||||
let appController: AppController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const app: TestingModule = await Test.createTestingModule({
|
||||
controllers: [AppController],
|
||||
providers: [AppService],
|
||||
}).compile();
|
||||
|
||||
appController = app.get<AppController>(AppController);
|
||||
});
|
||||
|
||||
describe('root', () => {
|
||||
it('should return "Hello World!"', () => {
|
||||
expect(appController.getHello()).toBe('Hello World!');
|
||||
});
|
||||
});
|
||||
});
|
||||
12
src/app.controller.ts
Normal file
12
src/app.controller.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { AppService } from './app.service';
|
||||
|
||||
@Controller()
|
||||
export class AppController {
|
||||
constructor(private readonly appService: AppService) {}
|
||||
|
||||
@Get()
|
||||
getHello(): string {
|
||||
return this.appService.getHello();
|
||||
}
|
||||
}
|
||||
21
src/app.module.ts
Normal file
21
src/app.module.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { ThrottlerModule, ThrottlerGuard } from '@nestjs/throttler';
|
||||
import { APP_GUARD } from '@nestjs/core';
|
||||
import { PrismaModule } from './prisma/prisma.module';
|
||||
import { UbigeoModule } from './modules/ubigeo/ubigeo.module';
|
||||
import { PaisesModule } from './modules/paises/paises.module';
|
||||
import { HealthModule } from './modules/health/health.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({ isGlobal: true }),
|
||||
ThrottlerModule.forRoot([{ ttl: 60000, limit: 200 }]),
|
||||
PrismaModule,
|
||||
UbigeoModule,
|
||||
PaisesModule,
|
||||
HealthModule,
|
||||
],
|
||||
providers: [{ provide: APP_GUARD, useClass: ThrottlerGuard }],
|
||||
})
|
||||
export class AppModule {}
|
||||
8
src/app.service.ts
Normal file
8
src/app.service.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class AppService {
|
||||
getHello(): string {
|
||||
return 'Hello World!';
|
||||
}
|
||||
}
|
||||
46
src/main.ts
Normal file
46
src/main.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||
import * as helmet from 'helmet';
|
||||
import { AppModule } from './app.module';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
|
||||
app.setGlobalPrefix('api/v1');
|
||||
|
||||
app.enableCors({ origin: '*' });
|
||||
|
||||
app.use(helmet.default());
|
||||
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
whitelist: true,
|
||||
forbidNonWhitelisted: false,
|
||||
transform: true,
|
||||
transformOptions: { enableImplicitConversion: true },
|
||||
}),
|
||||
);
|
||||
|
||||
const config = new DocumentBuilder()
|
||||
.setTitle('API Ubigeo Peru')
|
||||
.setDescription(
|
||||
'API de ubicaciones geográficas del Perú (departamentos, provincias, distritos) y países del mundo. Fuente: INEI 2025.',
|
||||
)
|
||||
.setVersion('1.0')
|
||||
.addTag('ubigeo', 'Departamentos, provincias y distritos del Perú')
|
||||
.addTag('paises', 'Países del mundo')
|
||||
.addTag('health', 'Estado del servicio')
|
||||
.build();
|
||||
|
||||
const document = SwaggerModule.createDocument(app, config);
|
||||
SwaggerModule.setup('api/docs', app, document, {
|
||||
swaggerOptions: { persistAuthorization: true },
|
||||
});
|
||||
|
||||
const port = process.env.PORT ?? 3200;
|
||||
await app.listen(port);
|
||||
console.log(`API Ubigeo corriendo en: http://localhost:${port}/api/v1`);
|
||||
console.log(`Swagger docs: http://localhost:${port}/api/docs`);
|
||||
}
|
||||
bootstrap();
|
||||
BIN
src/modules/.DS_Store
vendored
Normal file
BIN
src/modules/.DS_Store
vendored
Normal file
Binary file not shown.
20
src/modules/health/health.controller.ts
Normal file
20
src/modules/health/health.controller.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { ApiTags, ApiOperation } from '@nestjs/swagger';
|
||||
import { SkipThrottle } from '@nestjs/throttler';
|
||||
|
||||
@ApiTags('health')
|
||||
@Controller('health')
|
||||
@SkipThrottle()
|
||||
export class HealthController {
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'Health check' })
|
||||
check() {
|
||||
return { status: 'ok', service: 'api-ubigeo', timestamp: new Date().toISOString(), uptime: process.uptime() };
|
||||
}
|
||||
|
||||
@Get('liveness')
|
||||
liveness() { return { status: 'ok' }; }
|
||||
|
||||
@Get('readiness')
|
||||
readiness() { return { status: 'ok' }; }
|
||||
}
|
||||
5
src/modules/health/health.module.ts
Normal file
5
src/modules/health/health.module.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { HealthController } from './health.controller';
|
||||
|
||||
@Module({ controllers: [HealthController] })
|
||||
export class HealthModule {}
|
||||
32
src/modules/paises/paises.controller.ts
Normal file
32
src/modules/paises/paises.controller.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { Controller, Get, Param, Query } from '@nestjs/common';
|
||||
import { ApiTags, ApiOperation, ApiParam, ApiQuery } from '@nestjs/swagger';
|
||||
import { PaisesService } from './paises.service';
|
||||
|
||||
@ApiTags('paises')
|
||||
@Controller('paises')
|
||||
export class PaisesController {
|
||||
constructor(private readonly svc: PaisesService) {}
|
||||
|
||||
@Get('stats')
|
||||
@ApiOperation({ summary: 'Estadísticas de países' })
|
||||
getStats() { return this.svc.getStats(); }
|
||||
|
||||
@Get('regiones')
|
||||
@ApiOperation({ summary: 'Listar regiones del mundo' })
|
||||
getRegiones() { return this.svc.getRegiones(); }
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: 'Listar países (filtrar con ?q= o ?region=)' })
|
||||
@ApiQuery({ name: 'q', required: false, description: 'Buscar por nombre o código ISO' })
|
||||
@ApiQuery({ name: 'region', required: false, description: 'Filtrar por región' })
|
||||
getPaises(@Query('q') q?: string, @Query('region') region?: string) {
|
||||
return this.svc.getPaises(q, region);
|
||||
}
|
||||
|
||||
@Get(':codigo')
|
||||
@ApiOperation({ summary: 'Obtener país por código ISO (PE, PER, etc.)' })
|
||||
@ApiParam({ name: 'codigo', description: 'Código ISO alpha-2 (PE) o alpha-3 (PER)', example: 'PE' })
|
||||
getPais(@Param('codigo') codigo: string) {
|
||||
return this.svc.getPais(codigo);
|
||||
}
|
||||
}
|
||||
10
src/modules/paises/paises.module.ts
Normal file
10
src/modules/paises/paises.module.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PaisesController } from './paises.controller';
|
||||
import { PaisesService } from './paises.service';
|
||||
|
||||
@Module({
|
||||
controllers: [PaisesController],
|
||||
providers: [PaisesService],
|
||||
exports: [PaisesService],
|
||||
})
|
||||
export class PaisesModule {}
|
||||
70
src/modules/paises/paises.service.ts
Normal file
70
src/modules/paises/paises.service.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
|
||||
@Injectable()
|
||||
export class PaisesService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async getPaises(search?: string, region?: string) {
|
||||
const where: any = { activo: true };
|
||||
if (search) {
|
||||
where.OR = [
|
||||
{ nombre: { contains: search, mode: 'insensitive' } },
|
||||
{ nombreEn: { contains: search, mode: 'insensitive' } },
|
||||
{ codigo: { equals: search.toUpperCase() } },
|
||||
{ codigoAlpha2: { equals: search.toUpperCase() } },
|
||||
];
|
||||
}
|
||||
if (region) {
|
||||
where.region = { contains: region, mode: 'insensitive' };
|
||||
}
|
||||
return this.prisma.pais.findMany({
|
||||
where,
|
||||
orderBy: { nombre: 'asc' },
|
||||
select: {
|
||||
codigo: true,
|
||||
codigoAlpha2: true,
|
||||
nombre: true,
|
||||
nombreEn: true,
|
||||
capital: true,
|
||||
region: true,
|
||||
subregion: true,
|
||||
emoji: true,
|
||||
latitud: true,
|
||||
longitud: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async getPais(codigo: string) {
|
||||
const where = codigo.length === 2
|
||||
? { codigoAlpha2: codigo.toUpperCase() }
|
||||
: { codigo: codigo.toUpperCase() };
|
||||
|
||||
const pais = await this.prisma.pais.findFirst({ where });
|
||||
if (!pais) throw new NotFoundException(`País '${codigo}' no encontrado`);
|
||||
return pais;
|
||||
}
|
||||
|
||||
async getRegiones() {
|
||||
const result = await this.prisma.pais.findMany({
|
||||
where: { activo: true },
|
||||
distinct: ['region'],
|
||||
select: { region: true },
|
||||
orderBy: { region: 'asc' },
|
||||
});
|
||||
return result.map((r) => r.region);
|
||||
}
|
||||
|
||||
async getStats() {
|
||||
const [total, regiones] = await Promise.all([
|
||||
this.prisma.pais.count({ where: { activo: true } }),
|
||||
this.prisma.pais.findMany({
|
||||
where: { activo: true },
|
||||
distinct: ['region'],
|
||||
select: { region: true },
|
||||
}),
|
||||
]);
|
||||
return { total, regiones: regiones.length };
|
||||
}
|
||||
}
|
||||
61
src/modules/ubigeo/dto/ubigeo.dto.ts
Normal file
61
src/modules/ubigeo/dto/ubigeo.dto.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsOptional, IsString, MinLength } from 'class-validator';
|
||||
import { Type } from 'class-transformer';
|
||||
|
||||
export class SearchDto {
|
||||
@ApiPropertyOptional({ description: 'Texto de búsqueda', example: 'Lima' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MinLength(2)
|
||||
q?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Página', default: 1 })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
page?: number = 1;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Resultados por página', default: 50 })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
limit?: number = 50;
|
||||
}
|
||||
|
||||
export class DepartamentoDto {
|
||||
@ApiProperty({ example: '15' }) codigo: string;
|
||||
@ApiProperty({ example: 'Lima' }) nombre: string;
|
||||
@ApiPropertyOptional({ example: -12.0464 }) latitud?: number;
|
||||
@ApiPropertyOptional({ example: -77.0428 }) longitud?: number;
|
||||
}
|
||||
|
||||
export class ProvinciaDto {
|
||||
@ApiProperty({ example: '1501' }) codigo: string;
|
||||
@ApiProperty({ example: '15' }) codigoDep: string;
|
||||
@ApiProperty({ example: 'Lima' }) nombre: string;
|
||||
@ApiPropertyOptional() latitud?: number;
|
||||
@ApiPropertyOptional() longitud?: number;
|
||||
@ApiPropertyOptional({ type: () => DepartamentoDto }) departamento?: DepartamentoDto;
|
||||
}
|
||||
|
||||
export class DistritoDto {
|
||||
@ApiProperty({ example: '150101' }) codigo: string;
|
||||
@ApiProperty({ example: '1501' }) codigoProv: string;
|
||||
@ApiProperty({ example: '15' }) codigoDep: string;
|
||||
@ApiProperty({ example: 'Lima' }) nombre: string;
|
||||
@ApiPropertyOptional({ example: 'Lima' }) capital?: string;
|
||||
@ApiPropertyOptional({ example: 'Ciudad' }) categoria?: string;
|
||||
@ApiPropertyOptional({ example: 154 }) altitud?: number;
|
||||
@ApiPropertyOptional({ example: 8445211 }) poblacion?: number;
|
||||
@ApiPropertyOptional() latitud?: number;
|
||||
@ApiPropertyOptional() longitud?: number;
|
||||
@ApiPropertyOptional({ type: () => ProvinciaDto }) provincia?: ProvinciaDto;
|
||||
@ApiPropertyOptional({ type: () => DepartamentoDto }) departamento?: DepartamentoDto;
|
||||
}
|
||||
|
||||
export class UbigeoLookupDto {
|
||||
@ApiProperty({ example: '150101' }) codigo: string;
|
||||
@ApiProperty({ example: 'Lima' }) departamento: string;
|
||||
@ApiProperty({ example: 'Lima' }) provincia: string;
|
||||
@ApiProperty({ example: 'Lima' }) distrito: string;
|
||||
@ApiPropertyOptional() latitud?: number;
|
||||
@ApiPropertyOptional() longitud?: number;
|
||||
}
|
||||
70
src/modules/ubigeo/ubigeo.controller.ts
Normal file
70
src/modules/ubigeo/ubigeo.controller.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
import { Controller, Get, Param, Query } from '@nestjs/common';
|
||||
import { ApiTags, ApiOperation, ApiParam, ApiOkResponse } from '@nestjs/swagger';
|
||||
import { UbigeoService } from './ubigeo.service';
|
||||
import { SearchDto } from './dto/ubigeo.dto';
|
||||
|
||||
@ApiTags('ubigeo')
|
||||
@Controller('ubigeo')
|
||||
export class UbigeoController {
|
||||
constructor(private readonly svc: UbigeoService) {}
|
||||
|
||||
// ─── STATS ─────────────────────────────────────────────────────────────────
|
||||
@Get('stats')
|
||||
@ApiOperation({ summary: 'Estadísticas generales del ubigeo' })
|
||||
getStats() {
|
||||
return this.svc.getStats();
|
||||
}
|
||||
|
||||
// ─── LOOKUP ─────────────────────────────────────────────────────────────────
|
||||
@Get('lookup/:codigo')
|
||||
@ApiOperation({ summary: 'Lookup de cualquier código ubigeo (2, 4 o 6 dígitos)' })
|
||||
@ApiParam({ name: 'codigo', description: 'Código ubigeo: 15 | 1501 | 150101', example: '150101' })
|
||||
lookup(@Param('codigo') codigo: string) {
|
||||
return this.svc.lookup(codigo);
|
||||
}
|
||||
|
||||
// ─── DEPARTAMENTOS ──────────────────────────────────────────────────────────
|
||||
@Get('departamentos')
|
||||
@ApiOperation({ summary: 'Listar todos los departamentos del Perú' })
|
||||
getDepartamentos(@Query() query: SearchDto) {
|
||||
if (query.q) return this.svc.searchDepartamentos(query);
|
||||
return this.svc.getDepartamentos();
|
||||
}
|
||||
|
||||
@Get('departamentos/:codigo')
|
||||
@ApiOperation({ summary: 'Obtener departamento con sus provincias' })
|
||||
@ApiParam({ name: 'codigo', description: 'Código de 2 dígitos', example: '15' })
|
||||
getDepartamento(@Param('codigo') codigo: string) {
|
||||
return this.svc.getDepartamento(codigo);
|
||||
}
|
||||
|
||||
// ─── PROVINCIAS ─────────────────────────────────────────────────────────────
|
||||
@Get('provincias')
|
||||
@ApiOperation({ summary: 'Listar provincias (filtrar por departamento con ?dep=15)' })
|
||||
getProvincias(@Query() query: SearchDto, @Query('dep') dep?: string) {
|
||||
if (query.q) return this.svc.searchProvincias(query);
|
||||
return this.svc.getProvincias(dep);
|
||||
}
|
||||
|
||||
@Get('provincias/:codigo')
|
||||
@ApiOperation({ summary: 'Obtener provincia con sus distritos' })
|
||||
@ApiParam({ name: 'codigo', description: 'Código de 4 dígitos', example: '1501' })
|
||||
getProvincia(@Param('codigo') codigo: string) {
|
||||
return this.svc.getProvincia(codigo);
|
||||
}
|
||||
|
||||
// ─── DISTRITOS ──────────────────────────────────────────────────────────────
|
||||
@Get('distritos')
|
||||
@ApiOperation({ summary: 'Buscar distritos (requiere ?q= o ?prov=)' })
|
||||
getDistritos(@Query() query: SearchDto, @Query('prov') prov?: string) {
|
||||
if (query.q) return this.svc.searchDistritos(query);
|
||||
return this.svc.getDistritos(prov);
|
||||
}
|
||||
|
||||
@Get('distritos/:codigo')
|
||||
@ApiOperation({ summary: 'Obtener distrito por código de 6 dígitos' })
|
||||
@ApiParam({ name: 'codigo', description: 'Código de 6 dígitos', example: '150101' })
|
||||
getDistrito(@Param('codigo') codigo: string) {
|
||||
return this.svc.getDistrito(codigo);
|
||||
}
|
||||
}
|
||||
10
src/modules/ubigeo/ubigeo.module.ts
Normal file
10
src/modules/ubigeo/ubigeo.module.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { UbigeoController } from './ubigeo.controller';
|
||||
import { UbigeoService } from './ubigeo.service';
|
||||
|
||||
@Module({
|
||||
controllers: [UbigeoController],
|
||||
providers: [UbigeoService],
|
||||
exports: [UbigeoService],
|
||||
})
|
||||
export class UbigeoModule {}
|
||||
203
src/modules/ubigeo/ubigeo.service.ts
Normal file
203
src/modules/ubigeo/ubigeo.service.ts
Normal file
@@ -0,0 +1,203 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { SearchDto } from './dto/ubigeo.dto';
|
||||
|
||||
@Injectable()
|
||||
export class UbigeoService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
// ─── DEPARTAMENTOS ────────────────────────────────────────────────────────────
|
||||
|
||||
async getDepartamentos() {
|
||||
return this.prisma.departamento.findMany({
|
||||
orderBy: { nombre: 'asc' },
|
||||
select: { codigo: true, nombre: true, latitud: true, longitud: true },
|
||||
});
|
||||
}
|
||||
|
||||
async getDepartamento(codigo: string) {
|
||||
const dep = await this.prisma.departamento.findUnique({
|
||||
where: { codigo },
|
||||
include: {
|
||||
provincias: {
|
||||
orderBy: { nombre: 'asc' },
|
||||
select: { codigo: true, nombre: true, latitud: true, longitud: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!dep) throw new NotFoundException(`Departamento '${codigo}' no encontrado`);
|
||||
return dep;
|
||||
}
|
||||
|
||||
async searchDepartamentos(dto: SearchDto) {
|
||||
const where = dto.q
|
||||
? { nombre: { contains: dto.q, mode: 'insensitive' as const } }
|
||||
: {};
|
||||
return this.prisma.departamento.findMany({
|
||||
where,
|
||||
orderBy: { nombre: 'asc' },
|
||||
take: dto.limit,
|
||||
skip: (dto.page! - 1) * dto.limit!,
|
||||
});
|
||||
}
|
||||
|
||||
// ─── PROVINCIAS ───────────────────────────────────────────────────────────────
|
||||
|
||||
async getProvincias(codigoDep?: string) {
|
||||
const where = codigoDep ? { codigoDep } : {};
|
||||
return this.prisma.provincia.findMany({
|
||||
where,
|
||||
orderBy: { nombre: 'asc' },
|
||||
include: {
|
||||
departamento: { select: { codigo: true, nombre: true } },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async getProvincia(codigo: string) {
|
||||
const prov = await this.prisma.provincia.findUnique({
|
||||
where: { codigo },
|
||||
include: {
|
||||
departamento: { select: { codigo: true, nombre: true } },
|
||||
distritos: {
|
||||
orderBy: { nombre: 'asc' },
|
||||
select: { codigo: true, nombre: true, capital: true, categoria: true, poblacion: true, latitud: true, longitud: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!prov) throw new NotFoundException(`Provincia '${codigo}' no encontrada`);
|
||||
return prov;
|
||||
}
|
||||
|
||||
async searchProvincias(dto: SearchDto) {
|
||||
const where = dto.q
|
||||
? { nombre: { contains: dto.q, mode: 'insensitive' as const } }
|
||||
: {};
|
||||
return this.prisma.provincia.findMany({
|
||||
where,
|
||||
orderBy: { nombre: 'asc' },
|
||||
take: dto.limit,
|
||||
skip: (dto.page! - 1) * dto.limit!,
|
||||
include: { departamento: { select: { codigo: true, nombre: true } } },
|
||||
});
|
||||
}
|
||||
|
||||
// ─── DISTRITOS ────────────────────────────────────────────────────────────────
|
||||
|
||||
async getDistritos(codigoProv?: string) {
|
||||
const where = codigoProv ? { codigoProv } : {};
|
||||
return this.prisma.distrito.findMany({
|
||||
where,
|
||||
orderBy: { nombre: 'asc' },
|
||||
include: {
|
||||
provincia: { select: { codigo: true, nombre: true } },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async getDistrito(codigo: string) {
|
||||
const dist = await this.prisma.distrito.findUnique({
|
||||
where: { codigo },
|
||||
include: {
|
||||
provincia: {
|
||||
select: { codigo: true, nombre: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!dist) throw new NotFoundException(`Distrito '${codigo}' no encontrado`);
|
||||
|
||||
const dep = await this.prisma.departamento.findUnique({
|
||||
where: { codigo: dist.codigoDep },
|
||||
select: { codigo: true, nombre: true },
|
||||
});
|
||||
|
||||
return { ...dist, departamento: dep };
|
||||
}
|
||||
|
||||
async searchDistritos(dto: SearchDto) {
|
||||
const where = dto.q
|
||||
? { nombre: { contains: dto.q, mode: 'insensitive' as const } }
|
||||
: {};
|
||||
const [data, total] = await Promise.all([
|
||||
this.prisma.distrito.findMany({
|
||||
where,
|
||||
orderBy: { nombre: 'asc' },
|
||||
take: dto.limit,
|
||||
skip: (dto.page! - 1) * dto.limit!,
|
||||
include: {
|
||||
provincia: { select: { codigo: true, nombre: true } },
|
||||
},
|
||||
}),
|
||||
this.prisma.distrito.count({ where }),
|
||||
]);
|
||||
|
||||
// Enriquecer con departamento
|
||||
const depCodigos = [...new Set(data.map((d) => d.codigoDep))];
|
||||
const deps = await this.prisma.departamento.findMany({
|
||||
where: { codigo: { in: depCodigos } },
|
||||
select: { codigo: true, nombre: true },
|
||||
});
|
||||
const depMap = Object.fromEntries(deps.map((d) => [d.codigo, d]));
|
||||
|
||||
return {
|
||||
data: data.map((d) => ({ ...d, departamento: depMap[d.codigoDep] })),
|
||||
meta: { total, page: dto.page, limit: dto.limit, totalPages: Math.ceil(total / dto.limit!) },
|
||||
};
|
||||
}
|
||||
|
||||
// ─── LOOKUP POR CÓDIGO ────────────────────────────────────────────────────────
|
||||
|
||||
async lookup(codigo: string) {
|
||||
const len = codigo.length;
|
||||
|
||||
if (len === 2) {
|
||||
const dep = await this.prisma.departamento.findUnique({ where: { codigo } });
|
||||
if (!dep) throw new NotFoundException(`Código '${codigo}' no encontrado`);
|
||||
return { tipo: 'departamento', codigo, nombre: dep.nombre };
|
||||
}
|
||||
|
||||
if (len === 4) {
|
||||
const prov = await this.prisma.provincia.findUnique({
|
||||
where: { codigo },
|
||||
include: { departamento: { select: { codigo: true, nombre: true } } },
|
||||
});
|
||||
if (!prov) throw new NotFoundException(`Código '${codigo}' no encontrado`);
|
||||
return { tipo: 'provincia', codigo, departamento: prov.departamento.nombre, provincia: prov.nombre };
|
||||
}
|
||||
|
||||
if (len === 6) {
|
||||
const dist = await this.prisma.distrito.findUnique({
|
||||
where: { codigo },
|
||||
include: { provincia: { select: { codigo: true, nombre: true } } },
|
||||
});
|
||||
if (!dist) throw new NotFoundException(`Código '${codigo}' no encontrado`);
|
||||
const dep = await this.prisma.departamento.findUnique({
|
||||
where: { codigo: dist.codigoDep },
|
||||
select: { nombre: true },
|
||||
});
|
||||
return {
|
||||
tipo: 'distrito',
|
||||
codigo,
|
||||
departamento: dep?.nombre,
|
||||
provincia: dist.provincia.nombre,
|
||||
distrito: dist.nombre,
|
||||
capital: dist.capital,
|
||||
latitud: dist.latitud,
|
||||
longitud: dist.longitud,
|
||||
};
|
||||
}
|
||||
|
||||
throw new NotFoundException(`Código '${codigo}' inválido (debe tener 2, 4 o 6 dígitos)`);
|
||||
}
|
||||
|
||||
// ─── STATS ────────────────────────────────────────────────────────────────────
|
||||
|
||||
async getStats() {
|
||||
const [departamentos, provincias, distritos] = await Promise.all([
|
||||
this.prisma.departamento.count(),
|
||||
this.prisma.provincia.count(),
|
||||
this.prisma.distrito.count(),
|
||||
]);
|
||||
return { departamentos, provincias, distritos, fuente: 'INEI 2025' };
|
||||
}
|
||||
}
|
||||
9
src/prisma/prisma.module.ts
Normal file
9
src/prisma/prisma.module.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { PrismaService } from './prisma.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [PrismaService],
|
||||
exports: [PrismaService],
|
||||
})
|
||||
export class PrismaModule {}
|
||||
24
src/prisma/prisma.service.ts
Normal file
24
src/prisma/prisma.service.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { PrismaPg } from '@prisma/adapter-pg';
|
||||
|
||||
@Injectable()
|
||||
export class PrismaService
|
||||
extends PrismaClient
|
||||
implements OnModuleInit, OnModuleDestroy
|
||||
{
|
||||
constructor() {
|
||||
const adapter = new PrismaPg({
|
||||
connectionString: process.env.DATABASE_URL,
|
||||
});
|
||||
super({ adapter });
|
||||
}
|
||||
|
||||
async onModuleInit() {
|
||||
await this.$connect();
|
||||
}
|
||||
|
||||
async onModuleDestroy() {
|
||||
await this.$disconnect();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user