apiempresas 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,87 @@
1
+ # APIEmpresas.es - Node.js SDK
2
+
3
+ SDK oficial para interactuar con la API de [APIEmpresas.es](https://apiempresas.es) desde Node.js utilizando TypeScript o JavaScript.
4
+
5
+ ## Instalación
6
+
7
+ ```bash
8
+ npm install apiempresas
9
+ ```
10
+
11
+ ## Inicialización
12
+
13
+ ```typescript
14
+ import { ApiEmpresas } from 'apiempresas';
15
+
16
+ const api = new ApiEmpresas({
17
+ apiKey: 'TU_API_KEY', // Obligatorio
18
+ });
19
+ ```
20
+
21
+ ## Uso Básico
22
+
23
+ ### 1. Obtener datos de una empresa
24
+
25
+ ```typescript
26
+ async function fetchCompany() {
27
+ try {
28
+ const company = await api.companies.get('B12345678');
29
+ console.log(company.name);
30
+ } catch (error) {
31
+ console.error('Error fetching company:', error.message);
32
+ }
33
+ }
34
+ ```
35
+
36
+ ### 2. Historial de Actos del BORME
37
+
38
+ ```typescript
39
+ async function fetchBorme() {
40
+ const bormeData = await api.companies.borme('B12345678');
41
+ console.log(bormeData.events);
42
+ }
43
+ ```
44
+
45
+ ### 3. Consulta Múltiple (Batch)
46
+
47
+ ```typescript
48
+ async function fetchBatch() {
49
+ const response = await api.companies.batch({
50
+ cifs: ['B12345678', 'A15075062']
51
+ });
52
+ console.log('Resultados:', response.data);
53
+ console.log('Coste:', response.meta.cost);
54
+ }
55
+ ```
56
+
57
+ ## Entorno de Pruebas (Sandbox)
58
+
59
+ Para probar la integración sin consumir saldo, puedes apuntar a la URL del Sandbox:
60
+
61
+ ```typescript
62
+ const api = new ApiEmpresas({
63
+ apiKey: 'sandbox_api_key',
64
+ baseURL: 'https://apiempresas.es/api/sandbox/v1'
65
+ });
66
+ ```
67
+
68
+ ## Manejo de Errores
69
+
70
+ El SDK arrojará un `ApiError` detallado si ocurre algún problema (ej. Plan Insuficiente, CIF inválido).
71
+
72
+ ```typescript
73
+ import { ApiError } from 'apiempresas';
74
+
75
+ try {
76
+ await api.companies.score('B00000000');
77
+ } catch (error) {
78
+ if (error instanceof ApiError) {
79
+ console.error(`Status: ${error.status}`);
80
+ console.error(`Message: ${error.message}`);
81
+ console.error(`Code: ${error.errorCode}`);
82
+ }
83
+ }
84
+ ```
85
+
86
+ ## Licencia
87
+ MIT
@@ -0,0 +1,10 @@
1
+ import { ApiEmpresasOptions } from './types';
2
+ import { Companies } from './resources/Companies';
3
+ export declare class ApiEmpresas {
4
+ private apiKey;
5
+ private baseURL;
6
+ private timeout;
7
+ companies: Companies;
8
+ constructor(options: ApiEmpresasOptions);
9
+ request<T>(endpoint: string, options?: RequestInit): Promise<T>;
10
+ }
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ApiEmpresas = void 0;
4
+ const ApiError_1 = require("./errors/ApiError");
5
+ const Companies_1 = require("./resources/Companies");
6
+ class ApiEmpresas {
7
+ apiKey;
8
+ baseURL;
9
+ timeout;
10
+ companies;
11
+ constructor(options) {
12
+ if (!options || !options.apiKey) {
13
+ throw new Error("La propiedad 'apiKey' es obligatoria para inicializar ApiEmpresas.");
14
+ }
15
+ this.apiKey = options.apiKey;
16
+ this.baseURL = (options.baseURL || 'https://apiempresas.es/api/v1').replace(/\/$/, '');
17
+ this.timeout = options.timeout || 30000;
18
+ this.companies = new Companies_1.Companies(this);
19
+ }
20
+ async request(endpoint, options = {}) {
21
+ const url = `${this.baseURL}${endpoint}`;
22
+ const headers = new Headers(options.headers || {});
23
+ headers.set('X-API-KEY', this.apiKey);
24
+ headers.set('Accept', 'application/json');
25
+ if (!headers.has('Content-Type') && options.method && options.method.toUpperCase() !== 'GET') {
26
+ headers.set('Content-Type', 'application/json');
27
+ }
28
+ const controller = new AbortController();
29
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
30
+ try {
31
+ const response = await fetch(url, {
32
+ ...options,
33
+ headers,
34
+ signal: controller.signal
35
+ });
36
+ clearTimeout(timeoutId);
37
+ const isJson = response.headers.get('content-type')?.includes('application/json');
38
+ const data = isJson ? await response.json() : await response.text();
39
+ if (!response.ok) {
40
+ throw new ApiError_1.ApiError(response.status, data?.message || response.statusText || 'Error desconocido en la API', data?.error || undefined, data);
41
+ }
42
+ return data;
43
+ }
44
+ catch (error) {
45
+ clearTimeout(timeoutId);
46
+ if (error.name === 'AbortError') {
47
+ throw new ApiError_1.ApiError(408, `La petición superó el tiempo límite de ${this.timeout}ms`);
48
+ }
49
+ if (error instanceof ApiError_1.ApiError) {
50
+ throw error;
51
+ }
52
+ throw new ApiError_1.ApiError(500, error.message || 'Error de red o conexión fallida');
53
+ }
54
+ }
55
+ }
56
+ exports.ApiEmpresas = ApiEmpresas;
@@ -0,0 +1,6 @@
1
+ export declare class ApiError extends Error {
2
+ status: number;
3
+ errorCode?: string;
4
+ rawData?: any;
5
+ constructor(status: number, message: string, errorCode?: string, rawData?: any);
6
+ }
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ApiError = void 0;
4
+ class ApiError extends Error {
5
+ status;
6
+ errorCode;
7
+ rawData;
8
+ constructor(status, message, errorCode, rawData) {
9
+ super(message);
10
+ this.name = 'ApiError';
11
+ this.status = status;
12
+ this.errorCode = errorCode;
13
+ this.rawData = rawData;
14
+ // Fix prototype chain for built-in classes in TS
15
+ Object.setPrototypeOf(this, ApiError.prototype);
16
+ }
17
+ }
18
+ exports.ApiError = ApiError;
@@ -0,0 +1,3 @@
1
+ export { ApiEmpresas } from './ApiEmpresas';
2
+ export { ApiError } from './errors/ApiError';
3
+ export * from './types';
package/dist/index.js ADDED
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.ApiError = exports.ApiEmpresas = void 0;
18
+ var ApiEmpresas_1 = require("./ApiEmpresas");
19
+ Object.defineProperty(exports, "ApiEmpresas", { enumerable: true, get: function () { return ApiEmpresas_1.ApiEmpresas; } });
20
+ var ApiError_1 = require("./errors/ApiError");
21
+ Object.defineProperty(exports, "ApiError", { enumerable: true, get: function () { return ApiError_1.ApiError; } });
22
+ __exportStar(require("./types"), exports);
@@ -0,0 +1,37 @@
1
+ import { ApiEmpresas } from '../ApiEmpresas';
2
+ import { Company, BatchRequest, BatchResponse, ScoreData, BormeData, SignalsData } from '../types';
3
+ export declare class Companies {
4
+ private client;
5
+ constructor(client: ApiEmpresas);
6
+ /**
7
+ * Obtiene los datos básicos de una empresa por su CIF.
8
+ */
9
+ get(cif: string): Promise<Company>;
10
+ /**
11
+ * Busca empresas por nombre o razón social.
12
+ */
13
+ search(q: string): Promise<Company>;
14
+ /**
15
+ * Consulta múltiple de CIFs en una sola petición.
16
+ */
17
+ batch(request: BatchRequest): Promise<{
18
+ meta: BatchResponse;
19
+ data: Company[];
20
+ }>;
21
+ /**
22
+ * (Pro) Obtiene el Scoring Comercial de una empresa.
23
+ */
24
+ score(cif: string): Promise<ScoreData>;
25
+ /**
26
+ * (Pro) Obtiene el historial de actos del BORME de una empresa.
27
+ */
28
+ borme(cif: string): Promise<BormeData>;
29
+ /**
30
+ * (Pro) Obtiene las señales societarias recientes de una empresa.
31
+ */
32
+ signals(cif: string): Promise<SignalsData>;
33
+ /**
34
+ * (Business) Obtiene Insights IA de una empresa.
35
+ */
36
+ insights(cif: string): Promise<any>;
37
+ }
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Companies = void 0;
4
+ class Companies {
5
+ client;
6
+ constructor(client) {
7
+ this.client = client;
8
+ }
9
+ /**
10
+ * Obtiene los datos básicos de una empresa por su CIF.
11
+ */
12
+ async get(cif) {
13
+ const params = new URLSearchParams({ cif });
14
+ const response = await this.client.request(`/companies?${params.toString()}`);
15
+ return response.data;
16
+ }
17
+ /**
18
+ * Busca empresas por nombre o razón social.
19
+ */
20
+ async search(q) {
21
+ const params = new URLSearchParams({ q });
22
+ const response = await this.client.request(`/companies/search?${params.toString()}`);
23
+ return response.data;
24
+ }
25
+ /**
26
+ * Consulta múltiple de CIFs en una sola petición.
27
+ */
28
+ async batch(request) {
29
+ const response = await this.client.request('/companies/batch', {
30
+ method: 'POST',
31
+ body: JSON.stringify(request)
32
+ });
33
+ return { meta: response.meta, data: response.data };
34
+ }
35
+ /**
36
+ * (Pro) Obtiene el Scoring Comercial de una empresa.
37
+ */
38
+ async score(cif) {
39
+ const params = new URLSearchParams({ cif });
40
+ const response = await this.client.request(`/companies/score?${params.toString()}`);
41
+ return response.data;
42
+ }
43
+ /**
44
+ * (Pro) Obtiene el historial de actos del BORME de una empresa.
45
+ */
46
+ async borme(cif) {
47
+ const params = new URLSearchParams({ cif });
48
+ const response = await this.client.request(`/companies/borme?${params.toString()}`);
49
+ return response.data;
50
+ }
51
+ /**
52
+ * (Pro) Obtiene las señales societarias recientes de una empresa.
53
+ */
54
+ async signals(cif) {
55
+ const params = new URLSearchParams({ cif });
56
+ const response = await this.client.request(`/companies/signals?${params.toString()}`);
57
+ return response.data;
58
+ }
59
+ /**
60
+ * (Business) Obtiene Insights IA de una empresa.
61
+ */
62
+ async insights(cif) {
63
+ const params = new URLSearchParams({ cif });
64
+ const response = await this.client.request(`/companies/insights?${params.toString()}`);
65
+ return response.data;
66
+ }
67
+ }
68
+ exports.Companies = Companies;
@@ -0,0 +1,75 @@
1
+ export interface ApiEmpresasOptions {
2
+ /**
3
+ * Tu API Key de APIEmpresas.es
4
+ */
5
+ apiKey: string;
6
+ /**
7
+ * Base URL de la API. Por defecto es https://apiempresas.es/api/v1
8
+ * Puedes sobreescribirla para apuntar al sandbox: https://apiempresas.es/api/sandbox/v1
9
+ */
10
+ baseURL?: string;
11
+ /**
12
+ * Timeout opcional para las peticiones en milisegundos.
13
+ */
14
+ timeout?: number;
15
+ }
16
+ export interface BaseResponse<T = any> {
17
+ success: boolean;
18
+ data?: T;
19
+ error?: string;
20
+ message?: string;
21
+ }
22
+ export interface Company {
23
+ id?: number;
24
+ cif: string;
25
+ name: string;
26
+ cnae?: string;
27
+ cnae_label?: string;
28
+ founded?: string;
29
+ province?: string;
30
+ municipality?: string;
31
+ address?: string;
32
+ status?: string;
33
+ score?: number;
34
+ }
35
+ export interface BatchRequest {
36
+ cifs: string[];
37
+ admin?: boolean;
38
+ }
39
+ export interface BatchResponse {
40
+ requested: number;
41
+ found: number;
42
+ cost: number;
43
+ truncated: boolean;
44
+ }
45
+ export interface ScoreData {
46
+ cif: string;
47
+ score: number;
48
+ priority: string;
49
+ reasons: string[];
50
+ last_signal?: {
51
+ type: string;
52
+ date: string;
53
+ };
54
+ }
55
+ export interface BormeEvent {
56
+ date: string;
57
+ act_types: string;
58
+ description: string;
59
+ url_pdf: string;
60
+ }
61
+ export interface BormeData {
62
+ cif: string;
63
+ company_name: string;
64
+ events: BormeEvent[];
65
+ }
66
+ export interface SignalEvent {
67
+ type: string;
68
+ label: string;
69
+ date: string;
70
+ probability: string;
71
+ }
72
+ export interface SignalsData {
73
+ cif: string;
74
+ signals: SignalEvent[];
75
+ }
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/package.json ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "apiempresas",
3
+ "version": "1.0.0",
4
+ "description": "SDK oficial de APIEmpresas.es para Node.js y TypeScript",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "scripts": {
8
+ "build": "tsc",
9
+ "test": "jest",
10
+ "prepublishOnly": "npm run build"
11
+ },
12
+ "keywords": [
13
+ "apiempresas",
14
+ "empresas",
15
+ "cif",
16
+ "borme",
17
+ "registro mercantil",
18
+ "españa"
19
+ ],
20
+ "author": "APIEmpresas",
21
+ "license": "MIT",
22
+ "devDependencies": {
23
+ "@types/jest": "^29.5.12",
24
+ "@types/node": "^20.11.19",
25
+ "jest": "^29.7.0",
26
+ "ts-jest": "^29.1.2",
27
+ "typescript": "^5.3.3"
28
+ }
29
+ }