@fiado/gateway-adapter

中文文档
3.16.0发布于 2026/11/11ISCTypeScriptES Module近 30 天下载 2622

AWS Lambda 和 API Gateways, sqs y Evention Bridge 互联网档案馆的存檔,存档日期2013-12-20

中文使用文档
文档目录48 节
  1. Lambda微型服务中心
  2. 康特尼多斯塔布拉
  3. 取消常规
  4. 提案
  5. 阿基特克图拉
  6. 事件预防基金会
  7. 伊斯塔拉西翁
  8. 同伴依赖关系
  9. 配置
  10. IoC连接器上的Registro
  11. 兰姆达入境点
  12. GatewayAdapter - 路由器特等
  13. 索波特多斯事件
  14. 乌苏
  15. API 网关
  16. ApiGateway 请求
  17. 控制者
  18. 控制者协会
  19. 托肯服务
  20. 科拉斯SQS语Name
  21. 用户
  22. 订户执行
  23. 新闻推文
  24. 事件桥
  25. IEvent BridgeMessage 用户
  26. 订户执行
  27. 装饰
  28. @ 认证 特征
  29. 特性 Enum
  30. 结束点
  31. Http 方法学 Enum
  32. 安全类型 Enum
  33. Sistema de Respuestas 总统府
  34. 回复
  35. 重建区
  36. 备选反应
  37. 编剧JWE
  38. Jwe 催化服务
  39. 配置
  40. Flujo de Encriptacion (法语)
  41. Uso 自动
  42. 普罗耶克托岛
  43. 依赖性
  44. 运行时间
  45. 发展
  46. 合作与公众
  47. 构建
  48. 公众

Fiado 网关适配器

Lambda微型服务中心

npm TypeScript AWS Lambda InversifyJS


康特尼多斯塔布拉


取消常规

@fiado/gateway-adapter 对啦 自由核心 生态科学 Fiado que actua como (法语) 路由器中心 (原始内容存档于2018-10-21) (英语). para todos los eventos que rebebe un a funcion Lambda. 支持者:

  • 自动操作 aPI 网关, SQS y EventBridge
  • 请求/答复转换 交锋
  • 自治省 装饰和特征
  • 代号: JWT 认知
  • (原始内容存档于2018-10-21) (英语). Respuestas HTTP estandarizadas cORS 配置图
  • 编剧JWE 理智的理性观点
  • 活动登记 自动

提案

En el modelo desarrollo Fiado, cada Lambda rebebes multies tipos de eventos: 维基语录链接:名人名言 - 文学作品 - 谚语 - 谚语 - 谚语

  • API 网关: Peticiones HTTP(公共、私营、后台)
  • 质量: Mensajes de colas para procesamiento asincrono (英语:
  • 事件桥: 服务活动

自由主义 曼尼霍岛 (原始内容存档于2019-09-21). de todos estos eventos en unico punto de entrada.


阿基特克图拉

                              LAMBDA HANDLER
                                index.ts
                                   |
                                   v
                          +---------------+
                          | GatewayAdapter | <-- Router Principal
                          +-------+-------+
                                  |
              +-------------------+-------------------+
              v                   v                   v
     +-----------------+ +-----------------+ +-----------------+
     |ApiGatewayAdapter| |QueueGatewayAdapter| |EventBridgeAdapter|
     +--------+--------+ +--------+--------+ +--------+--------+
              |                   |                   |
              v                   v                   v
     +-----------------+ +-----------------+ +-----------------+
     |   Controllers   | | SQS Subscriber  | |  EB Subscriber  |
     | Public/Private/ | |IMessageSubscriber| |IEventBridgeSub |
     |   Backoffice    | |                 | |                 |
     +-----------------+ +-----------------+ +-----------------+

事件预防基金会

El GatewayAdapter 探测出一个自动调试器:

  1. API 网关页:1 event.httpMethod 已存在
  2. 质量页:1 event.Records[0].eventSource === 'aws:sqs'
  3. 事件桥页:1 event.source === 'EVENT_BRIDGE'

伊斯塔拉西翁

npm install @fiado/gateway-adapter

同伴依赖关系

{
  "@fiado/logger": "^1.0.2",
  "@fiado/type-kit": "^2.1.35",
  "inversify": "^6.2.2",
  "reflect-metadata": "^0.2.2"
}

配置

IoC连接器上的Registro

import { Container } from "inversify";
import { 
    gatewayAdapterBindings, 
    TypeQueue, 
    TypeEventBridge,
    IController,
    IMessageSubscriber,
    IEventBridgeMessageSubscriber
} from "@fiado/gateway-adapter";

const container = new Container();

// Cargar bindings del gateway adapter
container.load(gatewayAdapterBindings);

// Registrar controladores del proyecto
container.bind<IController>('PublicController').to(PublicController);
container.bind<IController>('PrivateController').to(PrivateController);
container.bind<IController>('BackofficeController').to(BackofficeController);

// Registrar subscriber de SQS (si aplica)
container.bind<IMessageSubscriber<any>>("SQSMessageSubscriber").to(MySqsSubscriber);
container.bind<() => IMessageSubscriber<any>>(TypeQueue.SQSMessageSubscriberFactory)
    .toAutoFactory("SQSMessageSubscriber");

// Registrar subscriber de EventBridge (si aplica)
container.bind<IEventBridgeMessageSubscriber<any>>("EventBridgeMessageSubscriber")
    .to(MyEventBridgeSubscriber);
container.bind<() => IEventBridgeMessageSubscriber<any>>(
    TypeEventBridge.EventBridgeMessageSubscriberFactory
).toAutoFactory("EventBridgeMessageSubscriber");

export { container };

兰姆达入境点

import 'reflect-metadata';
import warmer from "lambda-warmer";
import { container } from './container.config';
import { GatewayAdapter, TypeGateway } from '@fiado/gateway-adapter';
import { log } from "@fiado/logger";

export const handler = async (event: any, context: any) => {
    
    // Soporte para lambda warming
    if (await warmer(event)) {
        return 'warmed';
    }

    log.info(`Event received: ${JSON.stringify(event)}`);

    // Obtener el router y ejecutar
    const gatewayAdapter = container.get<GatewayAdapter>(TypeGateway.GatewayAdapter);
    return await gatewayAdapter.execute(event);
}

GatewayAdapter - 路由器特等

埃尔 GatewayAdapter es el macifite central que systico de evento y lo enruta al 适配器等同体.

索波特多斯事件

提波解开适应者
API 网关event.httpMethod 已存在ApiGatewayAdapter
质量event.Records[0].eventSource === 'aws:sqs'QueueGatewayAdapter
事件桥event.source === 'EVENT_BRIDGE'EventBridgeGatewayAdapter

乌苏

import { GatewayAdapter, TypeGateway } from '@fiado/gateway-adapter';

const gatewayAdapter = container.get<GatewayAdapter>(TypeGateway.GatewayAdapter);

// El adapter detecta automaticamente el tipo de evento
const result = await gatewayAdapter.execute(event);

API 网关

ApiGateway 请求

接口尖端 que 代表了 una peticion HTTP 变形:

interface ApiGatewayRequest<TBody> {
    body: TBody | null;                                    // Body parseado
    headers: { [key: string]: string | undefined };        // Headers HTTP
    method: string;                                        // GET, POST, PUT, DELETE
    pathParameter: { [key: string]: string | undefined };  // Path params (/users/:id)
    queryStringParameters: { [key: string]: string };      // Query params (?key=value)
    multiValueQueryStringParameters: { [key: string]: string[] }; // Arrays
    token: TokenPayload | undefined | null;                // Token JWT decodificado
    operationName: string | null;                          // Nombre de la operacion
    base64EncodedFile?: string;                            // Archivos en base64
    requestContext: { identity?: { sourceIp?: string } };  // Contexto de request
}

控制者

(原始内容存档于2019-03-26) (英语). Los controladores se identifican por prefijo en el operationName数字 :

预选赛控制器乌苏
public*PublicController端点公示( Internet)
private*PrivateController终点
backoffice*BackofficeController最终管理点
agent* 编号 : agents*AgentController结束点去代理

控制者协会

import { injectable, inject } from 'inversify';
import { 
    IController, 
    ApiGatewayRequest, 
    ApiResponse,
    AuthorizedFeatures,
    Feature,
    Endpoint,
    HttpMethod,
    SecurityType
} from '@fiado/gateway-adapter';

@injectable()
export class PublicController implements IController {

    constructor(
        @inject("IUserManager") private userManager: IUserManager
    ) {}

    @AuthorizedFeatures(Feature.ANONIMUS)
    @Endpoint({
        method: HttpMethod.GET,
        path: '/users/:id',
        summary: 'Obtener usuario por ID',
        tags: ['PublicController'],
        security: SecurityType.CognitoAppAuthorizer
    })
    async getUser(request: ApiGatewayRequest<void>): Promise<any> {
        const userId = request.pathParameter?.id;
        const user = await this.userManager.getById(userId);
        return ApiResponse.success({ data: user });
    }

    @AuthorizedFeatures(Feature.ANONIMUS)
    @Endpoint({
        method: HttpMethod.POST,
        path: '/users',
        summary: 'Crear usuario',
        tags: ['PublicController'],
        security: SecurityType.CognitoAppAuthorizer
    })
    async createUser(request: ApiGatewayRequest<CreateUserDto>): Promise<any> {
        const user = await this.userManager.create(request.body);
        return ApiResponse.created({ data: user });
    }
}

托肯服务

塞维西奥·帕·德·科尼托(JWT de Cognto)的装饰品:

import { TokenService } from '@fiado/gateway-adapter';

const tokenService = new TokenService();
const payload = tokenService.decodeToken(bearerToken);

// payload contiene:
// - sub: ID del usuario
// - email: Email del usuario
// - permissions: Array de permisos/features
// - cognito:groups: Grupos de Cognito

科拉斯SQS语Name

用户

接口 processar mensajes de SQS:

export interface IMessageSubscriber<T> {
    handle(messageBody: T, receiptHandle: string): Promise<void>;
    deleteMessage(queueUrl: string, receiptHandle: string): Promise<void>;
}

订户执行

import { injectable } from 'inversify';
import { IMessageSubscriber } from '@fiado/gateway-adapter';
import { log } from '@fiado/logger';

@injectable()
export class OrderMessageSubscriber implements IMessageSubscriber<OrderMessage> {
    
    async handle(messageBody: OrderMessage, receiptHandle: string): Promise<void> {
        log.info('Processing order message', { orderId: messageBody.orderId });
        await this.processOrder(messageBody);
    }

    async deleteMessage(queueUrl: string, receiptHandle: string): Promise<void> {
        // Implementar si se necesita borrado manual
    }

    private async processOrder(order: OrderMessage): Promise<void> {
        // Logica de procesamiento
    }
}

新闻推文

SQS 公共广告界面:

export interface IMessagePublisher<T> {
    publish(messageBody: T, options?: PublishOptions): Promise<void>;
}

事件桥

IEvent BridgeMessage 用户

接口 processar 事件- de EventBridge :

import { EventBridgeMessageRequest } from "@fiado/type-kit";

export interface IEventBridgeMessageSubscriber<TPayload> {
    handle(message: EventBridgeMessageRequest<TPayload>): Promise<void>;
}

订户执行

import { injectable } from 'inversify';
import { IEventBridgeMessageSubscriber } from '@fiado/gateway-adapter';
import { EventBridgeMessageRequest } from '@fiado/type-kit';

@injectable()
export class PaymentEventSubscriber implements IEventBridgeMessageSubscriber<PaymentEvent> {
    
    async handle(message: EventBridgeMessageRequest<PaymentEvent>): Promise<void> {
        const { payload, eventType } = message;
        
        switch (eventType) {
            case 'PAYMENT_COMPLETED':
                await this.handlePaymentCompleted(payload);
                break;
            case 'PAYMENT_FAILED':
                await this.handlePaymentFailed(payload);
                break;
        }
    }
}

装饰

@ 认证 特征

装饰者 para definir que sets/permisos pueden admiters a un metodo: 装饰者 para definir que sets/permisos pueden acception a un metodo: 装饰者 设计者 设计者 设计师 设计师 设计师 设计师 设计师 设计师

import { AuthorizedFeatures, Feature } from '@fiado/gateway-adapter';

// Acceso anonimo (sin token)
@AuthorizedFeatures(Feature.ANONIMUS)
async publicEndpoint(request: ApiGatewayRequest<any>): Promise<any> { }

// Requiere feature especifico en el token
@AuthorizedFeatures(Feature.PAYROLL)
async payrollEndpoint(request: ApiGatewayRequest<any>): Promise<any> { }

// Multiples features (OR - cualquiera autoriza)
@AuthorizedFeatures(Feature.ADMIN, Feature.MANAGER)
async adminEndpoint(request: ApiGatewayRequest<any>): Promise<any> { }

特性 Enum

export enum Feature {
    ANONIMUS = "ANONIMUS",  // Acceso publico sin autenticacion
    TEST = "test",
    FEATURE1 = "feature1",
    PAYROLL = "PAYROLL"
}

结束点

端点元数据代号:

import { Endpoint, HttpMethod, SecurityType } from '@fiado/gateway-adapter';

@Endpoint({
    method: HttpMethod.POST,
    path: '/payments',
    summary: 'Procesar pago',
    tags: ['PaymentController'],
    security: SecurityType.CognitoAppAuthorizer,
    queryParams: ['currency'],
    pathParams: ['id']
})
async processPayment(request: ApiGatewayRequest<PaymentDto>): Promise<any> { }

Http 方法学 Enum

export enum HttpMethod {
    GET = 'get',
    POST = 'post',
    PUT = 'put',
    DELETE = 'delete'
}

安全类型 Enum

export enum SecurityType {
    CognitoAppAuthorizer = 'CognitoAppAuthorizer',           // Usuarios de la app
    CognitoBackofficeAuthorizer = 'CognitoBackofficeAuthorizer', // Administradores
    CognitoCombinedAuthorizer = 'CognitoCombinedAuthorizer',     // Ambos pools
    CognitoAgentAuthorizer = 'CognitoAgentAuthorizer'            // Agentes
}

Sistema de Respuestas 总统府

回复

(原始内容存档于2017-10-21) (英语). Clase estatica para construitur respuestas HTTP estandarizadas:

import { ApiResponse } from '@fiado/gateway-adapter';

// 200 OK
return ApiResponse.success({ data: result, msg: 'Operacion exitosa' });

// 201 Created
return ApiResponse.created({ data: newResource });

// 400 Bad Request
return ApiResponse.badRequest({ code: 'VALIDATION_ERROR', msg: 'Campo requerido' });

// 401 Unauthorized
return ApiResponse.unauthorized({ msg: 'Token invalido' });

// 403 Forbidden
return ApiResponse.forbidden({ msg: 'Acceso denegado' });

// 404 Not Found
return ApiResponse.notFound({ msg: 'Recurso no encontrado' });

// 425 Too Early
return ApiResponse.tooEarly({ msg: 'Intente mas tarde' });

// 500 Internal Server Error
return ApiResponse.internalServerError({ msg: 'Error interno' });

// 302 Redirect
return ApiResponse.redirect({ data: { url: 'https://...' } });

// Redireccion real con header Location
return ApiResponse.redirectTo('https://example.com/callback', 302);

重建区

Todas las repuestas siguen el formato estandar: 互联网档案馆的存檔,存档日期2014-12-21

{
    statusCode: 200,
    headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Headers": "*",
        "Access-Control-Allow-Methods": "*",
        "Content-Type": "application/json"
    },
    body: {
        code: "PROCESS_OK",      // Codigo de respuesta
        date: "2024-01-15T...",  // Timestamp ISO
        data: { ... },           // Datos de respuesta
        description: null,       // Descripcion opcional
        msg: null,               // Mensaje opcional
        encrypted: false         // Flag de encriptacion (opcional)
    }
}

备选反应

interface ResponseOptions<T> {
    data?: T;              // Datos a retornar
    code?: string;         // Codigo personalizado
    msg?: string;          // Mensaje
    description?: string;  // Descripcion
    encrypted?: boolean;   // Flag de encriptacion
}

编剧JWE

Jwe 催化服务

JSON网络加密:

配置

学习能力变量:

Environment:
  Variables:
    # Encriptar TODOS los endpoints de app
    JWE_ENCRYPTION_APP: "true"
    
    # O encriptar endpoints especificos
    JWE_ENCRYPTION_APP_ENDPOINTS: "publicGetBalance,publicGetTransactions"
    
    # Para backoffice
    JWE_ENCRYPTION_BACKOFFICE: "true"
    JWE_ENCRYPTION_BACKOFFICE_ENDPOINTS: "backofficeGetUserData"

Flujo de Encriptacion (法语)

  1. 客户端 envia 信头 x-session-key (JWE con lave publica RSA) Con Cession 密钥编码
  2. Lambda descifra 关键usando lave privada de secrets 管理器
  3. 复苏a data se encripta con AES-256-GCM usando 会话密钥
  4. 客户端 descifra respuesta con su 会话密钥

Uso 自动

自动调试:

  • 阿尔端点 esta configurado par encriptar 语句
  • 客户端 envia el 信头 x-session-key
  • El servicio puede inficializarse 正确和解
// La respuesta se encripta automaticamente
return ApiResponse.success({ data: sensitiveData });

// Respuesta encriptada:
{
    code: "PROCESS_OK",
    data: "eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0...",  // JWE
    encrypted: true
}

普罗耶克托岛

src/
├── index.ts                    # Exportaciones publicas
├── container.config.ts         # ContainerModule con bindings
├── GatewayAdapter.ts           # Router principal
│
├── apigateway/                 # Modulo API Gateway
│   ├── abstractions/
│   │   ├── ApiGatewayRequest.ts
│   │   ├── ApiGatewayResponse.ts
│   │   ├── FeatureEnum.ts
│   │   ├── IController.ts
│   │   ├── ResponseOptions.ts
│   │   ├── StandardResponse.ts
│   │   └── TypeGateway.ts
│   ├── decorators/
│   │   └── AuthorizedFeatures.ts
│   └── services/
│       ├── ActivitySessionService.ts
│       ├── ApiGatewayAdapter.ts
│       ├── ApiResponse.ts
│       ├── JweEncryptionService.ts
│       └── TokenService.ts
│
├── queue/                      # Modulo SQS
│   ├── abstractions/
│   │   ├── IMessagePublisher.ts
│   │   ├── IMessageSubscriber.ts
│   │   ├── IPublishOptions.ts
│   │   └── TypeQueue.ts
│   ├── decorators/
│   └── services/
│       └── QueueGatewayAdapter.ts
│
├── eventBridge/                # Modulo EventBridge
│   ├── abstractions/
│   │   ├── IEventBridgeMessageSubscriber.ts
│   │   └── TypeEventBridge.ts
│   └── service/
│       └── EventBridgeGatewayAdapter.ts
│
└── endpoint/                   # Decorador @Endpoint
    └── endpointDecorator.ts

依赖性

运行时间

依赖性版本提案
@fiado/api-invoker^1.4.6 (中文(简体) )Invocacion de APIs internas (英语:Invocacion de APIs internas) 互联网档案馆的存檔,存档日期2014-12-02
@fiado/logger^1.0.2 (中文(简体) )记录构造
@fiado/type-kit^ 2.1.35 (韩语)DTOs 和 Tipos 堆肥
aws-lambda^1.0.7 (中文(简体) )Tipos de AWS Lambda 兰克达
inversify^ 6.2.2依附地
jose^ 4.15.5 (韩语)编剧JWE
jsonwebtoken^ 9.0.2 (韩语)JWT 解码器
reflect-metadata^ 0.2.2 (中文(简体) )元代装饰
uuid(单位:千美元)乌干达民主联盟

发展

依赖性版本提案
@types/jsonwebtoken(单位:千美元)Tipos de jsonwebtoken (英语)

合作与公众

构建

npm run build

热那拉群岛 .js 尔 .d.ts 导演 bin/。 。 。 .

公众

npm version patch|minor|major
npm publish

菲亚多公司. @fiado/gateway-adapterv 1.1.59 (中文(简体) )

` , `

版本与发布记录

@fiado/gateway-adapter 共发布 116 个版本,首次发布于 2024/03/22;过去 12 个月发布了 35 个版本。

版本发布日期距今
3.16.0latest2026/11/113 天前
3.15.02026/11/059 天前
3.14.02026/10/031 个月前
3.13.02026/09/251 个月前
3.12.02026/08/113 个月前
3.11.12026/07/283 个月前

其他发布通道:legacy-v6 → 1.1.60。

关于 @fiado/gateway-adapter 的常见问题

@fiado/gateway-adapter 是什么?

AWS Lambda 和 API Gateways, sqs y Evention Bridge 互联网档案馆的存檔,存档日期2013-12-20

如何安装 @fiado/gateway-adapter?

在项目目录运行 npm install @fiado/gateway-adapter,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:inversify(^8.0.0)、reflect-metadata(^0.2.2)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@fiado/gateway-adapter 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@fiado/gateway-adapter 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@fiado/gateway-adapter 可以商用吗?

@fiado/gateway-adapter 使用 ISC 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@fiado/gateway-adapter 的下载量有多少?

根据 npm 官方下载统计,@fiado/gateway-adapter 在 2026/10/15 – 2026/11/13 这 30 天内被下载 2,622 次,日均约 87 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@fiado/gateway-adapter 还在维护吗?

最新版本 3.16.0 发布于 2026/11/11(3 天前);至今共发布 116 个版本,其中过去 12 个月发布了 35 个;首次发布于 2024/03/22。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。