Skip to content

Instantly share code, notes, and snippets.

@tamlyn tamlyn/Readme.md
Last active Mar 5, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.