|
| 1 | +import { delegateToSchema } from '@graphql-tools/delegate'; |
| 2 | +import { |
| 3 | + AuthenticationError, |
| 4 | + UserInputError, |
| 5 | + ForbiddenError |
| 6 | +} from 'apollo-server'; |
| 7 | +import Person from './db/entities/Person'; |
| 8 | +import Post from './db/entities/Post'; |
| 9 | + |
| 10 | +export default ({ subschema }) => ({ |
| 11 | + Query: { |
| 12 | + profile: async (_parent, _args, context, info) => { |
| 13 | + const [person] = await delegateToSchema({ |
| 14 | + schema: subschema, |
| 15 | + operation: 'query', |
| 16 | + fieldName: 'Person', |
| 17 | + args: { |
| 18 | + id: context.person.id |
| 19 | + }, |
| 20 | + context, |
| 21 | + info |
| 22 | + }); |
| 23 | + return person; |
| 24 | + } |
| 25 | + }, |
| 26 | + Mutation: { |
| 27 | + login: async (_parent, { email, password }, { jwtSign }) => { |
| 28 | + const person = await Person.first({ email }); |
| 29 | + if (person && person.checkPassword(password)) { |
| 30 | + return jwtSign({ person: { id: person.id } }); |
| 31 | + } |
| 32 | + throw new AuthenticationError('Wrong email/password combination!'); |
| 33 | + }, |
| 34 | + signup: async (_parent, { name, email, password }, { jwtSign }) => { |
| 35 | + const existingPerson = await Person.first({ email }); |
| 36 | + if (existingPerson) throw new UserInputError('email address not unique'); |
| 37 | + const person = new Person({ name, email, password }); |
| 38 | + await person.save(); |
| 39 | + return jwtSign({ person: { id: person.id } }); |
| 40 | + }, |
| 41 | + writePost: async (_parent, args, context, info) => { |
| 42 | + const currentUser = await Person.currentUser(context); |
| 43 | + if (!currentUser) |
| 44 | + throw new ForbiddenError('You must be authenticated to write a post!'); |
| 45 | + const post = new Post({ ...args, author: currentUser }); |
| 46 | + await post.save(); |
| 47 | + const [resolvedPost] = await delegateToSchema({ |
| 48 | + schema: subschema, |
| 49 | + operation: 'query', |
| 50 | + fieldName: 'Post', |
| 51 | + args: { id: post.id }, |
| 52 | + context, |
| 53 | + info |
| 54 | + }); |
| 55 | + return resolvedPost; |
| 56 | + } |
| 57 | + }, |
| 58 | + Person: { |
| 59 | + email: { |
| 60 | + selectionSet: '{ id }', |
| 61 | + resolve: (parent, _args, context) => { |
| 62 | + const { person } = context; |
| 63 | + if (person && person.id === parent.id) return parent.email; |
| 64 | + throw new ForbiddenError('E-Mail addresses are private'); |
| 65 | + } |
| 66 | + }, |
| 67 | + postCount: { |
| 68 | + selectionSet: '{ posts { id } }', |
| 69 | + resolve: person => person.posts.length |
| 70 | + } |
| 71 | + } |
| 72 | +}); |
0 commit comments