import _last from 'lodash/last' ; import { NODE_TYPES } from 'common/enums' ; import { fromGlobalId , toGlobalId } from 'common/utils' ; import { ArticleToResponsesResolver } from 'definitions' ; const resolver = async ( { articleId } , { input : { sort , first , ... restParams } } , { dataSources : { articleService , commentService } } ) => { const order = sort === 'oldest' ? 'asc' : 'desc' ; const state = 'active' ; if ( ! restParams . before && typeof first === 'undefined' ) { first = 8 ; } let after ; let before ; if ( restParams . after ) { after = fromGlobalId ( restParams . after ) . id ; } if ( restParams . before ) { before = fromGlobalId ( restParams . before ) . id ; } const { includeAfter , includeBefore , articleOnly } = restParams ; const [ sources , range ] = await Promise . all ( [ articleService . findResponses ( { id : articleId , order , state , after , before , first , includeAfter , includeBefore , articleOnly , } ) , articleService . responseRange ( { id : articleId , order , state , } ) , ] ) ; const items = await Promise . all ( sources . map ( ( source ) => { switch ( source . type ) { case 'Article' : { return articleService . draftLoader . load ( source . entityId ) ; } case 'Comment' : { return commentService . baseFindById ( source . entityId ) ; } } } ) ) ; const edges = items . map ( ( item ) => { const type = ! ! item . title ? NODE_TYPES . Article : NODE_TYPES . Comment ; const id = type === 'Article' ? item . articleId : item . id ; return { cursor : toGlobalId ( { type , id } ) , node : { __type : type , ... item } , } ; } ) ; const head = sources [ 0 ] as { [ key ] : any ; } ; const headSeq = head && parseInt ( head . seq , 10 ) ; const tail = _last ( sources ) as { [ key ] : any ; } ; const tailSeq = tail && parseInt ( tail . seq , 10 ) ; const edgeHead = edges [ 0 ] ; const edgeTail = _last ( edges ) ; return { edges , totalCount : range . count , pageInfo : { startCursor : edgeHead ? edgeHead . cursor : '' , endCursor : edgeTail ? edgeTail . cursor : '' , hasPreviousPage : order === 'asc' ? headSeq > range . min : headSeq < range . max , hasNextPage : order === 'asc' ? tailSeq < range . max : tailSeq > range . min , } , } ; } ; export default resolver ;