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

求基于amplify-appsync-simulator的HTTP数据源AppSync模拟器配置示例

使用amplify-appsync-simulator配置HTTP数据源示例

1. 基础项目结构

.
├── schema.graphql
├── resolvers/
│   ├── Query.getHttpData.req.vtl
│   └── Query.getHttpData.res.vtl
└── simulator.ts

2. 定义GraphQL Schema(schema.graphql)

type Query {
  getHttpData(id: String!): HttpResponse
}

type HttpResponse {
  statusCode: Int!
  body: String
}

3. 编写VTL解析器

请求模板(resolvers/Query.getHttpData.req.vtl)

{
  "version": "2018-05-29",
  "method": "GET",
  "resourcePath": "/data/${context.arguments.id}",
  "params": {
    "headers": {
      "Content-Type": "application/json"
    }
  }
}

响应模板(resolvers/Query.getHttpData.res.vtl)

{
  "statusCode": $context.result.statusCode,
  "body": $util.toJson($context.result.body)
}

4. 初始化模拟器代码(simulator.ts)

import { AppSyncSimulator } from 'amplify-appsync-simulator';

const simulator = new AppSyncSimulator({
  schema: './schema.graphql',
  resolvers: {
    Query: {
      getHttpData: {
        kind: 'UNIT',
        fieldName: 'getHttpData',
        dataSourceName: 'HttpDataSource',
        requestMappingTemplateLocation: './resolvers/Query.getHttpData.req.vtl',
        responseMappingTemplateLocation: './resolvers/Query.getHttpData.res.vtl',
      },
    },
  },
  dataSources: [
    {
      type: 'HTTP',
      name: 'HttpDataSource',
      config: {
        endpoint: 'http://your-backend-endpoint.com', // 替换为你的实际HTTP服务地址
        // 无需签名时可删除authorizationConfig
        authorizationConfig: {
          signingRegion: 'us-east-1',
          signingServiceName: 'execute-api',
        },
      },
    },
  ],
});

simulator.start().then(({ url }) => {
  console.log(`AppSync模拟器运行在: ${url}/graphiql`);
});

5. 错误排查提示

你遇到的Unable to convert to class com.amazonaws.deepish.transform.model.lambda.LambdaVersionedConfig错误,大概率是配置中混入了Lambda数据源的字段(比如lambdaFunctionArn),检查dataSources配置,确保HTTP数据源的config仅包含HTTP相关字段(endpoint、authorizationConfig等),不要掺杂Lambda相关配置。


替代方案:使用serverless-appsync-plugin本地模拟器

若不想依赖amplify-appsync-simulator,serverless-appsync-plugin也支持本地模拟HTTP数据源,配置更简洁,无需编写大量TypeScript代码。

1. 安装依赖

npm install serverless serverless-appsync-plugin --save-dev

2. serverless.yml配置示例

service: appsync-http-simulator

plugins:
  - serverless-appsync-plugin

custom:
  appSync:
    name: HttpSimulatorAPI
    schema: schema.graphql
    authenticationType: API_KEY
    apiKeys:
      - name: localKey
        description: Local API Key
    dataSources:
      - type: HTTP
        name: HttpDataSource
        config:
          endpoint: http://your-backend-endpoint.com
    resolvers:
      Query.getHttpData:
        dataSource: HttpDataSource
        requestMappingTemplate: ./resolvers/Query.getHttpData.req.vtl
        responseMappingTemplate: ./resolvers/Query.getHttpData.res.vtl

provider:
  name: aws
  region: us-east-1

3. 启动模拟器

serverless appsync simulate

启动后访问http://localhost:20002/graphql即可测试HTTP数据源查询。


轻量替代:自定义GraphQL服务器(仅支持HTTP数据源)

若仅需模拟HTTP数据源的GraphQL接口,可直接用graphql-yoga结合自定义解析器,无需依赖AppSync模拟器:

import { createServer } from '@graphql-yoga/node';
import fetch from 'node-fetch';

const typeDefs = `
type Query {
  getHttpData(id: String!): HttpResponse
}

type HttpResponse {
  statusCode: Int!
  body: String
}
`;

const resolvers = {
  Query: {
    getHttpData: async (_, { id }) => {
      const response = await fetch(`http://your-backend-endpoint.com/data/${id}`, {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' },
      });
      return {
        statusCode: response.status,
        body: await response.text(),
      };
    },
  },
};

const server = createServer({ typeDefs, resolvers });

server.start().then(() => {
  console.log('服务器运行在http://localhost:4000/graphql');
});

该方案无需VTL,直接用JavaScript编写解析逻辑,适合快速测试HTTP接口。

内容的提问来源于stack exchange,提问作者sudhir tataraju

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 23:42:07