New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

autocompleter-caba

Package Overview
Dependencies
Maintainers
0
Versions
9
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

autocompleter-caba - npm Package Compare versions

Comparing version 0.1.5 to 0.1.6

13

dist/src/api/urls.d.ts

@@ -1,5 +0,8 @@

export declare const address_suggestions_url = "https://api-serviciosgeo-dev.gcba.gob.ar//calles/nombre";
export declare const address_search_url = "https://api-serviciosgeo-dev.gcba.gob.ar//direcciones/geocoder";
export declare const transform_coordinates_url = "https://api-serviciosgeo-dev.gcba.gob.ar//coordenadas/transformar";
export declare const place_suggestions_url = "https://api-serviciosgeo-dev.gcba.gob.ar//lugares/sugerencias";
export declare const place_search_url = "https://api-serviciosgeo-dev.gcba.gob.ar//lugares/busqueda";
export declare const API_BASE_URL = "https://api-serviciosgeo-dev.gcba.gob.ar/";
export declare const API_URLS: {
address_suggestions_url: string;
address_search_url: string;
transform_coordinates_url: string;
place_suggestions_url: string;
place_search_url: string;
};

@@ -1,6 +0,9 @@

const API = "https://api-serviciosgeo-dev.gcba.gob.ar/";
export const address_suggestions_url = `${API}/calles/nombre`;
export const address_search_url = `${API}/direcciones/geocoder`;
export const transform_coordinates_url = `${API}/coordenadas/transformar`;
export const place_suggestions_url = `${API}/lugares/sugerencias`;
export const place_search_url = `${API}/lugares/busqueda`;
export const API_BASE_URL = "https://api-serviciosgeo-dev.gcba.gob.ar/";
// const API_PROD = "https://api-serviciosgeo.gcba.gob.ar/";
export const API_URLS = {
address_suggestions_url: "/calles/nombre",
address_search_url: "/direcciones/geocoder",
transform_coordinates_url: "/coordenadas/transformar",
place_suggestions_url: "/lugares/sugerencias",
place_search_url: "/lugares/busqueda",
};

@@ -1,1 +0,1 @@

export { Autocompleter } from './services/Autocompleter.js';
export {};

@@ -1,1 +0,25 @@

export { Autocompleter } from './services/Autocompleter.js';
// export { Autocompleter } from './services/Autocompleter.js';
import { Autocompleter } from "./services/Autocompleter.js";
const autocompleter = new Autocompleter();
let i = 0;
let calle = prompt("Ingrese la calle:");
if (calle) {
console.log("Input recibido:", calle); // Esto Verifica el input
const clientId = "b8e6e97b";
const clientSecret = "180db1929c02de9a65dbe4c3975e3953";
const apiBaseUrl = "https://datosabiertos-callejeros-apis.buenosaires.gob.ar/";
console.log("Configurando credenciales:", { clientId, clientSecret });
autocompleter.setCredentials(clientId, clientSecret);
console.log("Configurando URL base:", apiBaseUrl);
autocompleter.setApiBaseUrl(apiBaseUrl);
// Activa los suggesters manualmente
// autocompleter.enableSuggester(SuggestersOptions.AddressSuggester);
// autocompleter.enableSuggester(SuggestersOptions.PlaceSuggester);
autocompleter
.getSuggestions(calle, "address")
.then(data => console.log("Sugerencias obtenidas:", data))
.catch(error => console.error("Error:", error));
}
else {
console.log("No se ingresó ninguna calle."); // Verifica si el input está vacío
}

@@ -7,3 +7,5 @@ import Suggester from "./Suggester.js";

declare class AddressSuggester extends Suggester {
constructor(minTextLength?: number, waitingTime?: number, maxSuggestions?: number);
constructor(minTextLength?: number, waitingTime?: number, maxSuggestions?: number, apiUrls?: {
[key: string]: string;
});
search(address: string): Promise<AddressSearchResponse | void>;

@@ -10,0 +12,0 @@ transformCoordinates(x: number, y: number): Promise<any>;

@@ -11,6 +11,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

import Suggester from "./Suggester.js";
import { address_suggestions_url, address_search_url, transform_coordinates_url } from "../api/urls.js";
import { API_URLS } from "../api/urls.js";
class AddressSuggester extends Suggester {
constructor(minTextLength = 3, waitingTime = 1000, maxSuggestions = 10) {
super(minTextLength, waitingTime, maxSuggestions);
constructor(minTextLength = 3, waitingTime = 1000, maxSuggestions = 10, apiUrls = API_URLS // Usa API_URLS como valor por defecto
) {
super(minTextLength, waitingTime, maxSuggestions, apiUrls); // Pasa apiUrls a la clase base
this.name = "AddressSuggester";

@@ -22,3 +23,4 @@ }

if (this.active) {
const response = yield fetch(`${address_search_url}?direccion=${address}`, this.getCredentials());
const url = this.getApiUrl("address_search_url"); // Usa getApiUrl
const response = yield fetch(`${url}?direccion=${address}`, this.getCredentials());
const jsonResponse = yield response.json();

@@ -38,3 +40,4 @@ if (jsonResponse.status_code === 200) {

return __awaiter(this, void 0, void 0, function* () {
const response = yield fetch(`${transform_coordinates_url}?x=${x}&y=${y}`, this.getCredentials());
const url = this.getApiUrl("transform_coordinates_url"); // Usa getApiUrl
const response = yield fetch(`${url}?x=${x}&y=${y}`, this.getCredentials());
const jsonResponse = yield response.json();

@@ -51,2 +54,3 @@ return jsonResponse.data;

const jsonSuggestions = yield this.getSuggestions(street);
console.log("Respuesta de la API (AddressSuggester):", jsonSuggestions);
if ("error" in jsonSuggestions) {

@@ -59,3 +63,2 @@ resolve(jsonSuggestions);

resolve(this.errorResponse);
;
}

@@ -82,4 +85,16 @@ else {

return __awaiter(this, void 0, void 0, function* () {
const response = yield fetch(`${address_suggestions_url}?calle=${street}`, this.getCredentials());
return yield response.json();
const url = this.getApiUrl("address_suggestions_url"); // Usa getApiUrl
console.log("URL completa (AddressSuggester):", url); // Verifica la URL
console.log("Credenciales (AddressSuggester):", this.getCredentials());
try {
const response = yield fetch(`${url}?calle=${street}`, this.getCredentials());
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return yield response.json();
}
catch (error) {
console.error("Error al obtener sugerencias:", error);
throw error;
}
});

@@ -91,3 +106,6 @@ }

const atipicalStreets = ((_b = unsortedStreets === null || unsortedStreets === void 0 ? void 0 : unsortedStreets.data) === null || _b === void 0 ? void 0 : _b.calles_atipicas) || [];
const mergedStreets = [...streets, ...atipicalStreets];
const mergedStreets = [
...streets,
...atipicalStreets,
];
return mergedStreets.sort((a, b) => (b.similaridad - a.similaridad));

@@ -99,3 +117,5 @@ }

if (typeof street.intersecciones !== "undefined") {
return (street.intersecciones.map((intersection) => ({ direccion: `${street.nombre_calle} Y ${intersection.nombre_oficial}` })));
return street.intersecciones.map((intersection) => ({
direccion: `${street.nombre_calle} Y ${intersection.nombre_oficial}`,
}));
}

@@ -116,3 +136,3 @@ // Alturas válidas para calle ingresada

this.errorResponse = {
error: { error: message, "valid_numbers": valid_street_numbers },
error: { error: message, valid_numbers: valid_street_numbers },
status_code: 400,

@@ -119,0 +139,0 @@ };

@@ -9,10 +9,11 @@ import Suggester from "./Suggester.js";

private AuxSuggesterTypes;
private apiBaseUrl;
constructor();
/**
* Retorna el atributo clientId
*/
*/
getClientId(): string;
/**
* Retorna el atributo clientSecret
*/
*/
getClientSecret(): string;

@@ -30,4 +31,9 @@ getHeadersCredentials(): {

* @param clientSecret: string
*/
*/
setCredentials(clientId: string, clientSecret: string): void;
/**
* Cambia la URL base de la API.
* @param baseUrl La nueva URL base.
*/
setApiBaseUrl(baseUrl: string): void;
private investTypesSuggesters;

@@ -38,3 +44,3 @@ private findSuggesterByType;

* @param suggester Tipo de suggester a activar.
*/
*/
findSuggester(suggesterType: SuggestersOptions): Suggester;

@@ -44,3 +50,3 @@ /**

* @param suggester Tipo de suggester a activar.
*/
*/
enableSuggester(suggester: SuggestersOptions): void;

@@ -50,3 +56,3 @@ /**

* @param suggester Tipo de suggester a activar.
*/
*/
disableSuggester(suggester: SuggestersOptions): void;

@@ -56,3 +62,3 @@ /**

* @returns Un objeto con los suggesters disponibles.
*/
*/
getSuggesters(): {

@@ -67,3 +73,3 @@ [key: string]: Suggester;

* @returns Sugerencias normalizadas.
*/
*/
normalizeSuggestions(suggesterName: string, suggestions: Object[] | null | any): any;

@@ -75,3 +81,3 @@ /**

* @returns Sugerencias correspondientes a la input.
*/
*/
getSuggestions(input: string, typeSuggester?: string): Promise<any>;

@@ -82,3 +88,3 @@ /**

* @returns El resultado de la búsqueda.
*/
*/
getSearch(suggestion: any): Promise<any>;

@@ -89,3 +95,3 @@ /**

* @returns El resultado de la búsqueda de direcciones.
*/
*/
getSearchAddress(address: string): Promise<any>;

@@ -96,4 +102,4 @@ /**

* @returns El resultado de la búsqueda de lugares.
*/
*/
getSearchPlaces(place: string): Promise<any>;
}

@@ -12,3 +12,4 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

import PlaceSuggester from "./PlacesSuggesters.js";
import { SuggestersOptions, SuggesterTypes } from "../models/options/SuggesterOptions.js";
import { SuggestersOptions, SuggesterTypes, } from "../models/options/SuggesterOptions.js";
import { API_URLS, API_BASE_URL } from "../api/urls.js"; // Importa el objeto API_URLS
export class Autocompleter {

@@ -20,18 +21,16 @@ constructor() {

this.clientSecret = "";
this.apiBaseUrl = API_BASE_URL;
// Inicializa los suggesters como un objeto con llave-valor
this.suggesters = {
AddressSuggester: new AddressSuggester(),
PlaceSuggester: new PlaceSuggester(),
AddressSuggester: new AddressSuggester(3, 1000, 10, API_URLS),
PlaceSuggester: new PlaceSuggester(3, 1000, 10, API_URLS),
};
this.activeSuggeters = Object.values(this.suggesters);
this.AuxSuggesterTypes = this.investTypesSuggesters(SuggesterTypes);
for (let suggester in this.suggesters) {
if (this.suggesters[suggester].getActive()) {
this.activeSuggeters.push(this.suggesters[suggester]);
}
;
}
// Propaga la URL base a los suggesters
this.setApiBaseUrl(this.apiBaseUrl);
}
/**
* Retorna el atributo clientId
*/
*/
getClientId() {

@@ -42,3 +41,3 @@ return this.clientId;

* Retorna el atributo clientSecret
*/
*/
getClientSecret() {

@@ -54,8 +53,7 @@ return this.clientSecret;

headers: {
"client_id": this.getClientId(),
"client_secret": this.getClientSecret(),
}
client_id: this.getClientId(),
client_secret: this.getClientSecret(),
},
};
}
;
/**

@@ -65,10 +63,25 @@ * Permite establecer los atributos clientId y clientSecret

* @param clientSecret: string
*/
*/
setCredentials(clientId, clientSecret) {
this.clientId = clientId;
this.clientSecret = clientSecret;
this.activeSuggeters.forEach((active) => {
this.activeSuggeters.forEach(active => {
active.setCredentials(this.getHeadersCredentials());
});
}
/**
* Cambia la URL base de la API.
* @param baseUrl La nueva URL base.
*/
setApiBaseUrl(baseUrl) {
if (!baseUrl.endsWith("/")) {
baseUrl += "/";
}
this.apiBaseUrl = baseUrl;
// Actualizar las URLs en todos los suggesters
Object.values(this.suggesters).forEach(suggester => {
console.log(`Actualizando URL base para ${suggester.getName()} a ${baseUrl}`);
suggester.setApiBaseUrl(baseUrl);
});
}
investTypesSuggesters(Types) {

@@ -98,3 +111,3 @@ let investObject = {};

* @param suggester Tipo de suggester a activar.
*/
*/
findSuggester(suggesterType) {

@@ -111,6 +124,11 @@ let options = Object.values(SuggestersOptions);

* @param suggester Tipo de suggester a activar.
*/
*/
enableSuggester(suggester) {
let selectedSuggester = this.findSuggester(suggester);
selectedSuggester.setActive(true);
if (selectedSuggester) {
selectedSuggester.setActive(true);
}
else {
console.error(`Suggester de tipo '${suggester}' no encontrado.`);
}
}

@@ -120,3 +138,3 @@ /**

* @param suggester Tipo de suggester a activar.
*/
*/
disableSuggester(suggester) {

@@ -129,3 +147,3 @@ let selectedSuggester = this.findSuggester(suggester);

* @returns Un objeto con los suggesters disponibles.
*/
*/
getSuggesters() {

@@ -140,10 +158,19 @@ return this.suggesters;

* @returns Sugerencias normalizadas.
*/
*/
normalizeSuggestions(suggesterName, suggestions) {
let response = [];
if (suggestions === null || suggestions === undefined) {
return response.push({ error: true, type: SuggesterTypes[suggesterName], value: "No se encontraron sugerencias." });
return response.push({
error: true,
type: SuggesterTypes[suggesterName],
value: "No se encontraron sugerencias.",
});
}
if ("error" in suggestions) {
response.push({ error: true, type: SuggesterTypes[suggesterName], value: suggestions.error, status_code: suggestions.status_code });
response.push({
error: true,
type: SuggesterTypes[suggesterName],
value: suggestions.error,
status_code: suggestions.status_code,
});
}

@@ -154,3 +181,7 @@ if (suggesterName == "AddressSuggester") {

if (!("error" in suggestion)) {
response.push({ error: false, type: SuggesterTypes[suggesterName], value: suggestion.direccion });
response.push({
error: false,
type: SuggesterTypes[suggesterName],
value: suggestion.direccion,
});
}

@@ -164,3 +195,8 @@ });

if (!("error" in suggestion)) {
response.push({ error: false, type: SuggesterTypes[suggesterName], value: suggestion.nombre, category: suggestion.categoria });
response.push({
error: false,
type: SuggesterTypes[suggesterName],
value: suggestion.nombre,
category: suggestion.categoria,
});
}

@@ -177,3 +213,3 @@ });

* @returns Sugerencias correspondientes a la input.
*/
*/
getSuggestions(input, typeSuggester = "all") {

@@ -192,2 +228,3 @@ return __awaiter(this, void 0, void 0, function* () {

const fetchedSuggestions = yield Promise.all(suggestionPromises);
console.log("Sugerencias procesadas:", fetchedSuggestions);
fetchedSuggestions.forEach(element => {

@@ -210,3 +247,3 @@ response.push(this.normalizeSuggestions(element.suggesterName, element.suggestions));

* @returns El resultado de la búsqueda.
*/
*/
getSearch(suggestion) {

@@ -248,3 +285,3 @@ return __awaiter(this, void 0, void 0, function* () {

catch (error) {
return { "error": true, msg: error };
return { error: true, msg: error };
}

@@ -257,3 +294,3 @@ });

* @returns El resultado de la búsqueda de direcciones.
*/
*/
getSearchAddress(address) {

@@ -291,9 +328,9 @@ return __awaiter(this, void 0, void 0, function* () {

else {
return { "error": true, "msg": "AddressSuggester no está activo" };
return { error: true, msg: "AddressSuggester no está activo" };
}
}
return { "error": true, "msg": "No se encontró Suggester" };
return { error: true, msg: "No se encontró Suggester" };
}
catch (error) {
return { "error": true, msg: error };
return { error: true, msg: error };
}

@@ -306,3 +343,3 @@ });

* @returns El resultado de la búsqueda de lugares.
*/
*/
getSearchPlaces(place) {

@@ -340,9 +377,9 @@ return __awaiter(this, void 0, void 0, function* () {

else {
return { "error": true, "msg": "PlaceSuggester no está activo" };
return { error: true, msg: "PlaceSuggester no está activo" };
}
}
return { "error": true, "msg": "No se encontró Suggester" };
return { error: true, msg: "No se encontró Suggester" };
}
catch (error) {
return { "error": true, msg: error };
return { error: true, msg: error };
}

@@ -349,0 +386,0 @@ });

@@ -6,3 +6,5 @@ import Suggester from "./Suggester.js";

declare class PlaceSuggester extends Suggester {
constructor(minTextLength?: number, waitingTime?: number, maxSuggestions?: number);
constructor(minTextLength?: number, waitingTime?: number, maxSuggestions?: number, apiUrls?: {
[key: string]: string;
});
search(place: string): Promise<PlacesSearchResponse | void>;

@@ -9,0 +11,0 @@ getSuggestions(place: string): Promise<PlaceSuggestionResponse | ErrorResponse[]>;

@@ -11,6 +11,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

import Suggester from "./Suggester.js";
import { place_search_url, place_suggestions_url } from "../api/urls.js";
import { API_URLS } from "../api/urls.js";
class PlaceSuggester extends Suggester {
constructor(minTextLength = 3, waitingTime = 1000, maxSuggestions = 10) {
super(minTextLength, waitingTime, maxSuggestions);
constructor(minTextLength = 3, waitingTime = 1000, maxSuggestions = 10, apiUrls = API_URLS) {
super(minTextLength, waitingTime, maxSuggestions, apiUrls);
this.name = "PlaceSuggester";

@@ -21,3 +21,4 @@ }

if (this.active && place.length >= this.minTextLength) {
const response = yield fetch(`${place_search_url}?sitio_interes=${place}`, this.getCredentials());
const url = this.getApiUrl("place_search_url"); // Usa getApiUrl
const response = yield fetch(`${url}?sitio_interes=${place}`, this.getCredentials());
const jsonResponse = yield response.json();

@@ -30,3 +31,4 @@ return jsonResponse;

return __awaiter(this, void 0, void 0, function* () {
const response = yield fetch(`${place_suggestions_url}?sitio_interes=${place}`, this.getCredentials());
const url = this.getApiUrl("place_suggestions_url"); // Usa getApiUr
const response = yield fetch(`${url}?sitio_interes=${place}`, this.getCredentials());
const jsonResponse = yield response.json();

@@ -33,0 +35,0 @@ return jsonResponse;

@@ -16,3 +16,7 @@ import { AddressSearchResponse } from "../models/responses/AddressSearchResponse.js";

protected credentials: any;
constructor(minTextLength: number, waitingTime: number, maxSuggestions: number);
protected apiUrls: Record<string, string>;
protected apiBaseUrl: string;
constructor(minTextLength: number, waitingTime: number, maxSuggestions: number, apiUrls: {
[key: string]: string;
});
getName(): string;

@@ -40,2 +44,13 @@ getMinTextLength(): number;

abortSearch(): void;
/**
* Cambia la URL base de la API.
* @param baseUrl La nueva URL base.
*/
setApiBaseUrl(baseUrl: string): void;
/**
* Obtiene la URL completa para un endpoint específico.
* @param endpoint El endpoint (clave de API_URLS).
* @returns La URL completa.
*/
getApiUrl(endpoint: string): string;
setCredentials(credentials: any): void;

@@ -42,0 +57,0 @@ getCredentials(): any;

@@ -0,3 +1,5 @@

import { API_BASE_URL } from "../api/urls.js";
class Suggester {
constructor(minTextLength, waitingTime, maxSuggestions) {
constructor(minTextLength, waitingTime, maxSuggestions, apiUrls // Acepta el objeto apiUrls
) {
this.name = "";

@@ -7,2 +9,4 @@ this.minTextLength = minTextLength;

this.maxSuggestions = maxSuggestions;
this.apiUrls = Object.assign({}, apiUrls);
this.apiBaseUrl = API_BASE_URL || ""; // Inicializar la URL base por defecto
this.suggestions = Array();

@@ -65,2 +69,31 @@ this.active = true;

}
/**
* Cambia la URL base de la API.
* @param baseUrl La nueva URL base.
*/
setApiBaseUrl(baseUrl) {
if (!baseUrl.endsWith("/")) {
baseUrl += "/";
}
this.apiBaseUrl = baseUrl;
// Actualizar todas las URLs con la nueva base
Object.keys(this.apiUrls).forEach(key => {
const endpointPath = this.apiUrls[key].replace(/^https?:\/\/[^\/]+/, ""); // Elimina la URL base anterior
this.apiUrls[key] = `${baseUrl}${endpointPath.replace(/^\//, "")}`; // Asegura que no haya doble barra
});
console.log("URLs actualizadas:", this.apiUrls); // Depuración
}
/**
* Obtiene la URL completa para un endpoint específico.
* @param endpoint El endpoint (clave de API_URLS).
* @returns La URL completa.
*/
getApiUrl(endpoint) {
const url = this.apiUrls[endpoint];
if (!url) {
throw new Error(`Endpoint '${endpoint}' no está definido en API_URLS.`);
}
console.log(`URL construida para ${endpoint}: ${url}`);
return url;
}
setCredentials(credentials) {

@@ -67,0 +100,0 @@ this.credentials = credentials;

{
"name": "autocompleter-caba",
"version": "0.1.5",
"version": "0.1.6",
"private": false,

@@ -5,0 +5,0 @@ "description": "Un paquete para que permite obtener información sobre direcciones y sitios de interés de la Ciudad de Buenos Aires.",

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc