Skip to content

Instantly share code, notes, and snippets.

@tamlyn
Last active March 5, 2018 12:00
Show Gist options
  • Save tamlyn/aaf606b561d19b9afaa4cb081eae1aba to your computer and use it in GitHub Desktop.
Save tamlyn/aaf606b561d19b9afaa4cb081eae1aba to your computer and use it in GitHub Desktop.
Redacting fields in GraphQL with Apollo Server

Demo showing that by specifying a resolver for a scalar property, you can override the value.

This is useful for authorization as it means you can centrally check permissions per field. Your general resolvers can return whole objects without caring about which fields the current user may or may not be allowed to see.

const express = require('express')
const { graphqlExpress } = require('apollo-server-express')
const { makeExecutableSchema } = require('graphql-tools')
const bodyParser = require('body-parser');
const app = express()
const typeDefs = `
type Query {
test: Test
}
type Test {
public: String
private: String
}
`
const resolvers = {
Query: {
test: () => ({ public: 'hey', private: 'ho' }),
},
Test: {
private: () => null,
},
}
const schema = makeExecutableSchema({ typeDefs, resolvers })
app.use(bodyParser.json())
app.use('/graphql', graphqlExpress({ schema }))
app.listen(3000)

Query

{
  test {
    public
    private
  }
}

Result

{
  "data": {
    "test": {
      "public": "hey",
      "private": null
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment