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',
})
);
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": [
...
...
]
}
]
}
}
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": [
...
...
]
}
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)
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
The updated code looks like:
app.use(
'/graphql',
bodyParser.json(),
graphqlExpress({ schema, formatResponse: res => (res.data.regions && res.data.regions[0]) || res })
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.