问题描述
我有一个使用以下现有路线的GraphQL和Express项目:
I have a GraphQL and Express project with these existing routes:
// ...
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响应:
My results after a GET on http://localhost:3030/graphql?query={regions(countries:["FR"],level:0){...}
look like a normal GraphQL response:
{
"data": {
"regions": [
{
"type": "FeatureCollection",
"features": [
...
...
]
}
]
}
}
是否可以将响应转换为更有效的GeoJSON格式?(没有"数据:{} ",并且没有我的查询名称等),例如:
Is there a way to transform the response to something more like a valid GeoJSON format? (no "data:{ }" and without the name of my query, etc.) such as:
{
"type": "FeatureCollection",
"features": [
...
...
]
}
我已经想到要做的是使用 middleare (但是如何?)和/或诸如 graphql-normalizr 之类的规范化器(但我不这样做)不知道如何用Express插入)
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)
推荐答案
经过左右几个小时的搜索,我找到了可行的解决方案.幸运的是,您可以使用 formatResponse
: https://github.com/apollographql/apollo-server/blob/master/packages/apollo-server-core/src/graphqlOptions.ts#L43
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
更新后的代码如下:
app.use(
'/graphql',
bodyParser.json(),
graphqlExpress({ schema, formatResponse: res => (res.data.regions && res.data.regions[0]) || res })
);
这篇关于更改GraphQL响应的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!