Skip to content

Commit 1a86f2e

Browse files
authored
Merge pull request #343 from open-mexico/codigos-search
Codigos search
2 parents 34664d8 + 888e8b8 commit 1a86f2e

22 files changed

+1276
-374
lines changed

.env.example

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,8 @@ PORT=3333
77
HOST=localhost
88
LOG_LEVEL=info
99

10-
DB_CONNECTION=sqlite
1110
DB_HOST=127.0.0.1
12-
DB_PORT=5432
11+
DB_PORT=3306
1312
DB_USER=root
1413
DB_PASSWORD=root
1514
DB_DATABASE=app

.github/dependabot.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,4 +29,4 @@ updates:
2929
commit-message:
3030
prefix: fix
3131
prefix-development: chore
32-
include: scope
32+
include: scope

README.md

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,13 @@
2323
<p align="center">
2424
Consulta colonias, municipios, códigos postales y coordenadas.
2525
<br />
26-
<a href="https://pages.github.com/mexpost"><strong>Explora la documentación »</strong></a>
26+
<a href="https://open-mexico.github.io/mexpost/"><strong>Explora la documentación »</strong></a>
2727
<br />
28-
<a href="https://github.com/open-mexico/mexpost">View Demo</a>
28+
<!-- <a href="https://github.com/open-mexico/mexpost">View Demo</a>
29+
· -->
30+
<a href="https://github.com/open-mexico/mexpost/issues/new?template=---1-report-an-issue.md">Report Bug</a>
2931
·
30-
<a href="https://github.com/open-mexico/mexpost/issues">Report Bug</a>
31-
·
32-
<a href="https://github.com/open-mexico/mexpost/issues">Request Feature</a>
32+
<a href="https://github.com/open-mexico/mexpost/issues/new?template=---2-share-an-idea.md">Request Feature</a>
3333
</p>
3434
</p>
3535

@@ -42,6 +42,8 @@
4242
<li>
4343
<a href="#about-the-project">Sobre el Proyecto</a>
4444
<ul>
45+
<li><a href="#descripción">Descripción</a></li>
46+
<li><a href="#funcionalidades-principales">Funcionalidades principales</a></li>
4547
<li><a href="#herramientas-utilizadas">🛠️- Herramientas Utilizadas</a></li>
4648
</ul>
4749
</li>
@@ -82,9 +84,9 @@ Este proyecto de código abierto tiene como objetivo facilitar la búsqueda y co
8284

8385
## **Herramientas Utilizadas**
8486

85-
* [NodeJS](https://nodejs.org/)
86-
* [ExpressJS](https://expressjs.com/)
87+
* [AdonisJS](https://adonisjs.com/)
8788
* [TypeScript](https://www.typescriptlang.org/)
89+
* [NodeJS](https://nodejs.org/)
8890

8991

9092
---
Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,26 @@
11
import type { HttpContext } from '@adonisjs/core/http'
22
import Postal from '#models/postal'
3-
import {
3+
4+
import {
45
codigoPostalValidator,
5-
codigoPostalEstadoValidator
6-
} from '#validators/postal'
6+
codigoPostalEstadoValidator,
7+
coloniaEstadoValidator
8+
} from '#validators/postal_validator'
79

810
import { getEstadoName } from '#utils/estados'
911

1012
export default class PostalsController {
11-
async codigo({ params, response }: HttpContext) {
13+
/**
14+
* Retrieves postal data based on the provided codigo.
15+
* @param {HttpContext} ctx - The HTTP context object.
16+
* @returns {Promise<void>} - A promise that resolves when the response is sent.
17+
*/
18+
async codigo({ params, request, response }: HttpContext) {
1219
const { codigo } = await codigoPostalValidator.validate(params)
1320

14-
const data = await Postal.query().whereLike('codigo', `%${codigo}%`)
21+
const { wc } = request.qs()
22+
const busqueda = wc ? `'%${codigo}%'` : `'${codigo}%'`
23+
const data = await Postal.query().whereRaw(`codigo like ${busqueda}`).preload('estado')
1524

1625
const payload = {
1726
values: data.length,
@@ -21,11 +30,14 @@ export default class PostalsController {
2130
response.json(payload)
2231
}
2332

24-
async codigoEstado({ params, response }: HttpContext) {
33+
async codigoEstado({ request, params, response }: HttpContext) {
2534
const { codigo, estado } = await codigoPostalEstadoValidator.validate(params)
2635

2736
const estadoName = getEstadoName(estado)
28-
const data = await Postal.query().whereLike('codigo', `%${codigo}%`).where('estado_id', estado)
37+
38+
const { wc } = request.qs()
39+
const busqueda = wc ? `'%${codigo}%'` : `'${codigo}%'`
40+
const data = await Postal.query().whereRaw(`codigo like ${busqueda}`).where('estado_id', estado).preload('estado').preload('municipio', q => q.where('estado_id', estado))
2941

3042
const payload = {
3143
values: data.length,
@@ -36,9 +48,15 @@ export default class PostalsController {
3648
response.json(payload)
3749
}
3850

39-
async colonia({ request, response }: HttpContext) {
40-
const postal = await Postal.find(1)
51+
async colonia({ params, request, response }: HttpContext) {
52+
const { colonia, estado } = await coloniaEstadoValidator.validate(params)
53+
54+
const newColonia = decodeURIComponent(colonia)
55+
const page = request.input('page', 1)
56+
const limit = 15
57+
58+
const data = await Postal.query().whereRaw(`nombre like '%${newColonia}%'`).where('estado_id', estado).preload('municipio', q => q.where('estado_id', estado)).paginate(page, limit)
4159

42-
response.json(postal)
60+
response.json(data)
4361
}
4462
}

app/models/estado.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import { DateTime } from 'luxon'
2+
import { BaseModel, column } from '@adonisjs/lucid/orm'
3+
4+
export default class Estado extends BaseModel {
5+
@column({ isPrimary: true })
6+
declare id: number
7+
8+
@column()
9+
declare nombre: string
10+
}

app/models/municipio.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import { DateTime } from 'luxon'
2+
import { BaseModel, column } from '@adonisjs/lucid/orm'
3+
4+
export default class Municipio extends BaseModel {
5+
@column({ isPrimary: true })
6+
declare id: number
7+
8+
@column()
9+
declare nombre: string
10+
}

app/models/postal.ts

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
import { DateTime } from 'luxon'
2-
import { BaseModel, column } from '@adonisjs/lucid/orm'
2+
import Estado from '#models/estado'
3+
import Municipio from '#models/municipio'
4+
import { BaseModel, column, belongsTo } from '@adonisjs/lucid/orm'
5+
import type { BelongsTo } from '@adonisjs/lucid/types/relations'
36

47
export default class Postal extends BaseModel {
58
static table = 'codigos_postales'
@@ -22,6 +25,15 @@ export default class Postal extends BaseModel {
2225
@column()
2326
declare zona: string
2427

25-
@column({ serializeAs: null})
26-
declare estado_id: string
28+
@column({ serializeAs: null })
29+
declare estadoId: number
30+
31+
@column({ serializeAs: null })
32+
declare municipioId: number
33+
34+
@belongsTo(() => Estado)
35+
declare estado: BelongsTo<typeof Estado>
36+
37+
@belongsTo(() => Municipio)
38+
declare municipio: BelongsTo<typeof Municipio>
2739
}

app/validators/postal.ts renamed to app/validators/postal_validator.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,10 @@ export const codigoPostalEstadoValidator = vine.compile(
2020
codigoPostalEstadoValidator.messagesProvider = new SimpleMessagesProvider({
2121
'codigo.regex': 'El código postal debe ser un número entre 3 y 5 dígitos',
2222
})
23+
24+
export const coloniaEstadoValidator = vine.compile(
25+
vine.object({
26+
colonia: vine.string().trim().minLength(3).maxLength(64),
27+
estado: vine.number().positive().withoutDecimals().min(1).max(32),
28+
})
29+
)

config/database.ts

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@ import env from '#start/env'
22
import { defineConfig } from '@adonisjs/lucid'
33

44
const dbConfig = defineConfig({
5-
connection: env.get('DB_CONNECTION', 'sqlite'),
5+
connection: 'mysql',
66
connections: {
7-
postgres: {
8-
client: 'pg',
7+
mysql: {
8+
client: 'mysql2',
99
connection: {
1010
host: env.get('DB_HOST'),
1111
port: env.get('DB_PORT'),
@@ -17,13 +17,7 @@ const dbConfig = defineConfig({
1717
naturalSort: true,
1818
paths: ['database/migrations'],
1919
},
20-
},
21-
sqlite: {
22-
client: 'better-sqlite3',
23-
connection: {
24-
filename: env.get('DB_FILE', 'tmp/db.sqlite'),
25-
},
26-
} // squlite
20+
}
2721
},
2822
})
2923

database/migrations/1740407050839_create_postals_table.ts renamed to database/migrations/1740449596699_create_estados_table.ts

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,15 @@
11
import { BaseSchema } from '@adonisjs/lucid/schema'
22

33
export default class extends BaseSchema {
4-
protected tableName = 'codigos_postales'
4+
protected tableName = 'estados'
55

66
async up() {
77
this.schema.createTable(this.tableName, (table) => {
8-
table.increments('id')
8+
table.charset('utf8mb4')
9+
table.collate('utf8mb4_unicode_ci')
910

10-
table.string('postal_code', 10).notNullable().unique()
11-
12-
table.timestamp('created_at')
13-
table.timestamp('updated_at')
11+
table.increments('id').unique().primary()
12+
table.string('nombre').notNullable().index()
1413
})
1514
}
1615

0 commit comments

Comments
 (0)