[英]Change the structure of a GraphQL response
我有一个包含这些现有路线的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": [
...
...
]
}
我已经想过要做的是使用中间 (但是如何?)和/或规范化器如graphql-normalizr (但我不知道如何用Express插入它)
经过几个小时的左右搜索后,我找到了一个可行的解决方案。 幸运的是,您可以使用formatResponse
: https : //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 })
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.