You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为AWS Lambda的Hasura Action中间件添加正确TypeScript类型?

解决方案

1. 修复Promise<typeof formatJSONResponse<Output>>的TS2635错误

错误核心是typeof formatJSONResponse拿到的是函数类型,不能直接给它传递泛型参数。解决步骤:

  • 先给formatJSONResponse定义泛型函数类型,让它的返回类型可复用
  • 用类型别名提取该函数的返回类型,替代原错误写法

修改代码如下:

// 给formatJSONResponse添加泛型定义
export const formatJSONResponse = <T>(response: T) => {
  return {
    statusCode: 200,
    body: JSON.stringify(response),
  };
};

// 提取函数的返回类型别名
type FormatJSONResponse<T> = ReturnType<typeof formatJSONResponse<T>>;

之后把Promise<typeof formatJSONResponse<Output>>替换为Promise<FormatJSONResponse<Output>>即可消除类型错误。

2. 替换中间件的:any返回类型

中间件本质是AWS Lambda处理函数,结合Hasura Action的输入结构,我们可以定义完整的类型约束:

第一步:定义基础类型

// Hasura Action的请求结构
interface HasuraActionEvent<Input> {
  input: Input;
  session_variables: Record<string, string>;
  action: {
    name: string;
  };
}

// Lambda触发事件的基础结构(API Gateway触发场景)
interface LambdaTriggerEvent<Input> {
  body: string;
}

// Lambda响应类型复用formatJSONResponse的返回类型
type LambdaResponse<T> = FormatJSONResponse<T>;

第二步:给中间件定义严格类型

中间件是高阶函数,接收Hasura业务逻辑handler,返回符合Lambda规范的处理函数:

// 定义业务handler的类型:接收解析后的Hasura事件,返回业务输出的Promise
type HasuraBusinessHandler<Input, Output> = (
  event: HasuraActionEvent<Input>
) => Promise<Output>;

// 中间件的完整类型定义
const createHasuraActionMiddleware = <Input, Output>(
  handler: HasuraBusinessHandler<Input, Output>
): ((event: LambdaTriggerEvent<Input>) => Promise<LambdaResponse<Output>>) => {
  return async (event) => {
    try {
      const parsedEvent = JSON.parse(event.body) as HasuraActionEvent<Input>;
      const result = await handler(parsedEvent);
      return formatJSONResponse(result);
    } catch (error) {
      return formatJSONResponse({
        message: (error as Error).message,
        status: "error",
      });
    }
  };
};

3. 完整使用示例

// 定义具体的业务输入输出类型
interface UserLookupInput {
  userId: string;
}

interface UserLookupOutput {
  user: {
    id: string;
    name: string;
    email: string;
  };
}

// 业务逻辑handler
const userLookupHandler: HasuraBusinessHandler<UserLookupInput, UserLookupOutput> = async (event) => {
  // 模拟数据库查询逻辑
  return {
    user: {
      id: event.input.userId,
      name: "John Doe",
      email: "john@example.com",
    },
  };
};

// 生成可直接部署的Lambda handler
export const handler = createHasuraActionMiddleware(userLookupHandler);

内容的提问来源于stack exchange,提问作者Stathis Ntonas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 23:45:38