File size: 3,678 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
// @flow
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 }
) => {
  // Make sure users don't provide bonkers arguments that paginate in both directions at the same time
  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 = {
    // Default first/last to 25 if their counterparts after/before are provided
    // so users can query messageConnection(after: "cursor") or (before: "cursor")
    // without any more options
    first: first ? first : after ? 25 : null,
    last: last ? last : before ? 25 : null,
    // Set after/before to the cursor depending on which one was requested by the user
    after: after ? cursor : null,
    before: before ? cursor : null,
  };

  // If we didn't get any arguments at all (i.e messageConnection {})
  // then just fetch the first 25 messages
  // $FlowIssue
  if (Object.keys(options).every(key => !options[key])) {
    options = {
      first: 25,
    };
  }

  debug('pagination options for query:', options);

  // Load one message too much so that we know whether there's
  // a next or previous page
  options.first && options.first++;
  options.last && options.last++;

  return getMessages(id, options).then(result => {
    let messages = result;
    // Check if more messages were returned than were requested, which would mean
    // there's a next/previous page. (depending on the direction of the pagination)
    const loadedMoreFirst = options.first && result.length > options.first - 1;
    const loadedMoreLast = options.last && result.length > options.last - 1;

    // Get rid of the extranous message if there is one
    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: {
        // Use the extranous message that was maybe loaded to figure out whether
        // there is a next/previous page, otherwise just try and guess based on
        // if a cursor was provided
        // $FlowIssue
        hasNextPage: loadedMoreFirst || !!options.before,
        // $FlowIssue
        hasPreviousPage: loadedMoreLast || !!options.after,
      },
      edges: messages.map(message => ({
        cursor: encode(message.timestamp.getTime().toString()),
        node: message,
      })),
    };
  });
};