简体   繁体   English

更改GraphQL响应的结构

[英]Change the structure of a GraphQL response

I have a GraphQL and Express project with these existing routes: 我有一个包含这些现有路线的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',
  })
);

My results after a GET on http://localhost:3030/graphql?query={regions(countries:["FR"],level:0){...} look like a normal GraphQL response: http://localhost:3030/graphql?query={regions(countries:["FR"],level:0){...}上获取GET之后的结果看起来像普通的GraphQL响应:

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

Is there a way to transform the response to something more like a valid GeoJSON format? 有没有办法将响应转换为更有效的GeoJSON格式? (no " data:{ } " and without the name of my query, etc.) such as: (没有“ data:{} ”,没有我的查询名称等),例如:

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

What I've already thought of doing is either using a middleare (but how?) and/or a normalizer such as graphql-normalizr (but I don't know how to plug it with Express) 我已经想过要做的是使用中间 (但是如何?)和/或规范化器如graphql-normalizr (但我不知道如何用Express插入它)

After a few good hours of searching left and right I found a viable solution. 经过几个小时的左右搜索后,我找到了一个可行的解决方案。 Luckily there is a formatResponse that you can use: https://github.com/apollographql/apollo-server/blob/master/packages/apollo-server-core/src/graphqlOptions.ts#L43 幸运的是,您可以使用formatResponsehttps//github.com/apollographql/apollo-server/blob/master/packages/apollo-server-core/src/graphqlOptions.ts#L43

The updated code looks like: 更新的代码如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM