@geekmidas/ 构造
一个构建类型安全HTTP端点,云功能,计划任务,以及事件订阅器的综合框架,具备了全面的TypeScript支持和AWS Lambda部署能力.
特征
- 类型安全终点: 以完全类型推论构建 HTTP 端点
- 云函数: 创建无服务器功能并进行计划验证
- 计划任务: 用类型安全处理器定义 cron 任务
- 事件订阅者: 处理结构化消息的事件
- 服务发现: 内置依赖性注射系统
- 多个适配器: AWS Lambda, API Gateway (v1/v2) 和 Hono 支持
- 标准计划验证: 与Zod、Valibot和其他验证图书馆合作
- 事件出版: 从任意构造中综合事件发布
- 审计日志: 具有自动回滚支持的交易意识审计系统
- 限制费率: 使用可配置储存限制内置率
- OpenAPI 集成: 从端点生成 OpenAPI 规格
安装
pnpm add @geekmidas/constructs
软件包导出
// Endpoints
import { e, EndpointBuilder } from '@geekmidas/constructs/endpoints';
// Functions
import { f, FunctionBuilder } from '@geekmidas/constructs/functions';
// Crons
import { cron, CronBuilder } from '@geekmidas/constructs/crons';
// Subscribers
import { SubscriberBuilder } from '@geekmidas/constructs/subscribers';
快速启动
HTTP 终点
以流畅的构建器模式创建类型安全 HTTP 端点 :
import { e } from '@geekmidas/constructs/endpoints';
import { z } from 'zod';
// Simple GET endpoint
export const getUsers = e
.get('/users')
.output(z.array(z.object({
id: z.string(),
name: z.string(),
email: z.string().email()
})))
.handle(async () => {
return [
{ id: '1', name: 'John Doe', email: '[email protected]' }
];
});
// POST endpoint with body validation
export const createUser = e
.post('/users')
.body(z.object({
name: z.string().min(1),
email: z.string().email()
}))
.output(z.object({
id: z.string(),
name: z.string(),
email: z.string()
}))
.handle(async ({ body }) => {
// body is fully typed as { name: string; email: string }
return {
id: crypto.randomUUID(),
name: body.name,
email: body.email
};
});
// Endpoint with query parameters
export const searchUsers = e
.get('/users/search')
.query(z.object({
q: z.string(),
limit: z.coerce.number().default(10)
}))
.output(z.array(z.object({
id: z.string(),
name: z.string()
})))
.handle(async ({ query }) => {
// query is typed as { q: string; limit: number }
return [];
});
云函数
以输入/输出验证创建无服务器功能 :
import { f } from '@geekmidas/constructs/functions';
import { z } from 'zod';
export const processOrder = f
.input(z.object({
orderId: z.string(),
items: z.array(z.object({
id: z.string(),
quantity: z.number().int().positive()
}))
}))
.output(z.object({
orderId: z.string(),
status: z.enum(['processing', 'completed', 'failed']),
processedAt: z.string().datetime()
}))
.timeout(300000) // 5 minutes
.handle(async ({ input, logger }) => {
logger.info(`Processing order ${input.orderId}`);
// Process order logic
for (const item of input.items) {
logger.info(`Processing item ${item.id}, quantity: ${item.quantity}`);
}
return {
orderId: input.orderId,
status: 'completed',
processedAt: new Date().toISOString()
};
});
计划任务( Crons)
定义带有时间表的 cron 工作 :
import { cron } from '@geekmidas/constructs/crons';
// Daily report at 9 AM UTC
export const dailyReport = cron
.schedule('cron(0 9 * * ? *)')
.timeout(600000) // 10 minutes
.handle(async ({ logger }) => {
logger.info('Generating daily report');
const reportDate = new Date().toISOString().split('T')[0];
const reportData = {
date: reportDate,
totalOrders: 150,
totalRevenue: 12500.00
};
logger.info('Daily report generated', reportData);
return reportData;
});
// Hourly cleanup
export const hourlyCleanup = cron
.schedule('cron(0 * * * *)')
.timeout(300000) // 5 minutes
.handle(async ({ logger }) => {
logger.info('Running hourly cleanup');
const itemsCleaned = 42;
logger.info(`Cleaned ${itemsCleaned} items`);
return { itemsCleaned };
});
事件订阅者
处理类型安全消息的事件 :
import { SubscriberBuilder } from '@geekmidas/constructs/subscribers';
import { z } from 'zod';
export const userEventsSubscriber = new SubscriberBuilder()
.subscribe(['user.created', 'user.updated', 'user.deleted'])
.timeout(30000)
.output(z.object({
processed: z.number(),
success: z.boolean()
}))
.handle(async ({ events, logger }) => {
logger.info(
{ eventCount: events.length },
'Processing user events'
);
for (const event of events) {
try {
switch (event.type) {
case 'user.created':
logger.info({ userId: event.data.userId }, 'User created');
break;
case 'user.updated':
logger.info({ userId: event.data.userId }, 'User updated');
break;
case 'user.deleted':
logger.info({ userId: event.data.userId }, 'User deleted');
break;
}
} catch (error) {
logger.error({ error, event }, 'Failed to process event');
throw error;
}
}
return {
processed: events.length,
success: true
};
});
高级特性
安保计划
为您的 API 定义 OpenAPI 安全方案。 这些用于: @geekmidas/cli 在客户端中生成类型安全认证.
内设安保计划
下列授权方名称自动映射到 OpenAPI 安全方案 :
| 授权者 | 安保计划 |
|---|---|
jwt | { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' } |
bearer | { type: 'http', scheme: 'bearer' } |
apiKey | { type: 'apiKey', in: 'header', name: 'X-API-Key' } |
oauth2 | { type: 'oauth2', flows: {} } |
oidc | { type: 'openIdConnect', openIdConnectUrl: '' } |
iam | { type: 'apiKey', in: 'header', name: 'Authorization' } (AWS SigV4号) |
import { e } from '@geekmidas/constructs/endpoints';
// Using built-in 'jwt' scheme
export const getUsers = e
.get('/users')
.authorizer('jwt') // Automatically uses JWT security scheme
.handle(async ({ session }) => {
// session contains JWT claims
return [];
});
自定义安全方案
对于自定义认证方法, 使用 .securitySchemes() 终点事实 :
import { EndpointFactory } from '@geekmidas/constructs/endpoints';
const api = new EndpointFactory()
.securitySchemes({
// Custom OAuth2 with specific flows
oauth2: {
type: 'oauth2',
flows: {
authorizationCode: {
authorizationUrl: 'https://auth.example.com/authorize',
tokenUrl: 'https://auth.example.com/token',
scopes: {
'read:users': 'Read user data',
'write:users': 'Modify user data',
},
},
},
},
// Custom API key in query parameter
queryApiKey: {
type: 'apiKey',
in: 'query',
name: 'api_key',
},
});
// Use custom security scheme
export const getUsers = api
.get('/users')
.authorizer('oauth2')
.handle(async () => []);
默认授权器
设置工厂所有端点的默认授权符 :
const api = new EndpointFactory()
.authorizer('jwt'); // All endpoints inherit this authorizer
// Protected by default
export const getProfile = api
.get('/profile')
.handle(async ({ session }) => {
return { userId: session.claims.sub };
});
// Override to make public
export const getHealth = api
.get('/health')
.authorizer('none') // Explicitly public
.handle(async () => ({ status: 'ok' }));
服务发现
向您的构造注入服务 :
import { e } from '@geekmidas/constructs/endpoints';
import type { Service } from '@geekmidas/services';
import type { EnvironmentParser } from '@geekmidas/envkit';
import { Kysely } from 'kysely';
import { z } from 'zod';
// Define a database service
const databaseService = {
serviceName: 'database' as const,
async register(envParser: EnvironmentParser<{}>) {
const config = envParser.create((get) => ({
url: get('DATABASE_URL').string()
})).parse();
const db = new Kysely({ /* config */ });
return db;
}
} satisfies Service<'database', Kysely<Database>>;
// Use service in endpoint
export const getUserFromDb = e
.get('/users/:id')
.params(z.object({ id: z.string() }))
.services([databaseService])
.handle(async ({ params, services }) => {
// services.database is fully typed
const user = await services.database
.selectFrom('users')
.where('id', '=', params.id)
.selectAll()
.executeTakeFirst();
return user;
});
事件出版
从任意构造发布事件 :
import { e } from '@geekmidas/constructs/endpoints';
import type { Service } from '@geekmidas/services';
import type { EventPublisher, PublishableMessage } from '@geekmidas/events';
import { z } from 'zod';
// Define event types
type UserEvents =
| PublishableMessage<'user.created', { userId: string; email: string }>
| PublishableMessage<'user.updated', { userId: string }>;
// Create event publisher service
const userEventPublisher = {
serviceName: 'userEventPublisher' as const,
async register(envParser: EnvironmentParser<{}>) {
const config = envParser.create((get) => ({
publisherUrl: get('EVENT_PUBLISHER_URL').string()
})).parse();
const { Publisher } = await import('@geekmidas/events');
return Publisher.fromConnectionString<UserEvents>(config.publisherUrl);
}
} satisfies Service<'userEventPublisher', EventPublisher<UserEvents>>;
// Use in endpoint with event publishing
export const createUser = e
.post('/users')
.body(z.object({
name: z.string(),
email: z.string().email()
}))
.publisher(userEventPublisher)
.event('user.created', (body, result) => ({
userId: result.id,
email: body.email
}))
.handle(async ({ body, publish }) => {
const user = {
id: crypto.randomUUID(),
name: body.name,
email: body.email
};
// Events are automatically published after successful execution
return user;
});
数据库背景
使用 .database()数字 :
import { e } from '@geekmidas/constructs/endpoints';
import type { Service } from '@geekmidas/services';
import type { EnvironmentParser } from '@geekmidas/envkit';
import { Kysely, PostgresDialect } from 'kysely';
import { z } from 'zod';
// Define a database service
const databaseService = {
serviceName: 'database' as const,
async register(envParser: EnvironmentParser<{}>) {
const config = envParser.create((get) => ({
url: get('DATABASE_URL').string()
})).parse();
return new Kysely<Database>({
dialect: new PostgresDialect({
connectionString: config.url
})
});
}
} satisfies Service<'database', Kysely<Database>>;
// Use .database() to inject db into context
export const getUsers = e
.get('/users')
.output(z.array(userSchema))
.database(databaseService)
.handle(async ({ db }) => {
// db is always defined when .database() is called (not optional)
const users = await db
.selectFrom('users')
.selectAll()
.execute();
return users;
});
关键特性:
- 类型安全数字 :
db仅在上下文中.database()名为 - 非可选: 与
services.database, (中文(简体) ),db总是被定义(不是)undefined(中文(简体) ) - 自动交易: 与
.auditor()使用KyselyAuditStorage, (中文(简体) ),db自动进行交易
审计交易数据库
在使用两者时 .database() 财务报告和审定财务报表 .auditor() 拥有同样的数据库, db 自动为交易 - 确保ACID 遵守,而不附加任何代码 :
export const createUser = e
.post('/users')
.body(z.object({ name: z.string(), email: z.string().email() }))
.output(userSchema)
.database(databaseService)
.auditor(auditStorageService)
.handle(async ({ body, db }) => {
// db is automatically the transaction when auditor uses KyselyAuditStorage
// Both the user insert and audit records commit/rollback together
const user = await db
.insertInto('users')
.values({ id: crypto.randomUUID(), ...body })
.returningAll()
.executeTakeFirstOrThrow();
return user;
});
如何运作:
- 无
.auditor()数字 :db是原始数据库连接 - 与
.auditor()使用KyselyAuditStorage与匹配databaseServiceName数字 :db自动进行交易 - 与
.auditor()使用不同的存储或不同的数据库:db仍为原始数据库
对于自动交易共享,审计存储必须声明相同的数据库服务名称:
const auditStorageService = {
serviceName: 'auditStorage' as const,
async register(envParser: EnvironmentParser<{}>) {
const db = await databaseService.register(envParser);
return new KyselyAuditStorage({
db,
tableName: 'audit_logs',
databaseServiceName: 'database', // Must match databaseService.serviceName
});
}
};
审计日志
添加了解交易的审计记录以跟踪数据变化。 审计 内部 同样的数据库交易 与您的突变, 确保它们被解剖 或滚回一起.
建立审计存储
首先,利用 @geekmidas/audit数字 :
import { KyselyAuditStorage } from '@geekmidas/audit/kysely';
import type { Service } from '@geekmidas/services';
import type { EnvironmentParser } from '@geekmidas/envkit';
const auditStorageService = {
serviceName: 'auditStorage' as const,
async register(envParser: EnvironmentParser<{}>) {
const db = await databaseService.register(envParser);
return new KyselyAuditStorage({
db,
tableName: 'audit_logs',
// Set this to enable automatic transaction sharing with .database()
databaseServiceName: databaseService.serviceName,
});
}
} satisfies Service<'auditStorage', KyselyAuditStorage<Database>>;
界定审计行动类型
为您的应用程序定义类型安全的审计动作 :
import type { AuditableAction } from '@geekmidas/audit';
type AppAuditAction =
| AuditableAction<'user.created', { userId: string; email: string }>
| AuditableAction<'user.updated', { userId: string; changes: string[] }>
| AuditableAction<'user.deleted', { userId: string; reason?: string }>
| AuditableAction<'order.placed', { orderId: string; total: number }>;
申报审计
定义在结束点上宣布的审计 - 在成功处理器执行后自动记录:
import { e } from '@geekmidas/constructs/endpoints';
import { z } from 'zod';
const userSchema = z.object({
id: z.string(),
name: z.string(),
email: z.string().email()
});
export const createUser = e
.post('/users')
.body(z.object({ name: z.string(), email: z.string().email() }))
.output(userSchema)
.database(databaseService)
.auditor(auditStorageService)
// Optional: extract actor from request context
.actor(({ session, header }) => ({
id: session?.userId ?? 'anonymous',
type: session ? 'user' : 'anonymous',
ip: header('x-forwarded-for'),
}))
// Declarative audits - type-safe with AppAuditAction
.audit<AppAuditAction>([
{
type: 'user.created',
payload: (response) => ({
userId: response.id,
email: response.email,
}),
// Optional: only audit when condition is true
when: (response) => response.email !== '[email protected]',
// Optional: link audit to entity for querying
entityId: (response) => response.id,
table: 'users',
},
])
.handle(async ({ body, db }) => {
// db is automatically the transaction when auditor uses KyselyAuditStorage
const user = await db
.insertInto('users')
.values({ id: crypto.randomUUID(), ...body })
.returningAll()
.executeTakeFirstOrThrow();
return user;
});
重要: 当使用时 KyselyAuditStorage,适配器将处理器执行包在一个数据库交易中。 这个 db 在上下文中是自动交易,因此可以直接用于符合ACID的突变.
手动操作的审计
对于复杂的情景,使用 ctx.auditor 以手动记录操作器内的审计 :
export const processOrder = e
.post('/orders')
.database(databaseService)
.services([paymentService])
.auditor(auditStorageService)
.actor(({ session }) => ({ id: session.userId, type: 'user' }))
.handle(async ({ body, db, services, auditor }) => {
// db is automatically the transaction when auditor uses KyselyAuditStorage
const order = await db
.insertInto('orders')
.values(body)
.returningAll()
.executeTakeFirstOrThrow();
// Manual audit for payment (external service call)
const payment = await services.payment.charge(order.total);
auditor.audit('payment.processed', {
orderId: order.id,
amount: order.total,
transactionId: payment.transactionId,
});
// Conditional audit for high-value orders
if (order.total > 10000) {
auditor.audit('order.high_value', {
orderId: order.id,
total: order.total,
requiresReview: true,
});
}
return order;
});
合并申报和人工审计
你们可以一起使用两种方法:
export const updateUser = e
.put('/users/:id')
.params(z.object({ id: z.string() }))
.body(z.object({ name: z.string().optional(), email: z.string().email().optional() }))
.output(userSchema)
.database(databaseService)
.auditor(auditStorageService)
.actor(({ session }) => ({ id: session.userId, type: 'user' }))
// Declarative audit - always runs on success
.audit<AppAuditAction>([
{
type: 'user.updated',
payload: (response) => ({
userId: response.id,
changes: ['profile'],
}),
},
])
.handle(async ({ params, body, db, auditor }) => {
// db is automatically the transaction when auditor uses KyselyAuditStorage
// Fetch old values for comparison
const oldUser = await db
.selectFrom('users')
.where('id', '=', params.id)
.selectAll()
.executeTakeFirstOrThrow();
// Update user
const user = await db
.updateTable('users')
.set(body)
.where('id', '=', params.id)
.returningAll()
.executeTakeFirstOrThrow();
// Manual audit with old/new values for detailed change tracking
if (oldUser.email !== user.email) {
auditor.audit('user.email_changed', {
userId: user.id,
oldEmail: oldUser.email,
newEmail: user.email,
});
}
return user;
});
交易支助如何运作
使用时 KyselyAuditStorage,自动调整器:
- 创建审计背景 处理器执行前
- 在交易中环绕执行 使用
withAuditableTransaction - 通过审计员 通过
ctx.auditor - 申报性审计过程 处理器成功后
- 取消所有审计 在交易中存储
- 提交或滚回 - 如果操作员丢弃,数据和审计都会回滚
┌─────────────────────────────────────────────────────────────┐
│ Request Flow │
├─────────────────────────────────────────────────────────────┤
│ 1. Create audit context (auditor + storage) │
│ 2. BEGIN TRANSACTION │
│ ├── Execute handler (with ctx.auditor) │
│ ├── Handler calls auditor.audit() for manual audits │
│ ├── Process declarative .audit() definitions │
│ ├── Flush all audit records to storage │
│ 3. COMMIT (or ROLLBACK if handler throws) │
└─────────────────────────────────────────────────────────────┘
这确保:
- 原子: 如果突变失败, 审计永远不会被写入
- 一致性: 没有因操作失败而成为孤儿的审计记录
- 回滚安全:在日后出现错误之前记录的手工审计也被卷回
审计表
为审计表创建 Kysely 迁移 :
// migrations/YYYYMMDDHHMMSS_create_audit_logs.ts
import type { Kysely } from 'kysely';
import { sql } from 'kysely';
export async function up(db: Kysely<unknown>): Promise<void> {
await db.schema
.createTable('audit_logs')
.addColumn('id', 'varchar(32)', (col) => col.primaryKey())
.addColumn('type', 'varchar', (col) => col.notNull())
.addColumn('operation', 'varchar', (col) => col.notNull())
.addColumn('table', 'varchar')
.addColumn('entity_id', 'varchar')
.addColumn('old_values', 'jsonb')
.addColumn('new_values', 'jsonb')
.addColumn('payload', 'jsonb')
.addColumn('timestamp', 'timestamp', (col) =>
col.defaultTo(sql`now()`).notNull(),
)
.addColumn('actor_id', 'varchar')
.addColumn('actor_type', 'varchar')
.addColumn('actor_data', 'jsonb')
.addColumn('metadata', 'jsonb')
.execute();
// Create indexes for common queries
await db.schema
.createIndex('idx_audit_logs_type')
.on('audit_logs')
.column('type')
.execute();
await db.schema
.createIndex('idx_audit_logs_entity')
.on('audit_logs')
.column('entity_id')
.execute();
await db.schema
.createIndex('idx_audit_logs_actor')
.on('audit_logs')
.column('actor_id')
.execute();
await db.schema
.createIndex('idx_audit_logs_timestamp')
.on('audit_logs')
.column('timestamp')
.execute();
}
export async function down(db: Kysely<unknown>): Promise<void> {
await db.schema.dropTable('audit_logs').execute();
}
如果使用带有 Kysely 的 CameCase 列名称 CamelCasePlugin数字 :
// migrations/YYYYMMDDHHMMSS_create_audit_logs.ts
import type { Kysely } from 'kysely';
import { sql } from 'kysely';
export async function up(db: Kysely<unknown>): Promise<void> {
await db.schema
.createTable('auditLogs')
.addColumn('id', 'varchar(32)', (col) => col.primaryKey())
.addColumn('type', 'varchar', (col) => col.notNull())
.addColumn('operation', 'varchar', (col) => col.notNull())
.addColumn('table', 'varchar')
.addColumn('entityId', 'varchar')
.addColumn('oldValues', 'jsonb')
.addColumn('newValues', 'jsonb')
.addColumn('payload', 'jsonb')
.addColumn('timestamp', 'timestamp', (col) =>
col.defaultTo(sql`now()`).notNull(),
)
.addColumn('actorId', 'varchar')
.addColumn('actorType', 'varchar')
.addColumn('actorData', 'jsonb')
.addColumn('metadata', 'jsonb')
.execute();
await db.schema
.createIndex('idx_audit_logs_type')
.on('auditLogs')
.column('type')
.execute();
await db.schema
.createIndex('idx_audit_logs_entity')
.on('auditLogs')
.column('entityId')
.execute();
await db.schema
.createIndex('idx_audit_logs_actor')
.on('auditLogs')
.column('actorId')
.execute();
await db.schema
.createIndex('idx_audit_logs_timestamp')
.on('auditLogs')
.column('timestamp')
.execute();
}
export async function down(db: Kysely<unknown>): Promise<void> {
await db.schema.dropTable('auditLogs').execute();
}
查询审计记录
这个 KyselyAuditStorage 页:1 query 方法 :
// In a handler or service
const audits = await auditStorage.query({
entityId: userId,
table: 'users',
limit: 50,
orderBy: 'timestamp',
orderDirection: 'desc',
});
限制费率
添加限制终点的速率 :
import { e } from '@geekmidas/constructs/endpoints';
import { InMemoryCache } from '@geekmidas/cache/memory';
import { z } from 'zod';
export const sendMessage = e
.post('/api/messages')
.rateLimit({
limit: 10,
windowMs: 60000, // 1 minute
cache: new InMemoryCache(),
})
.body(z.object({
content: z.string()
}))
.handle(async ({ body }) => {
// Rate limited to 10 requests per minute
return { success: true };
});
AWS Lambda 适应器
向AWS Lambda部署您的构造:
API 网关 v1 适应器
import { AmazonApiGatewayV1Endpoint } from '@geekmidas/constructs/aws';
import { getUsers } from './endpoints';
import { envParser } from './env';
const adapter = new AmazonApiGatewayV1Endpoint(envParser, getUsers);
export const handler = adapter.handler;
API 网关 v2 适配器
import { AmazonApiGatewayV2Endpoint } from '@geekmidas/constructs/aws';
import { getUsers } from './endpoints';
import { envParser } from './env';
const adapter = new AmazonApiGatewayV2Endpoint(envParser, getUsers);
export const handler = adapter.handler;
Lambda 函数适配器
import { AWSLambdaFunction } from '@geekmidas/constructs/aws';
import { processOrder } from './functions';
import { envParser } from './env';
const adapter = new AWSLambdaFunction(envParser, processOrder);
export const handler = adapter.handler;
Lambda Cron 适应器
import { AWSScheduledFunction } from '@geekmidas/constructs/aws';
import { dailyReport } from './crons';
import { envParser } from './env';
const adapter = new AWSScheduledFunction(envParser, dailyReport);
export const handler = adapter.handler;
Lambda 订户适应器
import { AWSLambdaSubscriber } from '@geekmidas/constructs/aws';
import { userEventsSubscriber } from './subscribers';
import { envParser } from './env';
const adapter = new AWSLambdaSubscriber(envParser, userEventsSubscriber);
export const handler = adapter.handler;
Hono 服务器适配器
将您的端点作为 Hono 服务器 :
import { HonoEndpoint } from '@geekmidas/constructs/endpoints';
import { ServiceDiscovery } from '@geekmidas/services';
import { Hono } from 'hono';
import { envParser } from './env';
import { logger } from './logger';
import { getUsers, createUser } from './endpoints';
export function createApp(app?: Hono): Hono {
const honoApp = app || new Hono();
const endpoints = [getUsers, createUser];
const serviceDiscovery = ServiceDiscovery.getInstance(logger, envParser);
HonoEndpoint.addRoutes(endpoints, serviceDiscovery, honoApp);
return honoApp;
}
// server.ts
import { serve } from '@hono/node-server';
import { createApp } from './app';
const app = createApp();
serve({
fetch: app.fetch,
port: 3000
}, () => {
console.log('Server running on http://localhost:3000');
});
OpenAPI 支持
从端点提取 OpenAPI 组件 :
import { OpenApiExtractor } from '@geekmidas/constructs/endpoints';
import { getUsers, createUser } from './endpoints';
const extractor = new OpenApiExtractor();
const components = extractor.extractComponents([getUsers, createUser]);
// Use with @geekmidas/cli to generate full OpenAPI spec
环境可变检测
所有建筑都支持自动环境可变检测以提供建设时的基础设施。 这使部署工具能够确切了解每个构造需要哪些环境变量.
使用 getEnvironment()
每个构造都有一个同位素 getEnvironment() 返回其服务所需的环境变量的方法:
import { e } from '@geekmidas/constructs/endpoints';
import { databaseService } from './services/database';
import { cacheService } from './services/cache';
const endpoint = e
.get('/users')
.services([databaseService, cacheService])
.handle(async ({ services }) => {
// Implementation
});
// Detect required environment variables
const envVars = await endpoint.getEnvironment();
// Returns: ['CACHE_URL', 'DATABASE_URL'] (sorted alphabetically)
如何运作
探测工作由:
- 创建“ 偷窥”
EnvironmentParser带有空配置 - 呼叫每个服务
register()使用嗅探器的方法 - 跟踪哪些环境变量通过
get('VAR_NAME') - 收集和删除可变名称
- 返回排序的可变名称数组
重要: 环境变量在 get('VAR_NAME') 被称为, 在此之前 .parse() 验证数值。 这意味着即使实际环境值不存在(建设时间),检测也是有效的.
检测服务模式
为使环境探测发挥作用,服务应返回 ConfigParser 从 envParser.create()数字 :
import type { Service } from '@geekmidas/services';
import type { EnvironmentParser } from '@geekmidas/envkit';
// ✅ Sync service - returns ConfigParser directly
const databaseService = {
serviceName: 'database' as const,
register(envParser: EnvironmentParser<{}>) {
// Return the ConfigParser - this tracks env vars
return envParser.create((get) => ({
url: get('DATABASE_URL').string(),
port: get('DATABASE_PORT').string().transform(Number).default('5432')
}));
}
} satisfies Service<'database', any>;
// ✅ Async service - check for empty env to support detection
const eventService = {
serviceName: 'events' as const,
register(envParser: EnvironmentParser<{}>) {
const configParser = envParser.create((get) => ({
connectionString: get('EVENT_CONNECTION_STRING').string()
}));
// Return ConfigParser for environment detection (build time)
// @ts-ignore - accessing internal property to detect sniffer
if (Object.keys(envParser.env || {}).length === 0) {
return configParser;
}
// Return Promise for runtime
return (async () => {
const config = configParser.parse();
// Initialize service with config
return await createService(config);
})();
}
} satisfies Service<'events', any>;
构建时间使用
这个 @geekmidas/cli 自动调用 getEnvironment() 在构建时填充列表 :
{
"routes": [
{
"path": "/users",
"method": "GET",
"handler": ".gkm/getUsers.handler",
"environment": [
"DATABASE_URL",
"DATABASE_PORT"
]
}
]
}
然后,这个表可以被基础设施-as-code工具(Terraform,CDK,SST等)使用,以正确的环境变量自动配置Lambda函数.
特征
- 自动检测: 不需要手动配置
- Async 服务支持: 既同步又同步服务
- 复制: 即使被多个服务使用, 每一个变量都列出一次
- 排序输出: 变量总是按字母顺序返回
- 反应错误: 解析失败不影响检测
- 出版商支持: 从中检测变量
.publisher()服务
多服务示例
import { e } from '@geekmidas/constructs/endpoints';
import { databaseService } from './services/database';
import { cacheService } from './services/cache';
import { emailService } from './services/email';
const endpoint = e
.post('/users')
.services([databaseService, cacheService, emailService])
.handle(async ({ services }) => {
// Create user
});
// Automatically detects all variables from all services
const envVars = await endpoint.getEnvironment();
// Returns: [
// 'CACHE_URL',
// 'DATABASE_URL',
// 'DATABASE_PORT',
// 'SMTP_HOST',
// 'SMTP_PORT',
// 'SMTP_USER',
// 'SMTP_PASS'
// ]
相关软件包
- @geekmidas/服务 - 服务发现和依赖性注射
- @geekmidas/活动 - 活动出版和订阅
- @geekmidas/审计 - 了解交易的审计记录
- @ geekmidas/ logger (英语) - 结构化伐木
- @geekmidas/envkit (英语) - 环境配置
- @geekmidas/错误 - HTTP 错误分类
- @geekmidas/ 客户端 - 消费终点的安全型客户端
- @geekmidas/ cli (英语) - 用于建设和部署的CLI工具
许可证
麻省理工学院