Created
September 5, 2020 14:10
-
-
Save segunadebayo/caa22986241ec614fff55519a639c83d to your computer and use it in GitHub Desktop.
Applying Middleware to Apollo Server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { ApolloServer, gql, makeExecutableSchema } = require('apollo-server') | |
const { applyMiddleware } = require('graphql-middleware') | |
const uppercaseCategory = async (resolve, parent, args, context, info) => { | |
const result = await resolve(parent, args, context, info) | |
return result.toUpperCase() | |
} | |
const postsMiddleware = async (resolve, parent, args, context, info) => { | |
const result = await resolve(parent, args, context, info) | |
const formattedPosts = result.reduce( | |
(formatted, post) => [ | |
...formatted, | |
{ | |
...post, | |
title: `${post.category}: ${post.title}` | |
} | |
], | |
[] | |
) | |
return formattedPosts | |
} | |
const postMiddleware = { | |
Post: { | |
category: uppercaseCategory | |
}, | |
Query: { | |
posts: postsMiddleware | |
} | |
} | |
const middleware = [postMiddleware] | |
const schemaWithMiddleware = applyMiddleware(schema, ...middleware) | |
const server = new ApolloServer({ schema: schemaWithMiddleware }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment