import { IResolvers } from 'apollo-server-express' ; import { UserArgs , UserBookingArgs , UserBookingsData , UserListingsArgs , UserListingsData } from "./types" ; import { Database , User } from "../../../lib/types" ; import { Request } from 'express' ; import { authorize } from "../../../lib/utils" ; export const userResolvers = { Query : { user : async ( _root , { id } , { db , req } ) : Promise < User > => { try { const user = await db . users . findOne ( { _id : id } ) ; if ( ! user ) { throw new Error ( "user can't be found" ) ; } const viewer = await authorize ( db , req ) ; if ( viewer && viewer . _id === user . _id ) { user . authorized = true ; } return user ; } catch ( error ) { throw new Error ( `Failed to query user: ${ error }` ) ; } } } , User : { id : ( user ) : string => { return user . _id ; } , hasWallet : ( user ) : boolean => { return Boolean ( user . walletId ) ; } , income : ( user ) : number | null => { return user . authorized ? user . income : null ; } , bookings : async ( user , { limit , page } , { db } ) : Promise < UserBookingsData | null > => { try { if ( ! user . authorized ) { return null ; } const data = { total : 0 , result : [ ] } ; let cursor = await db . bookings . find ( { _id : { $in : user . bookings } } ) ; cursor = cursor . skip ( page > 0 ? ( page - 1 ) * limit : 0 ) ; cursor = cursor . limit ( limit ) ; data . total = await cursor . count ( ) ; data . result = await cursor . toArray ( ) ; return data ; } catch ( error ) { throw new Error ( `Failed to query user bookings: ${ error }` ) ; } } , listings : async ( user , { limit , page } , { db } ) : Promise < UserListingsData | null > => { try { const data = { total : 0 , result : [ ] } ; let cursor = await db . listings . find ( { _id : { $in : user . listings } } ) ; cursor = cursor . skip ( page > 0 ? ( page - 1 ) * limit : 0 ) ; cursor = cursor . limit ( limit ) ; data . total = await cursor . count ( ) ; data . result = await cursor . toArray ( ) ; return data ; } catch ( error ) { throw new Error ( `Failed to query user listings: ${ error }` ) ; } } } } ;