Skip to content

Instantly share code, notes, and snippets.

@abhitheawesomecoder
Last active November 5, 2017 05:05
Show Gist options
  • Save abhitheawesomecoder/bef7d8138c4a20ca8139adb1335f5002 to your computer and use it in GitHub Desktop.
Save abhitheawesomecoder/bef7d8138c4a20ca8139adb1335f5002 to your computer and use it in GitHub Desktop.
import { User } from './connectors';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import Constants from '../constants';
const resolvers = {
Query: {
user(_, args) {
return User.find({ where: args });
},
allUsers: (_, args, ctx) => {
return ctx.user.then((user) => {
if (!user) {
return Promise.reject('Unauthorized');
}
return User.all();
});
}
},
Mutation: {
createUser: (_, data) => {
const ret = User.create({
firstName: data.firstName,
lastName: data.lastName,
})
return ret
},
deleteUser: (_,args)=> {
User.destroy({ where: args });
return { id : args.id}
},
updateUser: (_,args)=> {
User.update({ firstName: args.firstName,lastName: args.lastName },{ where: { id: args.id } });
return { id: args.id, firstName: args.firstName,lastName: args.lastName}
},
login(_, { email, password }, ctx) {
return User.findOne({ where: { email } }).then((user) => {
if (user) {
return bcrypt.compare(password, user.password).then((res) => {
if (res) {
const token = jwt.sign({
id: user.id,
email: user.email,
}, Constants.SECRET);
user.jwt = token;
ctx.user = Promise.resolve(user);
return user;
}
return Promise.reject('password incorrect');
});
}
return Promise.reject('email not found');
});
},
signup(_, { email, password }, ctx) {
return User.findOne({ where: { email } }).then((existing) => {
if (!existing) {
return bcrypt.hash(password, 10).then(hash => User.create({
email,
password: hash
})).then((user) => {
const { id } = user;
const token = jwt.sign({ id, email }, Constants.SECRET);
user.jwt = token;
ctx.user = Promise.resolve(user);
return user;
});
}
return Promise.reject('email already exists');
});
}
}
};
export default resolvers;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment