【问题标题】:Change the structure of a GraphQL response更改 GraphQL 响应的结构
【发布时间】:2019-10-20 00:57:57
【问题描述】:

我有一个包含以下现有路由的 GraphQL 和 Express 项目:

// ...

const graphiqlExpress = require('graphql-server-express').graphiqlExpress;
const graphqlExpress = require('graphql-server-express').graphqlExpress;
const makeExecutableSchema = require('graphql-tools').makeExecutableSchema;

// ...

const schema = makeExecutableSchema({
  typeDefs,
  resolvers,
});

// ...

app.use('/graphql', bodyParser.json(), graphqlExpress({ schema }));
app.use(
  '/graphiql',
  graphiqlExpress({
    endpointURL: '/graphql',
  })
);

我在http://localhost:3030/graphql?query={regions(countries:["FR"],level:0){...} 上获得 GET 后的结果看起来像正常的 GraphQL 响应:

{
  "data": {
    "regions": [
      {
        "type": "FeatureCollection",
        "features": [
          ...
          ...
        ]
      }
    ]
  }
}

有没有办法将响应转换为更像有效的 GeoJSON 格式? (没有 "data:{ }" 并且没有我的查询名称等)例如:

{
  "type": "FeatureCollection",
    "features": [
      ...
      ...
    ]  
}

我已经考虑过使用 middleare(但如何使用?)和/或规范化器,例如 graphql-normalizr(但我没有不知道如何用 Express 插入)

【问题讨论】:

    标签: javascript node.js express graphql


    【解决方案1】:

    经过几个小时左右的搜索,我找到了一个可行的解决方案。 幸运的是,您可以使用 formatResponsehttps://github.com/apollographql/apollo-server/blob/master/packages/apollo-server-core/src/graphqlOptions.ts#L43

    更新后的代码如下:

    app.use(
      '/graphql',
      bodyParser.json(),
      graphqlExpress({ schema, formatResponse: res => (res.data.regions && res.data.regions[0]) || res })
    );
    

    【讨论】:

    猜你喜欢
    • 2019-11-17
    • 1970-01-01
    • 1970-01-01
    • 2019-01-17
    • 2021-12-14
    • 2017-03-08
    • 2019-09-28
    • 2020-04-23
    • 2019-01-15
    相关资源
    最近更新 更多