康特尼多斯塔布拉
- 取消常规
- 阿基特克图拉
- 伊斯塔拉西翁
- 配置
- GatewayAdapter - 路由器特等
- API 网关
- 科拉斯SQS语Name
- 事件桥
- 装饰
- Sistema de Respuestas 总统府
- 编剧JWE
- 普罗耶克托岛
- 依赖性
取消常规
@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 探测出一个自动调试器:
- API 网关页:1
event.httpMethod已存在 - 质量页:1
event.Records[0].eventSource === 'aws:sqs' - 事件桥页: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 (法语)
- 客户端 envia 信头
x-session-key(JWE con lave publica RSA) Con Cession 密钥编码 - Lambda descifra 关键usando lave privada de secrets 管理器
- 复苏a
datase encripta con AES-256-GCM usando 会话密钥 - 客户端 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 (中文(简体) )