Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,7 @@ DATABASE_URL="postgresql://${DB_USER}:${DB_PASSWORD}@${DB_HOST}:${DB_PORT}/${DB_
SECRET_KEY=

HOST=::0.0.0.0
PORT=4000
PORT=4000

MAPS_API_KEY=
MAPS_API_URL=https://maps.googleapis.com/maps/api
25 changes: 25 additions & 0 deletions src/googleMaps/mapsApi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
export class MapsApi {
static key: string = process.env.MAPS_API_KEY || '';
static url: string = process.env.MAPS_API_URL || 'https://maps.googleapis.com/maps/api';

static async getCoordinates(address: string): Promise<{ lat: number | null ; lng: number | null }> {
try {
const response = await fetch(`${MapsApi.url}/geocode/json?address=${encodeURI(address)}&key=${MapsApi.key}`);
if (!response.ok) {
throw new Error(`[MAPS API] Failed to fetch coordinates. Status: ${response.status}`);
}

const data = await response.json();
const location = data?.results?.[0]?.geometry?.location;
if (!location || !location.lat || !location.lng) {
throw new Error('Invalid response from maps API');
}

return location;
} catch (error: any) {
console.error(`[MAPS API] Error fetching coordinates: ${error.message}`);
return { lat: null, lng: null };
}
}
}

6 changes: 4 additions & 2 deletions src/shelter/shelter.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
import { ApiTags } from '@nestjs/swagger';

import { ShelterService } from './shelter.service';
import { ServerResponse } from '../utils';
import { ServerResponse, fetchShelterCoordinates } from '../utils';
import { StaffGuard } from '@/guards/staff.guard';

@ApiTags('Abrigos')
Expand Down Expand Up @@ -49,13 +49,14 @@ export class ShelterController {
@UseGuards(StaffGuard)
async store(@Body() body) {
try {
await fetchShelterCoordinates(body);
Copy link

@andersoncscz andersoncscz May 13, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❓ Já que esta mutando o body adicionando lat/lng, não seria melhor fazer isso direto no service?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Realmente :D
Vou alterar, obrigado.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A propósito, acabei de ver que este PR esta utilizado o Google Maps para mostrar o local do abrigo com base no endereço

Copy link
Author

@lul-cas lul-cas May 13, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah sim, correto.
Mas se considerarmos o uso das informações como longitude e latitude do abrigo teríamos que usar a api ou semelhante. - Claro, se a implementação de futuras funcionalidades como "Achar abrigo mais próximo" ou calcular "distância" da localização atual do usuário até o abrigo x, y ainda forem relevantes.

Acha interessante prosseguir?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Na minha opnião "achar abrigo mais próximo" por exemplo é bem interessante sim, apesar de talvez não ser um item de alta prioridade no momento? Estou tendo problemas pra acessar meu Discord 😓, talvez seja interessante anunciar por lá pra ver o que outras pessoas acham.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ótimo. Eu gostaria de fazer parte da comunidade, mas não encontrei link para o discord.
Eu poderia ter acesso?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@wOL-Lucas eu peguei aqui nessa issue

const data = await this.shelterService.store(body);
return new ServerResponse(200, 'Successfully created shelter', data);
} catch (err: any) {
this.logger.error(`Failed to create shelter: ${err}`);
throw new HttpException(err?.code ?? err?.name ?? `${err}`, 400);
}
}
}

@Put(':id')
async update(@Param('id') id: string, @Body() body) {
Expand All @@ -72,6 +73,7 @@ export class ShelterController {
@UseGuards(StaffGuard)
async fullUpdate(@Param('id') id: string, @Body() body) {
try {
await fetchShelterCoordinates(body);
const data = await this.shelterService.fullUpdate(id, body);
return new ServerResponse(200, 'Successfully updated shelter', data);
} catch (err: any) {
Expand Down
2 changes: 2 additions & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
getSessionData,
deepMerge,
capitalize,
fetchShelterCoordinates
} from './utils';

export {
Expand All @@ -12,4 +13,5 @@ export {
removeNotNumbers,
getSessionData,
deepMerge,
fetchShelterCoordinates
};
14 changes: 14 additions & 0 deletions src/utils/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { Logger } from '@nestjs/common';
import { Shelter } from '@prisma/client';
import { MapsApi } from '../googleMaps/mapsApi'

class ServerResponse<T> {
readonly message: string;
Expand Down Expand Up @@ -74,11 +76,23 @@ function deepMerge(target: Record<string, any>, source: Record<string, any>) {
return source;
}
}
async function fetchShelterCoordinates(shelter: Shelter) {
try {
const { address } = shelter;
const coordinates = await MapsApi.getCoordinates(address);
shelter.latitude = coordinates.lat;
shelter.longitude = coordinates.lng;
} catch (error) {
console.error(`Failed to fetch coordinates for shelter: ${error}`);
console.log("Failed to fetch coordinates for shelter: ", error);
}
}

export {
ServerResponse,
removeNotNumbers,
getSessionData,
deepMerge,
capitalize,
fetchShelterCoordinates,
};