Skip to content

Instantly share code, notes, and snippets.

@maticzav
Last active January 3, 2018 17:14
Show Gist options
  • Save maticzav/07dda531002d0af26b9ca014d4a208d0 to your computer and use it in GitHub Desktop.
Save maticzav/07dda531002d0af26b9ca014d4a208d0 to your computer and use it in GitHub Desktop.
// src/resolvers/index.ts
import { me } from './Query/me'
import { auth } from './Mutation/auth'
export const resolvers = {
Query: {
me,
},
Mutation: {
...auth,
}
}
// src/resolvers/Query/me.ts
import { Context, User, getUserId } from '../../utils'
export const me = async (_, args, ctx: Context, info) => {
const id = getUserId(ctx) // Tries to identify the user using JWT.
return await ctx.db.query.user({ where: { id } }, info) // Queryies the user if one exists.
}
// src/resolvers/Mutation/auth.ts
import { Context, User } from '../../utils'
import { getGithubToken, getGithubUser, GithubUser } from '../../github'
import * as jwt from 'jsonwebtoken'
async function getGraphcoolUser(ctx: Context, githubUserId: string): Promise<User> {
return await ctx.db.query.user({ where: { githubUserId } })
}
async function createGraphcoolUser(ctx, githubUser: GithubUser): Promise<User> {
const user = await ctx.db.mutation.createUser({
data: {
githubUserId: githubUser.id,
name: githubUser.name,
bio: githubUser.bio,
public_repos: githubUser.public_repos,
public_gists: githubUser.public_gists,
notes: []
}
})
return user
}
export const auth = {
authenticate: async (parent, { githubCode }, ctx: Context, info) => {
const githubToken = await getGithubToken(githubCode) // Obtains "super" token.
const githubUser = await getGithubUser(githubToken) // Fetches user profile
// Checks whether a User with this id already exists.
let user = await getGraphcoolUser(ctx, githubUser.id)
if (!user) {
// Creates a new user if there's no user with such id.
user = await createGraphcoolUser(ctx, githubUser)
}
// Returns user and it's access token.
return {
token: jwt.sign({ userId: user.id }, process.env.JWT_SECRET),
user
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment