更改GraphQL响应的结构

时间:2019-06-04 13:23:21

标签: javascript node.js express graphql

我有一个使用以下现有路线的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格式? (没有“ 数据:{} ”,并且没有我的查询名称等),例如:

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

我已经想到要做的是使用 middleare (但是如何?)和/或诸如 graphql-normalizr 之类的规范化器(但我不这样做)不知道如何用Express插入它)

1 个答案:

答案 0 :(得分:0)

经过左右几个小时的搜索,我找到了可行的解决方案。 幸运的是,您可以使用一个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 })
);
相关问题