@fiado/api-invoker 1.5.33 → 1.5.35

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 CHANGED
@@ -1,64 +1,600 @@
1
- # fiado-api-invoker
1
+ <div align="center">
2
2
 
3
- `fiado-api-invoker` es una librería diseñada para facilitar la invocación de APIs privadas de AWS Lambda a través de API Gateway dentro de la misma VPC. Esta librería simplifica el proceso de configuración y llamada a servicios, permitiendo a los desarrolladores centrarse en la lógica de negocio.
3
+ # 🔗 Fiado API Invoker
4
4
 
5
+ ### Librería de Comunicación Inter-Servicios para Microservicios Lambda
5
6
 
6
- ## Configuración
7
+ [![npm](https://img.shields.io/badge/npm-@fiado/api--invoker-CB3837?logo=npm&logoColor=white)](https://www.npmjs.com/)
8
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.x-3178C6?logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
9
+ [![AWS Lambda](https://img.shields.io/badge/AWS-Lambda-FF9900?logo=aws-lambda&logoColor=white)](https://aws.amazon.com/lambda/)
10
+ [![InversifyJS](https://img.shields.io/badge/InversifyJS-6.x-1E88E5)](https://inversify.io/)
11
+
12
+ </div>
13
+
14
+ ---
15
+
16
+ ## Tabla de Contenidos
17
+
18
+ - [Descripción General](#descripción-general)
19
+ - [Arquitectura](#arquitectura)
20
+ - [Instalación](#instalación)
21
+ - [Configuración](#configuración)
22
+ - [APIs Disponibles](#apis-disponibles)
23
+ - [Publishers (Colas SQS)](#publishers-colas-sqs)
24
+ - [Uso en Proyectos](#uso-en-proyectos)
25
+ - [Variables de Entorno](#variables-de-entorno)
26
+ - [Estructura del Proyecto](#estructura-del-proyecto)
27
+ - [Convenciones de Desarrollo](#convenciones-de-desarrollo)
28
+ - [Dependencias](#dependencias)
29
+
30
+ ---
31
+
32
+ ## Descripción General
33
+
34
+ `@fiado/api-invoker` es una librería empresarial que actúa como **puente de comunicación entre microservicios Lambda** dentro del ecosistema Fiado. Proporciona:
35
+
36
+ - **Clientes HTTP tipados** para invocar APIs privadas de otros Lambdas
37
+ - **Publishers SQS** para comunicación asíncrona mediante colas
38
+ - **Inyección de dependencias** integrada con InversifyJS
39
+ - **Abstracción de complejidad** de configuración y manejo de errores
40
+
41
+ ### Propósito
42
+
43
+ En una arquitectura de microservicios, cada Lambda expone una API privada accesible únicamente desde la VPC. Esta librería encapsula:
7
44
 
8
- Antes de usar la librería, asegúrate de configurar la URL base del API Gateway privado que corresponda por ejemplo si vas a usar los servicios del Lambda `Directory` se puede hacer estableciendo la variable de entorno `DIRECTORY_LAMBDA_URL`.
45
+ 1. La construcción de URLs base desde variables de entorno
46
+ 2. El manejo de headers y operaciones HTTP
47
+ 3. La serialización/deserialización de payloads
48
+ 4. La publicación de mensajes a colas SQS
9
49
 
50
+ ---
51
+
52
+ ## Arquitectura
53
+
54
+ ```
55
+ ┌─────────────────────────────────────────────────────────────────────────┐
56
+ │ LAMBDA CONSUMIDOR │
57
+ │ │
58
+ │ ┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐ │
59
+ │ │ Manager/ │───▶│ @fiado/ │───▶│ @fiado/ │ │
60
+ │ │ Service │ │ api-invoker │ │ http-client │ │
61
+ │ └──────────────────┘ └──────────────────┘ └──────────────────┘ │
62
+ │ │ │ │
63
+ └───────────────────────────────────┼────────────────────────┼────────────┘
64
+ │ │
65
+ ┌───────────────┴───────────────┐ │
66
+ ▼ ▼ ▼
67
+ ┌──────────────┐ ┌──────────────────┐
68
+ │ AWS SQS │ │ API Gateway │
69
+ │ (Queues) │ │ (Private VPC) │
70
+ └──────────────┘ └──────────────────┘
71
+ │ │
72
+ ▼ ▼
73
+ ┌──────────────┐ ┌──────────────────┐
74
+ │ Lambda │ │ Lambda │
75
+ │ Subscriber │ │ Target │
76
+ └──────────────┘ └──────────────────┘
77
+ ```
78
+
79
+ ### Patrones de Comunicación
80
+
81
+ | Patrón | Implementación | Uso |
82
+ |--------|----------------|-----|
83
+ | **Síncrono** | HTTP via API Gateway privado | Consultas, operaciones CRUD |
84
+ | **Asíncrono** | SQS Publishers | Eventos, notificaciones, procesos batch |
85
+
86
+ ---
10
87
 
11
88
  ## Instalación
89
+
12
90
  ```bash
13
- `npm install fiado-api-invoker @fiado/http-client`
91
+ npm install @fiado/api-invoker @fiado/http-client
14
92
  ```
15
93
 
16
- ## Configuración del Contenedor de InversifyJS
94
+ ### Peer Dependencies
95
+
96
+ La librería requiere las siguientes dependencias en el proyecto consumidor:
97
+
98
+ ```json
99
+ {
100
+ "@fiado/http-client": "^1.0.7",
101
+ "@fiado/logger": "^1.0.3",
102
+ "@fiado/type-kit": "^2.1.28",
103
+ "inversify": "^6.2.2",
104
+ "reflect-metadata": "^0.2.2"
105
+ }
106
+ ```
107
+
108
+ ---
109
+
110
+ ## Configuración
111
+
112
+ ### Registro en el Contenedor IoC
113
+
114
+ La librería exporta un `ContainerModule` de InversifyJS que registra automáticamente todos los clientes API y publishers:
17
115
 
18
116
  ```typescript
19
117
  import { Container } from "inversify";
20
118
  import { IHttpRequest, AxiosHttpRequest } from "@fiado/http-client";
21
- import { apiInvokerContainer } from '@fiado/api-invoker';
119
+ import { apiInvokerBindings } from "@fiado/api-invoker";
22
120
 
23
- // Crea el contenedor principal de tu aplicación
24
121
  const container = new Container();
25
122
 
26
- // Aplica las configuraciones de vinculación de fiado-gateway-adapter al contenedor
27
- container.load(gatewayAdapterBindings);
123
+ // 1. Cargar bindings de api-invoker (registra todos los clientes)
124
+ container.load(apiInvokerBindings);
28
125
 
29
- // Registro del cliente HTTP
126
+ // 2. Registrar el cliente HTTP (requerido por los clientes API)
30
127
  container.bind<IHttpRequest>("IHttpRequest").to(AxiosHttpRequest);
31
128
 
32
- // Exporta el contenedor para su uso en toda tu aplicación
33
129
  export { container };
130
+ ```
34
131
 
132
+ ### Importación de Interfaces
35
133
 
134
+ ```typescript
135
+ // Importar interfaces específicas
136
+ import {
137
+ IDirectoryApi,
138
+ IIdentityApi,
139
+ ITransactionApi,
140
+ INotificationMessagesPublisher
141
+ } from "@fiado/api-invoker";
36
142
  ```
37
143
 
144
+ ---
145
+
146
+ ## APIs Disponibles
147
+
148
+ La librería proporciona clientes para **60+ microservicios** del ecosistema Fiado:
149
+
150
+ ### Servicios Core
151
+
152
+ | Interface | Descripción | Variable de Entorno |
153
+ |-----------|-------------|---------------------|
154
+ | `IDirectoryApi` | Gestión de directorios de usuarios | `DIRECTORY_LAMBDA_URL` |
155
+ | `IIdentityApi` | Verificación de identidad | `IDENTITY_LAMBDA_URL` |
156
+ | `IAuthenticationApi` | Autenticación y tokens | `AUTHENTICATION_LAMBDA_URL` |
157
+ | `ITransactionApi` | Procesamiento de transacciones | `TRANSACTION_LAMBDA_URL` |
158
+
159
+ ### Servicios de Cuenta
160
+
161
+ | Interface | Descripción | Variable de Entorno |
162
+ |-----------|-------------|---------------------|
163
+ | `IAccountFiadoIncApi` | Cuentas Fiado Inc | `ACCOUNT_FIADOINC_LAMBDA_URL` |
164
+ | `IAccountFiadoSAApi` | Cuentas Fiado SA | `ACCOUNT_FIADOSA_LAMBDA_URL` |
165
+ | `IAccountPagoConfiadoApi` | Cuentas PagoConfiado | `ACCOUNT_PAGOCONFIADO_LAMBDA_URL` |
166
+ | `IAccountBeneficiaryApi` | Beneficiarios de cuentas | `ACCOUNT_BENEFICIARY_LAMBDA_URL` |
167
+ | `IBankAccountApi` | Cuentas bancarias | `BANK_ACCOUNT_LAMBDA_URL` |
168
+
169
+ ### Servicios de Pago
170
+
171
+ | Interface | Descripción | Variable de Entorno |
172
+ |-----------|-------------|---------------------|
173
+ | `IStpSpeiApi` | Transferencias SPEI | `STP_SPEI_LAMBDA_URL` |
174
+ | `IStpServicePaymentApi` | Pagos de servicios STP | `STP_SERVICE_PAYMENT_LAMBDA_URL` |
175
+ | `ICentralPaymentsConnectorApi` | Conector de pagos central | `CENTRAL_PAYMENTS_LAMBDA_URL` |
176
+ | `ICollectorApi` | Cobranza | `COLLECTOR_LAMBDA_URL` |
177
+
178
+ ### Servicios de Tarjeta
179
+
180
+ | Interface | Descripción | Variable de Entorno |
181
+ |-----------|-------------|---------------------|
182
+ | `ICardApi` | Gestión de tarjetas | `CARD_LAMBDA_URL` |
183
+ | `IPomeloApi` | Integración Pomelo | `POMELO_LAMBDA_URL` |
184
+ | `IPomeloProcessorApi` | Procesador Pomelo | `POMELO_PROCESSOR_LAMBDA_URL` |
185
+
186
+ ### Servicios de Riesgo y Fraude
38
187
 
39
- ## Uso de IDirectoryApi en Servicios del Proyecto
188
+ | Interface | Descripción | Variable de Entorno |
189
+ |-----------|-------------|---------------------|
190
+ | `IRiskProfileApi` | Perfiles de riesgo | `RISK_PROFILE_LAMBDA_URL` |
191
+ | `IFraudPreventionEngineApi` | Motor antifraude | `FRAUD_PREVENTION_LAMBDA_URL` |
192
+ | `IBlackListApi` | Listas negras | `BLACKLIST_LAMBDA_URL` |
193
+ | `ITransactionAlertApi` | Alertas de transacciones | `RISK_PROFILE_LAMBDA_URL` |
40
194
 
41
- Para utilizar `fiado-api-invoker`, necesitas configurar el contenedor de InversifyJS en tu aplicación. Aquí te mostramos cómo registrar las dependencias necesarias:
195
+ ### Servicios de Onboarding
196
+
197
+ | Interface | Descripción | Variable de Entorno |
198
+ |-----------|-------------|---------------------|
199
+ | `IOnboardingApi` | Onboarding de usuarios | `ONBOARDING_LAMBDA_URL` |
200
+ | `IOnboardingBusinessApi` | Onboarding de negocios | `ONBOARDING_BUSINESS_LAMBDA_URL` |
201
+ | `ICnbvApi` | Integración CNBV | `CNBV_BUSINESS_LAMBDA_URL` |
202
+
203
+ ### Servicios de Comunicación
204
+
205
+ | Interface | Descripción | Variable de Entorno |
206
+ |-----------|-------------|---------------------|
207
+ | `IFiadoMessagesApi` | Mensajería interna | `FIADO_MESSAGES_LAMBDA_URL` |
208
+ | `IFirebaseConnectorApi` | Push notifications | `FIREBASE_CONNECTOR_LAMBDA_URL` |
209
+ | `IZendeskApi` | Integración Zendesk | `ZENDESK_LAMBDA_URL` |
210
+
211
+ ### Servicios de Negocio
212
+
213
+ | Interface | Descripción | Variable de Entorno |
214
+ |-----------|-------------|---------------------|
215
+ | `IActivityApi` | Actividades de negocio | `ACTIVITY_BUSINESS_LAMBDA_URL` |
216
+ | `IServiceApi` | Servicios de negocio | `SERVICE_BUSINESS_LAMBDA_URL` |
217
+ | `IPriceListApi` | Listas de precios | `PRICELIST_BUSINESS_LAMBDA_URL` |
218
+ | `IPayrollApi` | Nómina | `PAYROLL_BUSINESS_LAMBDA_URL` |
219
+ | `IOrderCollectorApi` | Órdenes de cobranza | `ORDER_COLLECTOR_LAMBDA_URL` |
220
+
221
+ ### Servicios Auxiliares
222
+
223
+ | Interface | Descripción | Variable de Entorno |
224
+ |-----------|-------------|---------------------|
225
+ | `IAddressApi` | Direcciones | `ADDRESS_LAMBDA_URL` |
226
+ | `IContactInformationApi` | Información de contacto | `CONTACT_INFORMATION_LAMBDA_URL` |
227
+ | `IDeviceApi` | Dispositivos | `DEVICE_LAMBDA_URL` |
228
+ | `IGroupApi` | Grupos | `GROUP_LAMBDA_URL` |
229
+ | `IP2pContactApi` | Contactos P2P | `P2P_CONTACT_LAMBDA_URL` |
230
+ | `IExchangeRatesApi` | Tipos de cambio | `EXCHANGE_RATES_LAMBDA_URL` |
231
+ | `IProductCatalogApi` | Catálogo de productos | `PRODUCT_CATALOG_LAMBDA_URL` |
232
+ | `IContractGeneratorApi` | Generador de contratos | `CONTRACT_GENERATOR_LAMBDA_URL` |
233
+ | `IDocumentImageProcessorApi` | Procesador de imágenes | `DOCUMENT_IMAGE_PROCESSOR_LAMBDA_URL` |
234
+ | `ILegalDocumentApi` | Documentos legales | `LEGAL_DOCUMENT_LAMBDA_URL` |
235
+ | `IObservationsApi` | Observaciones | `OBSERVATIONS_LAMBDA_URL` |
236
+ | `IDirectoriesApi` | Directorios múltiples | `DIRECTORIES_LAMBDA_URL` |
237
+ | `IDirectorySettingApi` | Configuración de directorio | `DIRECTORY_SETTING_LAMBDA_URL` |
238
+ | `IAppSelectionDataApi` | Datos de selección de app | `APP_SELECTION_DATA_LAMBDA_URL` |
239
+ | `IReferralBusinessApi` | Referidos | `REFERRAL_BUSINESS_LAMBDA_URL` |
240
+ | `IEventHistoryApi` | Historial de eventos | `EVENT_HISTORY_LAMBDA_URL` |
241
+ | `IReportProcessorBusinessApi` | Procesador de reportes | `REPORT_PROCESSOR_LAMBDA_URL` |
242
+ | `IPeopleBusinessApi` | Gestión de personas | `PEOPLE_BUSINESS_LAMBDA_URL` |
243
+
244
+ ### Integraciones Externas
245
+
246
+ | Interface | Descripción | Variable de Entorno |
247
+ |-----------|-------------|---------------------|
248
+ | `ITernApi` | Integración Tern | `TERN_LAMBDA_URL` |
249
+ | `IBBVARstApi` | Integración BBVA RST | `BBVA_RST_LAMBDA_URL` |
250
+ | `IEstafetaApi` | Integración Estafeta | `ESTAFETA_LAMBDA_URL` |
251
+ | `ICognitoConnectorApi` | Conector Cognito | `COGNITO_CONNECTOR_LAMBDA_URL` |
252
+ | `ICognitoV2Api` | Cognito V2 | `COGNITO_CONNECTOR_LAMBDA_URL` |
253
+ | `ISTPAccountApi` | Cuentas STP | `STP_ACCOUNT_LAMBDA_URL` |
254
+
255
+ ---
256
+
257
+ ## Publishers (Colas SQS)
258
+
259
+ Para comunicación asíncrona, la librería provee publishers que envían mensajes a colas SQS:
260
+
261
+ | Interface | Descripción | Variable de Entorno (Queue) |
262
+ |-----------|-------------|----------------------------|
263
+ | `INotificationMessagesPublisher` | Notificaciones push/email/sms | `NOTIFICATION_MESSAGES_QUEUE` |
264
+ | `INotificationWSMessagesPublisher` | Notificaciones WebSocket | `NOTIFICATION_WS_QUEUE` |
265
+ | `ISessionActivityPublisher` | Actividad de sesión | `SESSION_ACTIVITY_QUEUE` |
266
+ | `ITransactionPublisher` | Eventos de transacción | `TRANSACTION_QUEUE` |
267
+ | `IActivityPublisher` | Eventos de actividad | `ACTIVITY_QUEUE` |
268
+ | `ITransactionAlarmPublisher` | Alarmas de transacción | `TRANSACTION_ALARM_QUEUE` |
269
+ | `IPublisher` | Publisher genérico | Configurable |
270
+
271
+ ### Ejemplo de Publisher
272
+
273
+ ```typescript
274
+ import { inject, injectable } from "inversify";
275
+ import { INotificationMessagesPublisher } from "@fiado/api-invoker";
276
+ import { NotificationQueueMessageRequest } from "@fiado/type-kit";
277
+
278
+ @injectable()
279
+ export class NotificationService {
280
+ constructor(
281
+ @inject("INotificationMessagesPublisher")
282
+ private notificationPublisher: INotificationMessagesPublisher
283
+ ) {}
284
+
285
+ async sendPushNotification(userId: string, message: string): Promise<void> {
286
+ const notification: NotificationQueueMessageRequest = {
287
+ userId,
288
+ type: "PUSH",
289
+ message,
290
+ timestamp: new Date().toISOString()
291
+ };
292
+
293
+ await this.notificationPublisher.publish(notification);
294
+ }
295
+ }
296
+ ```
297
+
298
+ ---
299
+
300
+ ## Uso en Proyectos
301
+
302
+ ### Ejemplo: Consultar Directorio
42
303
 
43
304
  ```typescript
44
305
  import { inject, injectable } from "inversify";
45
- import { IDirectoryApi } from "fiado-api-invoker";
306
+ import { IDirectoryApi } from "@fiado/api-invoker";
46
307
  import { log } from "@fiado/logger";
47
308
 
48
309
  @injectable()
49
- export class SomeService {
50
- constructor(@inject("IDirectoryApi") private directoryApi: IDirectoryApi) {}
310
+ export class UserService {
311
+ constructor(
312
+ @inject("IDirectoryApi") private directoryApi: IDirectoryApi
313
+ ) {}
51
314
 
52
- public async fetchDirectoryDetails(directoryIds: string[]): Promise<void> {
315
+ async getUsersByIds(directoryIds: string[]): Promise<any[]> {
53
316
  try {
54
- const details = await this.directoryApi.getByIds(directoryIds);
55
- log.info(details);
56
-
317
+ const response = await this.directoryApi.getByIds(directoryIds);
318
+ log.info("Directories fetched successfully", { count: response.length });
319
+ return response;
57
320
  } catch (error) {
58
- log.error("Error fetching directory details:", error);
321
+ log.error("Error fetching directories", error);
322
+ throw error;
59
323
  }
60
324
  }
325
+
326
+ async getUserByPhone(phoneNumber: string): Promise<any> {
327
+ return await this.directoryApi.getByPhoneNumber(phoneNumber);
328
+ }
329
+ }
330
+ ```
331
+
332
+ ### Ejemplo: Procesar Transacción
333
+
334
+ ```typescript
335
+ import { inject, injectable } from "inversify";
336
+ import { ITransactionApi, ITransactionPublisher } from "@fiado/api-invoker";
337
+
338
+ @injectable()
339
+ export class PaymentManager {
340
+ constructor(
341
+ @inject("ITransactionApi") private transactionApi: ITransactionApi,
342
+ @inject("ITransactionPublisher") private transactionPublisher: ITransactionPublisher
343
+ ) {}
344
+
345
+ async processPayment(paymentData: any): Promise<void> {
346
+ // 1. Crear transacción via API síncrona
347
+ const transaction = await this.transactionApi.create(paymentData);
348
+
349
+ // 2. Publicar evento para procesamiento asíncrono
350
+ await this.transactionPublisher.publish({
351
+ transactionId: transaction.id,
352
+ event: "PAYMENT_INITIATED",
353
+ timestamp: new Date().toISOString()
354
+ });
355
+ }
356
+ }
357
+ ```
358
+
359
+ ### Ejemplo: Verificación de Identidad
360
+
361
+ ```typescript
362
+ import { inject, injectable } from "inversify";
363
+ import { IIdentityApi, IRiskProfileApi } from "@fiado/api-invoker";
364
+
365
+ @injectable()
366
+ export class KYCService {
367
+ constructor(
368
+ @inject("IIdentityApi") private identityApi: IIdentityApi,
369
+ @inject("IRiskProfileApi") private riskProfileApi: IRiskProfileApi
370
+ ) {}
371
+
372
+ async verifyUser(directoryId: string, documents: any): Promise<boolean> {
373
+ // Verificar identidad
374
+ const identityResult = await this.identityApi.verify(directoryId, documents);
375
+
376
+ // Evaluar perfil de riesgo
377
+ const riskProfile = await this.riskProfileApi.evaluate(directoryId);
378
+
379
+ return identityResult.verified && riskProfile.score < 0.5;
380
+ }
61
381
  }
62
382
  ```
63
383
 
384
+ ---
385
+
386
+ ## Variables de Entorno
387
+
388
+ Cada cliente API requiere una variable de entorno con la URL base del Lambda destino. El formato estándar es:
389
+
390
+ ```
391
+ {SERVICE_NAME}_LAMBDA_URL=https://{api-id}.execute-api.{region}.amazonaws.com/v1/
392
+ ```
393
+
394
+ ### Configuración en template.yml
395
+
396
+ ```yaml
397
+ Environment:
398
+ Variables:
399
+ DIRECTORY_LAMBDA_URL: !Sub "{{resolve:ssm:fiado-directory-lambda}}"
400
+ IDENTITY_LAMBDA_URL: !Sub "{{resolve:ssm:fiado-identity-lambda}}"
401
+ TRANSACTION_LAMBDA_URL: !Sub "{{resolve:ssm:fiado-transaction-lambda}}"
402
+ # ... otras URLs
403
+
404
+ # Colas SQS
405
+ NOTIFICATION_MESSAGES_QUEUE: !ImportValue SqsNotificationMessagesQueueUrl
406
+ SESSION_ACTIVITY_QUEUE: !ImportValue SqsSessionActivityQueueUrl
407
+ ```
408
+
409
+ ### Resolución de URLs
410
+
411
+ Las URLs se almacenan en **SSM Parameter Store** y se resuelven en tiempo de despliegue. El pipeline de CI/CD registra automáticamente la URL de cada Lambda después del deploy.
412
+
413
+ ---
414
+
415
+ ## Estructura del Proyecto
416
+
417
+ ```
418
+ src/
419
+ ├── index.ts # Exportaciones públicas
420
+ ├── container.config.ts # ContainerModule con todos los bindings
421
+ ├── utils/ # Utilidades compartidas
422
+ │ └── InvokerUtils.ts
423
+
424
+ ├── directory/ # Ejemplo de estructura de módulo
425
+ │ ├── index.ts # Re-exportaciones del módulo
426
+ │ ├── DirectoryApi.ts # Implementación del cliente
427
+ │ └── interfaces/
428
+ │ └── IDirectoryApi.ts # Interface del cliente
429
+
430
+ ├── transaction/ # Módulo con API y Publisher
431
+ │ ├── index.ts
432
+ │ ├── api/
433
+ │ │ ├── TransactionApi.ts
434
+ │ │ └── ITransactionApi.ts
435
+ │ └── queue/
436
+ │ ├── TransactionPublisher.ts
437
+ │ └── ITransactionPublisher.ts
438
+
439
+ ├── notificationMessages/ # Módulo solo Publisher
440
+ │ ├── index.ts
441
+ │ └── queue/
442
+ │ ├── NotificationMessagePublisher.ts
443
+ │ └── interfaces/
444
+ │ └── INotificationMessagesPublisher.ts
445
+
446
+ └── [60+ módulos adicionales...]
447
+ ```
448
+
449
+ ### Estructura de un Módulo API
450
+
451
+ ```
452
+ {service-name}/
453
+ ├── index.ts # export * from './interfaces/I{Service}Api';
454
+ │ # export * from './{Service}Api';
455
+ ├── {Service}Api.ts # Implementación @injectable()
456
+ └── interfaces/
457
+ └── I{Service}Api.ts # Interface con JSDoc
458
+ ```
459
+
460
+ ### Estructura de un Módulo con Queue
461
+
462
+ ```
463
+ {service-name}/
464
+ ├── index.ts
465
+ ├── api/
466
+ │ ├── {Service}Api.ts
467
+ │ └── I{Service}Api.ts
468
+ └── queue/
469
+ ├── {Service}Publisher.ts
470
+ └── interfaces/
471
+ └── I{Service}Publisher.ts
472
+ ```
473
+
474
+ ---
475
+
476
+ ## Convenciones de Desarrollo
477
+
478
+ ### Nomenclatura
479
+
480
+ | Elemento | Patrón | Ejemplo |
481
+ |----------|--------|---------|
482
+ | **Carpeta de módulo** | `kebab-case` | `account-fiadoinc/` |
483
+ | **Interface API** | `I{Service}Api` | `IDirectoryApi` |
484
+ | **Implementación API** | `{Service}Api` | `DirectoryApi` |
485
+ | **Interface Publisher** | `I{Service}Publisher` | `ITransactionPublisher` |
486
+ | **Implementación Publisher** | `{Service}Publisher` | `TransactionPublisher` |
487
+
488
+ ### Patrón de Implementación API
489
+
490
+ ```typescript
491
+ import dotenv from 'dotenv';
492
+ import { inject, injectable } from "inversify";
493
+ import { IHttpRequest } from "@fiado/http-client";
494
+ import { I{Service}Api } from "./interfaces/I{Service}Api";
495
+ dotenv.config();
496
+
497
+ @injectable()
498
+ export class {Service}Api implements I{Service}Api {
499
+
500
+ private readonly baseUrl = process.env.{SERVICE}_LAMBDA_URL || "";
501
+
502
+ constructor(
503
+ @inject("IHttpRequest") private httpRequest: IHttpRequest
504
+ ) {}
505
+
506
+ public async getById(id: string): Promise<any> {
507
+ const url = `${this.baseUrl}?id=${id}`;
508
+ const operationName = "getById";
509
+
510
+ return await this.httpRequest.get(url, null, {
511
+ 'operationName': operationName
512
+ });
513
+ }
514
+ }
515
+ ```
516
+
517
+ ### Patrón de Implementación Publisher
518
+
519
+ ```typescript
520
+ import { SendMessageCommand, SQSClient } from "@aws-sdk/client-sqs";
521
+ import { inject, injectable } from "inversify";
522
+ import { I{Service}Publisher } from "./interfaces/I{Service}Publisher";
523
+
524
+ @injectable()
525
+ export class {Service}Publisher implements I{Service}Publisher {
526
+
527
+ private readonly queueUrl = process.env.{SERVICE}_QUEUE;
528
+
529
+ async publish(message: any): Promise<void> {
530
+ const client = new SQSClient();
531
+ const command = new SendMessageCommand({
532
+ QueueUrl: this.queueUrl,
533
+ MessageBody: JSON.stringify(message)
534
+ });
535
+ await client.send(command);
536
+ }
537
+ }
538
+ ```
539
+
540
+ ### Header operationName
541
+
542
+ Todas las llamadas HTTP incluyen el header `operationName` que permite:
543
+ - Trazabilidad en logs
544
+ - Métricas por operación
545
+ - Debugging en X-Ray
546
+
547
+ ---
548
+
549
+ ## Dependencias
550
+
551
+ ### Runtime
552
+
553
+ | Dependencia | Versión | Propósito |
554
+ |-------------|---------|-----------|
555
+ | `@aws-sdk/client-sqs` | ^3.919.0 | Cliente SQS para publishers |
556
+ | `@fiado/gateway-adapter` | ^1.1.50 | Tipos de respuesta API |
557
+ | `@fiado/http-client` | ^1.0.7 | Cliente HTTP base |
558
+ | `@fiado/logger` | ^1.0.3 | Logging estructurado |
559
+ | `@fiado/type-kit` | ^2.1.28 | DTOs y tipos compartidos |
560
+ | `inversify` | ^6.2.2 | Inyección de dependencias |
561
+ | `reflect-metadata` | ^0.2.2 | Metadatos para decoradores |
562
+ | `dotenv` | ^16.4.7 | Variables de entorno |
563
+
564
+ ### Desarrollo
565
+
566
+ | Dependencia | Versión | Propósito |
567
+ |-------------|---------|-----------|
568
+ | `@types/node` | ^20.17.24 | Tipos de Node.js |
569
+ | `typescript` | (peer) | Compilador TypeScript |
570
+
571
+ ---
572
+
573
+ ## Compilación y Publicación
574
+
575
+ ### Build
576
+
577
+ ```bash
578
+ npm run build
579
+ ```
580
+
581
+ Genera archivos `.js` y `.d.ts` en el directorio `bin/`.
582
+
583
+ ### Publicación
584
+
585
+ ```bash
586
+ npm version patch|minor|major
587
+ npm publish
588
+ ```
589
+
590
+ La librería se publica en el registry npm privado de Fiado configurado en `.npmrc`.
591
+
592
+ ---
593
+
594
+ <div align="center">
595
+
596
+ **Fiado Inc.** | @fiado/api-invoker v1.5.34
597
+
598
+ </div>
599
+
64
600
 
@@ -69,7 +69,7 @@ let PomeloApi = class PomeloApi {
69
69
  return await this.httpRequest.post(url, request);
70
70
  }
71
71
  async getUserToken(externalUserId) {
72
- const url = `${this.baseUrl}cards/user/token/${externalUserId}`;
72
+ const url = `${this.baseUrl}user/token/${externalUserId}`;
73
73
  return await this.httpRequest.get(url);
74
74
  }
75
75
  // //Shipping
@@ -6,6 +6,12 @@ export default class StpServicePaymentApi implements IStpServicePaymentApi {
6
6
  private httpRequest;
7
7
  private readonly baseUrl;
8
8
  constructor(httpRequest: IHttpRequest);
9
+ getSTPTransactionDownload(params: {
10
+ date: string;
11
+ index?: string;
12
+ pageSize?: number;
13
+ sort?: string;
14
+ }): Promise<ApiGatewayResponse<any>>;
9
15
  pay(request: ServicePaymentRequest): Promise<ApiGatewayResponse<any>>;
10
16
  getTransaction(transactionNumber: string): Promise<ApiGatewayResponse<any>>;
11
17
  getById(id: string): Promise<ApiGatewayResponse<any>>;
@@ -18,6 +18,10 @@ let StpServicePaymentApi = class StpServicePaymentApi {
18
18
  this.httpRequest = httpRequest;
19
19
  this.baseUrl = process.env.STP_SERVICE_PAY_LAMBDA_URL || "";
20
20
  }
21
+ async getSTPTransactionDownload(params) {
22
+ const url = `${this.baseUrl}transaction-download`;
23
+ return await this.httpRequest.get(url);
24
+ }
21
25
  async pay(request) {
22
26
  const url = `${this.baseUrl}/pay`;
23
27
  return await this.httpRequest.post(url, request);
@@ -5,5 +5,11 @@ export interface IStpServicePaymentApi {
5
5
  getTransaction(transactionNumber: string): Promise<ApiGatewayResponse<any>>;
6
6
  getPaymentValidation(transactionNumber: string): Promise<ApiGatewayResponse<any>>;
7
7
  getCatalog(params: GetCatalogParams): Promise<ApiGatewayResponse<any>>;
8
- getById(id: string): any;
8
+ getById(id: string): Promise<ApiGatewayResponse<any>>;
9
+ getSTPTransactionDownload(params: {
10
+ date: string;
11
+ index?: string;
12
+ pageSize?: number;
13
+ sort?: string;
14
+ }): Promise<ApiGatewayResponse<any>>;
9
15
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fiado/api-invoker",
3
- "version": "1.5.33",
3
+ "version": "1.5.35",
4
4
  "description": "Sirve como un puente entre diferentes funciones lambda, facilitando la comunicación entre ellas a través de invocaciones http",
5
5
  "main": "bin/index.js",
6
6
  "types": "bin/index.d.ts",
@@ -76,7 +76,7 @@ export default class PomeloApi implements IPomeloApi {
76
76
  }
77
77
 
78
78
  public async getUserToken(externalUserId:string): Promise<any> {
79
- const url: string = `${this.baseUrl}cards/user/token/${externalUserId}`;
79
+ const url: string = `${this.baseUrl}user/token/${externalUserId}`;
80
80
  return await this.httpRequest.get(url);
81
81
  }
82
82
 
@@ -10,6 +10,10 @@ export default class StpServicePaymentApi implements IStpServicePaymentApi {
10
10
 
11
11
  constructor(@inject("IHttpRequest") private httpRequest: IHttpRequest) {
12
12
  }
13
+ async getSTPTransactionDownload(params: { date: string; index?: string; pageSize?: number; sort?: string; }): Promise<ApiGatewayResponse<any>> {
14
+ const url= `${this.baseUrl}transaction-download`;
15
+ return await this.httpRequest.get(url);
16
+ }
13
17
 
14
18
  async pay(request: ServicePaymentRequest): Promise<ApiGatewayResponse<any>> {
15
19
  const url = `${this.baseUrl}/pay`;
@@ -10,5 +10,7 @@ export interface IStpServicePaymentApi {
10
10
 
11
11
  getCatalog(params: GetCatalogParams): Promise<ApiGatewayResponse<any>>;
12
12
 
13
- getById(id: string)
13
+ getById(id: string): Promise<ApiGatewayResponse<any>>;
14
+
15
+ getSTPTransactionDownload(params: {date: string,index?:string,pageSize?:number, sort?:string}): Promise<ApiGatewayResponse<any>>;
14
16
  }