Skip to content

Instantly share code, notes, and snippets.

@YuriFontella
Last active May 28, 2021 05:54
Show Gist options
  • Save YuriFontella/72d84cf91fc421f0be0c6abcea240405 to your computer and use it in GitHub Desktop.
Save YuriFontella/72d84cf91fc421f0be0c6abcea240405 to your computer and use it in GitHub Desktop.
graphql schemas and resolvers with auth
'use strict'
const Fastify = require('fastify')
const mercurius = require('mercurius')
const auth = require('mercurius-auth')
const { ErrorWithProps } = mercurius
const app = Fastify()
const users = [
{
id: '1',
name: 'John',
username: '@john',
password: '123'
},
{
id: '2',
name: 'Jane',
username: '@jane',
password: '123'
}
]
const schema = `
directive @auth on OBJECT | FIELD_DEFINITION
extend type Query {
me(id: ID!): User @auth
all(name: String): [User]
}
type User @key(fields: "id") {
id: ID!
name: String
username: String
password: String
}
input UserInput {
name: String
username: String
password: String
}
type Mutation {
post(input: UserInput): User
login(username: String, password: String): String
}
`
const resolvers = {
Query: {
me: (parent, { id }, context) => {
console.log(context)
return users[id]
},
all: (parent, { name }) => {
return users
}
},
Mutation: {
post: (parent, { input }) => {
if (!input.username) {
throw new ErrorWithProps('Invalid', {
code: 500,
message: 'Username not defined'
})
}
return input
},
login: (parent, { username, password }) => {
if (username === 'yuri' && password === '123') {
return 'token'
} else {
throw new ErrorWithProps('Login failed', {
code: 500,
message: 'username or password incorrect'
})
}
}
}
}
app.register(mercurius, {
schema,
resolvers,
graphiql: 'playground',
federationMetadata: true
})
app.register(auth, {
authContext (context) {
return {
// context.reply.request.headers['x-user']
identity: true
}
},
async applyPolicy (authDirectiveAST, parent, args, context, info) {
context.user_id = 10
return context.auth.identity
},
authDirective: 'auth'
})
app.register(require('fastify-cors'), {
origin: true
})
app.listen(5000)
// http://localhost:5000/playground
// mutation {
// post(input: { name: "", username: "" }) {
// username
// }
// }
// all {
// name
// }
//QUERY VARIABLES
//
// query getMe($id: ID!) {
// me(id: $id) {
// name
// }
// }
//
// {
// "id": 1
// }
// ALIASES
//
// mutation {
// auth: login(username: "yuri", password: "123")
// }
//
// FRAGMENT
//
// query getUsers {
// users: all {
// ...file
// }
// }
//
// fragment file on User {
// name
// username
// }
// DIRECTIVES
//
// query getMe($id: ID!, $permit: Boolean!) {
// me(id: $id) {
// name
// username @skip(if: $permit)
// password @include(if: $permit)
// }
// }
//
// {
// "id": 1,
// "permit": true
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment