feat: initial API Ubigeo Peru - INEI 2025 + países del mundo
This commit is contained in:
BIN
.github/.DS_Store
vendored
Normal file
BIN
.github/.DS_Store
vendored
Normal file
Binary file not shown.
45
.github/workflows/deploy.yml
vendored
Normal file
45
.github/workflows/deploy.yml
vendored
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
name: Deploy API Ubigeo
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
deploy:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Deploy al VPS via SSH
|
||||||
|
uses: appleboy/ssh-action@v1.0.3
|
||||||
|
with:
|
||||||
|
host: 158.220.106.131
|
||||||
|
username: root
|
||||||
|
password: ${{ secrets.VPS_PASSWORD }}
|
||||||
|
script: |
|
||||||
|
set -e
|
||||||
|
cd /home/deployer/api-ubigeo || (mkdir -p /home/deployer/api-ubigeo && cd /home/deployer/api-ubigeo)
|
||||||
|
|
||||||
|
# Pull o clone
|
||||||
|
if [ -d ".git" ]; then
|
||||||
|
git pull origin main
|
||||||
|
else
|
||||||
|
git clone https://github.com/${{ github.repository }} .
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Build imagen
|
||||||
|
docker build -t ubigeo-api:latest .
|
||||||
|
|
||||||
|
# Deploy con compose
|
||||||
|
docker compose -f docker-compose.production.yml up -d --force-recreate api
|
||||||
|
|
||||||
|
# Ejecutar migraciones
|
||||||
|
docker exec ubigeo-api npx prisma migrate deploy
|
||||||
|
|
||||||
|
# Verificar health
|
||||||
|
sleep 10
|
||||||
|
curl -f http://localhost:3200/api/v1/health || exit 1
|
||||||
|
|
||||||
|
echo "✅ Deploy exitoso"
|
||||||
8
.gitignore
vendored
Normal file
8
.gitignore
vendored
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
node_modules/
|
||||||
|
dist/
|
||||||
|
.env
|
||||||
|
.env.production
|
||||||
|
.env.local
|
||||||
|
*.log
|
||||||
|
/generated/
|
||||||
|
prisma/seed/*.js
|
||||||
4
.prettierrc
Normal file
4
.prettierrc
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"singleQuote": true,
|
||||||
|
"trailingComma": "all"
|
||||||
|
}
|
||||||
28
Dockerfile
Normal file
28
Dockerfile
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
FROM node:20-alpine AS builder
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY package*.json ./
|
||||||
|
COPY prisma ./prisma/
|
||||||
|
RUN npm ci
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# ─── PRODUCTION ───────────────────────────────────────────────────────────────
|
||||||
|
FROM node:20-alpine AS production
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY package*.json ./
|
||||||
|
COPY prisma ./prisma/
|
||||||
|
RUN npm ci --omit=dev && npm cache clean --force
|
||||||
|
|
||||||
|
COPY --from=builder /app/dist ./dist
|
||||||
|
|
||||||
|
RUN addgroup -g 1001 -S nodejs && adduser -S nestjs -u 1001
|
||||||
|
USER nestjs
|
||||||
|
|
||||||
|
EXPOSE 3200
|
||||||
|
|
||||||
|
CMD ["sh", "-c", "npx prisma migrate deploy && node dist/src/main.js"]
|
||||||
98
README.md
Normal file
98
README.md
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
<p align="center">
|
||||||
|
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
|
||||||
|
[circleci-url]: https://circleci.com/gh/nestjs/nest
|
||||||
|
|
||||||
|
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
|
||||||
|
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
|
||||||
|
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
|
||||||
|
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
|
||||||
|
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
|
||||||
|
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
|
||||||
|
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
|
||||||
|
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
|
||||||
|
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
|
||||||
|
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
|
||||||
|
</p>
|
||||||
|
<!--[](https://opencollective.com/nest#backer)
|
||||||
|
[](https://opencollective.com/nest#sponsor)-->
|
||||||
|
|
||||||
|
## Description
|
||||||
|
|
||||||
|
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
|
||||||
|
|
||||||
|
## Project setup
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ npm install
|
||||||
|
```
|
||||||
|
|
||||||
|
## Compile and run the project
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# development
|
||||||
|
$ npm run start
|
||||||
|
|
||||||
|
# watch mode
|
||||||
|
$ npm run start:dev
|
||||||
|
|
||||||
|
# production mode
|
||||||
|
$ npm run start:prod
|
||||||
|
```
|
||||||
|
|
||||||
|
## Run tests
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# unit tests
|
||||||
|
$ npm run test
|
||||||
|
|
||||||
|
# e2e tests
|
||||||
|
$ npm run test:e2e
|
||||||
|
|
||||||
|
# test coverage
|
||||||
|
$ npm run test:cov
|
||||||
|
```
|
||||||
|
|
||||||
|
## Deployment
|
||||||
|
|
||||||
|
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
|
||||||
|
|
||||||
|
If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ npm install -g @nestjs/mau
|
||||||
|
$ mau deploy
|
||||||
|
```
|
||||||
|
|
||||||
|
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
|
||||||
|
|
||||||
|
## Resources
|
||||||
|
|
||||||
|
Check out a few resources that may come in handy when working with NestJS:
|
||||||
|
|
||||||
|
- Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
|
||||||
|
- For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
|
||||||
|
- To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
|
||||||
|
- Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
|
||||||
|
- Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
|
||||||
|
- Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
|
||||||
|
- To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
|
||||||
|
- Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
|
||||||
|
|
||||||
|
## Support
|
||||||
|
|
||||||
|
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
|
||||||
|
|
||||||
|
## Stay in touch
|
||||||
|
|
||||||
|
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
|
||||||
|
- Website - [https://nestjs.com](https://nestjs.com/)
|
||||||
|
- Twitter - [@nestframework](https://twitter.com/nestframework)
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).
|
||||||
51
docker-compose.production.yml
Normal file
51
docker-compose.production.yml
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:16-alpine
|
||||||
|
container_name: ubigeo-postgres
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
POSTGRES_USER: ubigeo_user
|
||||||
|
POSTGRES_PASSWORD: UbigeoDB2026
|
||||||
|
POSTGRES_DB: ubigeo_db
|
||||||
|
volumes:
|
||||||
|
- postgres_data:/var/lib/postgresql/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U ubigeo_user -d ubigeo_db"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
networks:
|
||||||
|
- ubigeo_network
|
||||||
|
- easypanel
|
||||||
|
|
||||||
|
api:
|
||||||
|
image: ubigeo-api:latest
|
||||||
|
container_name: ubigeo-api
|
||||||
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:3200:3200"
|
||||||
|
environment:
|
||||||
|
DATABASE_URL: "postgresql://ubigeo_user:UbigeoDB2026@postgres:5432/ubigeo_db"
|
||||||
|
PORT: 3200
|
||||||
|
NODE_ENV: production
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
labels:
|
||||||
|
- "traefik.enable=true"
|
||||||
|
- "traefik.http.routers.ubigeo.rule=Host(`api-ubigeo.darkcodex.dev`)"
|
||||||
|
- "traefik.http.routers.ubigeo.entrypoints=websecure"
|
||||||
|
- "traefik.http.routers.ubigeo.tls=true"
|
||||||
|
- "traefik.http.services.ubigeo.loadbalancer.server.port=3200"
|
||||||
|
networks:
|
||||||
|
- ubigeo_network
|
||||||
|
- easypanel
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
postgres_data:
|
||||||
|
|
||||||
|
networks:
|
||||||
|
ubigeo_network:
|
||||||
|
driver: bridge
|
||||||
|
easypanel:
|
||||||
|
external: true
|
||||||
35
docker-compose.yml
Normal file
35
docker-compose.yml
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:16-alpine
|
||||||
|
container_name: ubigeo-postgres
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
POSTGRES_USER: ubigeo_user
|
||||||
|
POSTGRES_PASSWORD: UbigeoDB2026
|
||||||
|
POSTGRES_DB: ubigeo_db
|
||||||
|
ports:
|
||||||
|
- "5433:5432"
|
||||||
|
volumes:
|
||||||
|
- postgres_data:/var/lib/postgresql/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U ubigeo_user -d ubigeo_db"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
|
||||||
|
api:
|
||||||
|
build: .
|
||||||
|
container_name: ubigeo-api
|
||||||
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
- "3200:3200"
|
||||||
|
environment:
|
||||||
|
DATABASE_URL: "postgresql://ubigeo_user:UbigeoDB2026@postgres:5432/ubigeo_db"
|
||||||
|
PORT: 3200
|
||||||
|
NODE_ENV: production
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
postgres_data:
|
||||||
35
eslint.config.mjs
Normal file
35
eslint.config.mjs
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
// @ts-check
|
||||||
|
import eslint from '@eslint/js';
|
||||||
|
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';
|
||||||
|
import globals from 'globals';
|
||||||
|
import tseslint from 'typescript-eslint';
|
||||||
|
|
||||||
|
export default tseslint.config(
|
||||||
|
{
|
||||||
|
ignores: ['eslint.config.mjs'],
|
||||||
|
},
|
||||||
|
eslint.configs.recommended,
|
||||||
|
...tseslint.configs.recommendedTypeChecked,
|
||||||
|
eslintPluginPrettierRecommended,
|
||||||
|
{
|
||||||
|
languageOptions: {
|
||||||
|
globals: {
|
||||||
|
...globals.node,
|
||||||
|
...globals.jest,
|
||||||
|
},
|
||||||
|
sourceType: 'commonjs',
|
||||||
|
parserOptions: {
|
||||||
|
projectService: true,
|
||||||
|
tsconfigRootDir: import.meta.dirname,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
rules: {
|
||||||
|
'@typescript-eslint/no-explicit-any': 'off',
|
||||||
|
'@typescript-eslint/no-floating-promises': 'warn',
|
||||||
|
'@typescript-eslint/no-unsafe-argument': 'warn',
|
||||||
|
"prettier/prettier": ["error", { endOfLine: "auto" }],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
8
nest-cli.json
Normal file
8
nest-cli.json
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://json.schemastore.org/nest-cli",
|
||||||
|
"collection": "@nestjs/schematics",
|
||||||
|
"sourceRoot": "src",
|
||||||
|
"compilerOptions": {
|
||||||
|
"deleteOutDir": true
|
||||||
|
}
|
||||||
|
}
|
||||||
11282
package-lock.json
generated
Normal file
11282
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
87
package.json
Normal file
87
package.json
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
{
|
||||||
|
"name": "api-ubigeo",
|
||||||
|
"version": "0.0.1",
|
||||||
|
"description": "",
|
||||||
|
"author": "",
|
||||||
|
"private": true,
|
||||||
|
"license": "UNLICENSED",
|
||||||
|
"scripts": {
|
||||||
|
"build": "nest build",
|
||||||
|
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||||
|
"start": "nest start",
|
||||||
|
"start:dev": "nest start --watch",
|
||||||
|
"start:debug": "nest start --debug --watch",
|
||||||
|
"start:prod": "node dist/src/main",
|
||||||
|
"seed": "ts-node prisma/seed/seed.ts",
|
||||||
|
"prisma:migrate": "prisma migrate dev",
|
||||||
|
"prisma:deploy": "prisma migrate deploy",
|
||||||
|
"prisma:generate": "prisma generate",
|
||||||
|
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||||
|
"test": "jest",
|
||||||
|
"test:watch": "jest --watch",
|
||||||
|
"test:cov": "jest --coverage",
|
||||||
|
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
||||||
|
"test:e2e": "jest --config ./test/jest-e2e.json"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@nestjs/common": "^11.0.1",
|
||||||
|
"@nestjs/config": "^4.0.3",
|
||||||
|
"@nestjs/core": "^11.0.1",
|
||||||
|
"@nestjs/platform-express": "^11.0.1",
|
||||||
|
"@nestjs/swagger": "^11.2.6",
|
||||||
|
"@nestjs/throttler": "^6.5.0",
|
||||||
|
"@prisma/adapter-pg": "^7.4.2",
|
||||||
|
"@prisma/client": "^7.4.2",
|
||||||
|
"class-transformer": "^0.5.1",
|
||||||
|
"class-validator": "^0.14.4",
|
||||||
|
"helmet": "^8.1.0",
|
||||||
|
"pg": "^8.20.0",
|
||||||
|
"prisma": "^7.4.2",
|
||||||
|
"reflect-metadata": "^0.2.2",
|
||||||
|
"rxjs": "^7.8.1",
|
||||||
|
"swagger-ui-express": "^5.0.1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@eslint/eslintrc": "^3.2.0",
|
||||||
|
"@eslint/js": "^9.18.0",
|
||||||
|
"@nestjs/cli": "^11.0.0",
|
||||||
|
"@nestjs/schematics": "^11.0.0",
|
||||||
|
"@nestjs/testing": "^11.0.1",
|
||||||
|
"@types/express": "^5.0.0",
|
||||||
|
"@types/jest": "^30.0.0",
|
||||||
|
"@types/node": "^22.10.7",
|
||||||
|
"@types/supertest": "^6.0.2",
|
||||||
|
"dotenv": "^17.3.1",
|
||||||
|
"eslint": "^9.18.0",
|
||||||
|
"eslint-config-prettier": "^10.0.1",
|
||||||
|
"eslint-plugin-prettier": "^5.2.2",
|
||||||
|
"globals": "^16.0.0",
|
||||||
|
"jest": "^30.0.0",
|
||||||
|
"prettier": "^3.4.2",
|
||||||
|
"source-map-support": "^0.5.21",
|
||||||
|
"supertest": "^7.0.0",
|
||||||
|
"ts-jest": "^29.2.5",
|
||||||
|
"ts-loader": "^9.5.2",
|
||||||
|
"ts-node": "^10.9.2",
|
||||||
|
"tsconfig-paths": "^4.2.0",
|
||||||
|
"typescript": "^5.7.3",
|
||||||
|
"typescript-eslint": "^8.20.0"
|
||||||
|
},
|
||||||
|
"jest": {
|
||||||
|
"moduleFileExtensions": [
|
||||||
|
"js",
|
||||||
|
"json",
|
||||||
|
"ts"
|
||||||
|
],
|
||||||
|
"rootDir": "src",
|
||||||
|
"testRegex": ".*\\.spec\\.ts$",
|
||||||
|
"transform": {
|
||||||
|
"^.+\\.(t|j)s$": "ts-jest"
|
||||||
|
},
|
||||||
|
"collectCoverageFrom": [
|
||||||
|
"**/*.(t|j)s"
|
||||||
|
],
|
||||||
|
"coverageDirectory": "../coverage",
|
||||||
|
"testEnvironment": "node"
|
||||||
|
}
|
||||||
|
}
|
||||||
14
prisma.config.ts
Normal file
14
prisma.config.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
// This file was generated by Prisma, and assumes you have installed the following:
|
||||||
|
// npm install --save-dev prisma dotenv
|
||||||
|
import "dotenv/config";
|
||||||
|
import { defineConfig } from "prisma/config";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
schema: "prisma/schema.prisma",
|
||||||
|
migrations: {
|
||||||
|
path: "prisma/migrations",
|
||||||
|
},
|
||||||
|
datasource: {
|
||||||
|
url: process.env["DATABASE_URL"],
|
||||||
|
},
|
||||||
|
});
|
||||||
BIN
prisma/.DS_Store
vendored
Normal file
BIN
prisma/.DS_Store
vendored
Normal file
Binary file not shown.
121
prisma/migrations/20260310035352_init/migration.sql
Normal file
121
prisma/migrations/20260310035352_init/migration.sql
Normal file
@@ -0,0 +1,121 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "paises" (
|
||||||
|
"id" SERIAL NOT NULL,
|
||||||
|
"codigo" VARCHAR(3) NOT NULL,
|
||||||
|
"codigo_alpha2" VARCHAR(2) NOT NULL,
|
||||||
|
"nombre" VARCHAR(100) NOT NULL,
|
||||||
|
"nombre_en" VARCHAR(100) NOT NULL,
|
||||||
|
"capital" VARCHAR(100) NOT NULL,
|
||||||
|
"region" VARCHAR(50) NOT NULL,
|
||||||
|
"subregion" VARCHAR(50) NOT NULL,
|
||||||
|
"emoji" VARCHAR(10) NOT NULL,
|
||||||
|
"latitud" DECIMAL(10,8),
|
||||||
|
"longitud" DECIMAL(11,8),
|
||||||
|
"activo" BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "paises_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "departamentos" (
|
||||||
|
"id" SERIAL NOT NULL,
|
||||||
|
"codigo" VARCHAR(2) NOT NULL,
|
||||||
|
"nombre" VARCHAR(100) NOT NULL,
|
||||||
|
"latitud" DECIMAL(10,8),
|
||||||
|
"longitud" DECIMAL(11,8),
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "departamentos_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "provincias" (
|
||||||
|
"id" SERIAL NOT NULL,
|
||||||
|
"codigo" VARCHAR(4) NOT NULL,
|
||||||
|
"codigo_dep" VARCHAR(2) NOT NULL,
|
||||||
|
"nombre" VARCHAR(100) NOT NULL,
|
||||||
|
"latitud" DECIMAL(10,8),
|
||||||
|
"longitud" DECIMAL(11,8),
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "provincias_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "distritos" (
|
||||||
|
"id" SERIAL NOT NULL,
|
||||||
|
"codigo" VARCHAR(6) NOT NULL,
|
||||||
|
"codigo_prov" VARCHAR(4) NOT NULL,
|
||||||
|
"codigo_dep" VARCHAR(2) NOT NULL,
|
||||||
|
"nombre" VARCHAR(100) NOT NULL,
|
||||||
|
"capital" VARCHAR(100),
|
||||||
|
"categoria" VARCHAR(30),
|
||||||
|
"altitud" DECIMAL(10,2),
|
||||||
|
"poblacion" INTEGER,
|
||||||
|
"latitud" DECIMAL(10,8),
|
||||||
|
"longitud" DECIMAL(11,8),
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "distritos_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "paises_codigo_key" ON "paises"("codigo");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "paises_codigo_alpha2_key" ON "paises"("codigo_alpha2");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "paises_codigo_idx" ON "paises"("codigo");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "paises_codigo_alpha2_idx" ON "paises"("codigo_alpha2");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "paises_nombre_idx" ON "paises"("nombre");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "paises_region_idx" ON "paises"("region");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "departamentos_codigo_key" ON "departamentos"("codigo");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "departamentos_codigo_idx" ON "departamentos"("codigo");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "departamentos_nombre_idx" ON "departamentos"("nombre");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "provincias_codigo_key" ON "provincias"("codigo");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "provincias_codigo_idx" ON "provincias"("codigo");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "provincias_codigo_dep_idx" ON "provincias"("codigo_dep");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "provincias_nombre_idx" ON "provincias"("nombre");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "distritos_codigo_key" ON "distritos"("codigo");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "distritos_codigo_idx" ON "distritos"("codigo");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "distritos_codigo_prov_idx" ON "distritos"("codigo_prov");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "distritos_codigo_dep_idx" ON "distritos"("codigo_dep");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "distritos_nombre_idx" ON "distritos"("nombre");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "provincias" ADD CONSTRAINT "provincias_codigo_dep_fkey" FOREIGN KEY ("codigo_dep") REFERENCES "departamentos"("codigo") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "distritos" ADD CONSTRAINT "distritos_codigo_prov_fkey" FOREIGN KEY ("codigo_prov") REFERENCES "provincias"("codigo") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
3
prisma/migrations/migration_lock.toml
Normal file
3
prisma/migrations/migration_lock.toml
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Please do not edit this file manually
|
||||||
|
# It should be added in your version-control system (e.g., Git)
|
||||||
|
provider = "postgresql"
|
||||||
85
prisma/schema.prisma
Normal file
85
prisma/schema.prisma
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
generator client {
|
||||||
|
provider = "prisma-client-js"
|
||||||
|
}
|
||||||
|
|
||||||
|
datasource db {
|
||||||
|
provider = "postgresql"
|
||||||
|
}
|
||||||
|
|
||||||
|
model Pais {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
codigo String @unique @db.VarChar(3)
|
||||||
|
codigoAlpha2 String @unique @map("codigo_alpha2") @db.VarChar(2)
|
||||||
|
nombre String @db.VarChar(100)
|
||||||
|
nombreEn String @map("nombre_en") @db.VarChar(100)
|
||||||
|
capital String @db.VarChar(100)
|
||||||
|
region String @db.VarChar(50)
|
||||||
|
subregion String @db.VarChar(50)
|
||||||
|
emoji String @db.VarChar(10)
|
||||||
|
latitud Decimal? @db.Decimal(10, 8)
|
||||||
|
longitud Decimal? @db.Decimal(11, 8)
|
||||||
|
activo Boolean @default(true)
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
|
@@index([codigo])
|
||||||
|
@@index([codigoAlpha2])
|
||||||
|
@@index([nombre])
|
||||||
|
@@index([region])
|
||||||
|
@@map("paises")
|
||||||
|
}
|
||||||
|
|
||||||
|
model Departamento {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
codigo String @unique @db.VarChar(2)
|
||||||
|
nombre String @db.VarChar(100)
|
||||||
|
latitud Decimal? @db.Decimal(10, 8)
|
||||||
|
longitud Decimal? @db.Decimal(11, 8)
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
|
provincias Provincia[]
|
||||||
|
|
||||||
|
@@index([codigo])
|
||||||
|
@@index([nombre])
|
||||||
|
@@map("departamentos")
|
||||||
|
}
|
||||||
|
|
||||||
|
model Provincia {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
codigo String @unique @db.VarChar(4)
|
||||||
|
codigoDep String @map("codigo_dep") @db.VarChar(2)
|
||||||
|
nombre String @db.VarChar(100)
|
||||||
|
latitud Decimal? @db.Decimal(10, 8)
|
||||||
|
longitud Decimal? @db.Decimal(11, 8)
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
|
departamento Departamento @relation(fields: [codigoDep], references: [codigo])
|
||||||
|
distritos Distrito[]
|
||||||
|
|
||||||
|
@@index([codigo])
|
||||||
|
@@index([codigoDep])
|
||||||
|
@@index([nombre])
|
||||||
|
@@map("provincias")
|
||||||
|
}
|
||||||
|
|
||||||
|
model Distrito {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
codigo String @unique @db.VarChar(6)
|
||||||
|
codigoProv String @map("codigo_prov") @db.VarChar(4)
|
||||||
|
codigoDep String @map("codigo_dep") @db.VarChar(2)
|
||||||
|
nombre String @db.VarChar(100)
|
||||||
|
capital String? @db.VarChar(100)
|
||||||
|
categoria String? @db.VarChar(30)
|
||||||
|
altitud Decimal? @db.Decimal(10, 2)
|
||||||
|
poblacion Int?
|
||||||
|
latitud Decimal? @db.Decimal(10, 8)
|
||||||
|
longitud Decimal? @db.Decimal(11, 8)
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
|
provincia Provincia @relation(fields: [codigoProv], references: [codigo])
|
||||||
|
|
||||||
|
@@index([codigo])
|
||||||
|
@@index([codigoProv])
|
||||||
|
@@index([codigoDep])
|
||||||
|
@@index([nombre])
|
||||||
|
@@map("distritos")
|
||||||
|
}
|
||||||
164
prisma/seed/seed.ts
Normal file
164
prisma/seed/seed.ts
Normal file
@@ -0,0 +1,164 @@
|
|||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
import { PrismaPg } from '@prisma/adapter-pg';
|
||||||
|
import * as https from 'https';
|
||||||
|
import * as http from 'http';
|
||||||
|
|
||||||
|
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL });
|
||||||
|
const prisma = new PrismaClient({ adapter });
|
||||||
|
|
||||||
|
// ─── HELPERS ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function fetch(url: string): Promise<string> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const client = url.startsWith('https') ? https : http;
|
||||||
|
let data = '';
|
||||||
|
client.get(url, (res) => {
|
||||||
|
if (res.statusCode === 301 || res.statusCode === 302) {
|
||||||
|
return fetch(res.headers.location!).then(resolve).catch(reject);
|
||||||
|
}
|
||||||
|
res.on('data', (chunk) => (data += chunk));
|
||||||
|
res.on('end', () => resolve(data));
|
||||||
|
}).on('error', reject);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── SEED UBIGEO INEI 2025 ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async function seedUbigeo() {
|
||||||
|
console.log('📍 Descargando ubigeos INEI 2025...');
|
||||||
|
const csv = await fetch('https://raw.githubusercontent.com/MichaelSuarez0/ubigeos_peru/main/databases/ubigeo_inei_2025.csv');
|
||||||
|
|
||||||
|
const lines = csv.trim().split('\n').slice(1); // skip header
|
||||||
|
console.log(` ${lines.length} registros encontrados`);
|
||||||
|
|
||||||
|
const depMap = new Map<string, { nombre: string; lat?: number; lon?: number }>();
|
||||||
|
const provMap = new Map<string, { nombre: string; depCod: string; lat?: number; lon?: number }>();
|
||||||
|
const distritos: any[] = [];
|
||||||
|
|
||||||
|
for (const line of lines) {
|
||||||
|
const parts = line.split(';');
|
||||||
|
if (parts.length < 10) continue;
|
||||||
|
|
||||||
|
const [depNombre, provNombre, distNombre, ubigeo, capital, categoria, altitud, poblacion, lat, lon] = parts;
|
||||||
|
|
||||||
|
if (!ubigeo || ubigeo.length !== 6) continue;
|
||||||
|
|
||||||
|
const codDep = ubigeo.substring(0, 2);
|
||||||
|
const codProv = ubigeo.substring(0, 4);
|
||||||
|
const latNum = parseFloat(lat) || undefined;
|
||||||
|
const lonNum = parseFloat(lon) || undefined;
|
||||||
|
|
||||||
|
if (!depMap.has(codDep)) {
|
||||||
|
depMap.set(codDep, { nombre: depNombre.trim(), lat: latNum, lon: lonNum });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!provMap.has(codProv)) {
|
||||||
|
provMap.set(codProv, { nombre: provNombre.trim(), depCod: codDep, lat: latNum, lon: lonNum });
|
||||||
|
}
|
||||||
|
|
||||||
|
distritos.push({
|
||||||
|
codigo: ubigeo.trim(),
|
||||||
|
codigoProv: codProv,
|
||||||
|
codigoDep: codDep,
|
||||||
|
nombre: distNombre.trim(),
|
||||||
|
capital: capital?.trim() || null,
|
||||||
|
categoria: categoria?.trim() || null,
|
||||||
|
altitud: parseFloat(altitud) || null,
|
||||||
|
poblacion: parseInt(poblacion) || null,
|
||||||
|
latitud: latNum,
|
||||||
|
longitud: lonNum,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(` Departamentos: ${depMap.size} | Provincias: ${provMap.size} | Distritos: ${distritos.length}`);
|
||||||
|
|
||||||
|
// Insertar departamentos
|
||||||
|
console.log(' Insertando departamentos...');
|
||||||
|
await prisma.departamento.deleteMany();
|
||||||
|
for (const [codigo, { nombre, lat, lon }] of depMap) {
|
||||||
|
await prisma.departamento.create({
|
||||||
|
data: { codigo, nombre, latitud: lat, longitud: lon },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Insertar provincias
|
||||||
|
console.log(' Insertando provincias...');
|
||||||
|
await prisma.provincia.deleteMany();
|
||||||
|
for (const [codigo, { nombre, depCod, lat, lon }] of provMap) {
|
||||||
|
await prisma.provincia.create({
|
||||||
|
data: { codigo, codigoDep: depCod, nombre, latitud: lat, longitud: lon },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Insertar distritos en batches
|
||||||
|
console.log(' Insertando distritos...');
|
||||||
|
await prisma.distrito.deleteMany();
|
||||||
|
const batchSize = 100;
|
||||||
|
for (let i = 0; i < distritos.length; i += batchSize) {
|
||||||
|
const batch = distritos.slice(i, i + batchSize);
|
||||||
|
await prisma.distrito.createMany({ data: batch, skipDuplicates: true });
|
||||||
|
process.stdout.write(`\r Progreso: ${Math.min(i + batchSize, distritos.length)}/${distritos.length}`);
|
||||||
|
}
|
||||||
|
console.log('\n ✅ Ubigeos insertados');
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── SEED PAÍSES ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async function seedPaises() {
|
||||||
|
console.log('\n🌍 Descargando países del mundo...');
|
||||||
|
const raw = await fetch('https://restcountries.com/v3.1/all?fields=name,cca2,cca3,capital,region,subregion,latlng,flag');
|
||||||
|
const countries = JSON.parse(raw);
|
||||||
|
|
||||||
|
console.log(` ${countries.length} países encontrados`);
|
||||||
|
|
||||||
|
await prisma.pais.deleteMany();
|
||||||
|
|
||||||
|
const data = countries
|
||||||
|
.filter((c: any) => c.cca3 && c.cca2)
|
||||||
|
.map((c: any) => ({
|
||||||
|
codigo: c.cca3,
|
||||||
|
codigoAlpha2: c.cca2,
|
||||||
|
nombre: c.name?.translations?.spa?.official || c.name?.translations?.spa?.common || c.name?.common || '',
|
||||||
|
nombreEn: c.name?.common || '',
|
||||||
|
capital: Array.isArray(c.capital) ? c.capital[0] || '' : '',
|
||||||
|
region: c.region || '',
|
||||||
|
subregion: c.subregion || '',
|
||||||
|
emoji: c.flag || '',
|
||||||
|
latitud: c.latlng?.[0] || null,
|
||||||
|
longitud: c.latlng?.[1] || null,
|
||||||
|
}))
|
||||||
|
.filter((c: any) => c.nombre);
|
||||||
|
|
||||||
|
await prisma.pais.createMany({ data, skipDuplicates: true });
|
||||||
|
console.log(` ✅ ${data.length} países insertados`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── MAIN ─────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
console.log('🚀 Iniciando seed...\n');
|
||||||
|
try {
|
||||||
|
await seedUbigeo();
|
||||||
|
await seedPaises();
|
||||||
|
|
||||||
|
const stats = {
|
||||||
|
departamentos: await prisma.departamento.count(),
|
||||||
|
provincias: await prisma.provincia.count(),
|
||||||
|
distritos: await prisma.distrito.count(),
|
||||||
|
paises: await prisma.pais.count(),
|
||||||
|
};
|
||||||
|
|
||||||
|
console.log('\n✅ Seed completado:');
|
||||||
|
console.log(` Departamentos: ${stats.departamentos}`);
|
||||||
|
console.log(` Provincias: ${stats.provincias}`);
|
||||||
|
console.log(` Distritos: ${stats.distritos}`);
|
||||||
|
console.log(` Países: ${stats.paises}`);
|
||||||
|
} catch (e) {
|
||||||
|
console.error('❌ Error en seed:', e);
|
||||||
|
process.exit(1);
|
||||||
|
} finally {
|
||||||
|
await prisma.$disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
main();
|
||||||
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
25
test/app.e2e-spec.ts
Normal file
25
test/app.e2e-spec.ts
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { INestApplication } from '@nestjs/common';
|
||||||
|
import request from 'supertest';
|
||||||
|
import { App } from 'supertest/types';
|
||||||
|
import { AppModule } from './../src/app.module';
|
||||||
|
|
||||||
|
describe('AppController (e2e)', () => {
|
||||||
|
let app: INestApplication<App>;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const moduleFixture: TestingModule = await Test.createTestingModule({
|
||||||
|
imports: [AppModule],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
app = moduleFixture.createNestApplication();
|
||||||
|
await app.init();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('/ (GET)', () => {
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.get('/')
|
||||||
|
.expect(200)
|
||||||
|
.expect('Hello World!');
|
||||||
|
});
|
||||||
|
});
|
||||||
9
test/jest-e2e.json
Normal file
9
test/jest-e2e.json
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"moduleFileExtensions": ["js", "json", "ts"],
|
||||||
|
"rootDir": ".",
|
||||||
|
"testEnvironment": "node",
|
||||||
|
"testRegex": ".e2e-spec.ts$",
|
||||||
|
"transform": {
|
||||||
|
"^.+\\.(t|j)s$": "ts-jest"
|
||||||
|
}
|
||||||
|
}
|
||||||
4
tsconfig.build.json
Normal file
4
tsconfig.build.json
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"extends": "./tsconfig.json",
|
||||||
|
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
|
||||||
|
}
|
||||||
25
tsconfig.json
Normal file
25
tsconfig.json
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"module": "nodenext",
|
||||||
|
"moduleResolution": "nodenext",
|
||||||
|
"resolvePackageJsonExports": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"declaration": true,
|
||||||
|
"removeComments": true,
|
||||||
|
"emitDecoratorMetadata": true,
|
||||||
|
"experimentalDecorators": true,
|
||||||
|
"allowSyntheticDefaultImports": true,
|
||||||
|
"target": "ES2023",
|
||||||
|
"sourceMap": true,
|
||||||
|
"outDir": "./dist",
|
||||||
|
"baseUrl": "./",
|
||||||
|
"incremental": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"strictNullChecks": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"noImplicitAny": false,
|
||||||
|
"strictBindCallApply": false,
|
||||||
|
"noFallthroughCasesInSwitch": false
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user