Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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;
Add Comment
Please, Sign In to add comment