import * as bcrypt from 'bcryptjs' ; import * as jwt from 'jsonwebtoken' ; import { MutationResolvers } from '../generated/resolvers' ; import { getUserId } from '../utils' ; import { TypeMap } from './types/TypeMap' ; export interface MutationParent { } export const Mutation = { signup : async ( _ , args , ctx , _info ) => { const password = await bcrypt . hash ( args . password , 10 ) ; const user = await ctx . db . createUser ( { ... args , password , responseRate : 0 , responseTime : 0 } ) ; const token = jwt . sign ( { userId : user . id } , process . env . APP_SECRET as jwt . Secret ) ; return { id : user . id , token } ; } , login : async ( _parent , { email , password } , ctx ) => { const user = await ctx . db . user ( { email } ) ; const valid = await bcrypt . compare ( password , user ? user . password : '' ) ; if ( ! valid || ! user ) { throw new Error ( 'Invalid Credentials' ) ; } const token = jwt . sign ( { userId : user . id } , process . env . APP_SECRET as jwt . Secret ) ; return { id : user . id , token } ; } , addPaymentMethod : ( parent , args ) => { throw new Error ( 'Resolver not implemented' ) ; } , book : async ( _parent , args , ctx ) => { const userId = getUserId ( ctx ) ; const alreadyBooked = await ctx . db . bookings ( { where : { startDate_gte : args . checkIn , startDate_lte : args . checkOut , place : { id : args . placeId } } } ) ; if ( alreadyBooked && alreadyBooked . length > 0 ) { throw new Error ( `The requested time is not free.` ) ; } const pricing = await ctx . db . place ( { id : args . placeId } ) . pricing ( ) ; if ( ! pricing ) { throw new Error ( `No such place/pricing found` ) ; } await ctx . db . createBooking ( { startDate : args . checkIn , endDate : args . checkOut , bookee : { connect : { id : userId } } , place : { connect : { id : args . placeId } } } ) ; return { success : true } ; } } ;