|
|
|
|
|
const debug = require('debug')('api:thread-message-connection'); |
|
|
import type { DBThread } from 'shared/types'; |
|
|
import type { PaginationOptions } from '../../utils/paginate-arrays'; |
|
|
import UserError from '../../utils/UserError'; |
|
|
import { encode, decode } from '../../utils/base64'; |
|
|
import { getMessages } from '../../models/message'; |
|
|
|
|
|
export default ( |
|
|
{ id }: DBThread, |
|
|
{ |
|
|
first, |
|
|
after, |
|
|
last, |
|
|
before, |
|
|
}: { ...PaginationOptions, last: number, before: string } |
|
|
) => { |
|
|
|
|
|
if ( |
|
|
(first && last) || |
|
|
(after && before) || |
|
|
(first && before) || |
|
|
(after && last) |
|
|
) { |
|
|
debug('invalid pagination options provided:'); |
|
|
debug( |
|
|
'first:', |
|
|
first, |
|
|
' last:', |
|
|
last, |
|
|
' after:', |
|
|
after, |
|
|
' before:', |
|
|
before |
|
|
); |
|
|
return new UserError( |
|
|
'Cannot paginate back- and forwards at the same time. Please only ask for the first messages after a certain point or the last messages before a certain point.' |
|
|
); |
|
|
} |
|
|
|
|
|
debug(`get messages for ${id}`); |
|
|
let cursor = after || before; |
|
|
try { |
|
|
cursor = decode(cursor); |
|
|
if (cursor) cursor = parseInt(cursor, 10); |
|
|
} catch (err) { |
|
|
console.error('❌ Error in job:\n'); |
|
|
console.error(err); |
|
|
return new UserError('Invalid cursor passed to thread.messageConnection.'); |
|
|
} |
|
|
if (cursor) debug(`cursor: ${cursor}`); |
|
|
|
|
|
let options = { |
|
|
|
|
|
|
|
|
|
|
|
first: first ? first : after ? 25 : null, |
|
|
last: last ? last : before ? 25 : null, |
|
|
|
|
|
after: after ? cursor : null, |
|
|
before: before ? cursor : null, |
|
|
}; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if (Object.keys(options).every(key => !options[key])) { |
|
|
options = { |
|
|
first: 25, |
|
|
}; |
|
|
} |
|
|
|
|
|
debug('pagination options for query:', options); |
|
|
|
|
|
|
|
|
|
|
|
options.first && options.first++; |
|
|
options.last && options.last++; |
|
|
|
|
|
return getMessages(id, options).then(result => { |
|
|
let messages = result; |
|
|
|
|
|
|
|
|
const loadedMoreFirst = options.first && result.length > options.first - 1; |
|
|
const loadedMoreLast = options.last && result.length > options.last - 1; |
|
|
|
|
|
|
|
|
if (loadedMoreFirst) { |
|
|
debug('not sending extranous message loaded first'); |
|
|
messages = result.slice(0, result.length - 1); |
|
|
} else if (loadedMoreLast) { |
|
|
debug('not sending extranous message loaded last'); |
|
|
messages = result.reverse().slice(1, result.length); |
|
|
} |
|
|
|
|
|
return { |
|
|
pageInfo: { |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
hasNextPage: loadedMoreFirst || !!options.before, |
|
|
|
|
|
hasPreviousPage: loadedMoreLast || !!options.after, |
|
|
}, |
|
|
edges: messages.map(message => ({ |
|
|
cursor: encode(message.timestamp.getTime().toString()), |
|
|
node: message, |
|
|
})), |
|
|
}; |
|
|
}); |
|
|
}; |
|
|
|