File size: 1,919 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
// @flow
import type { GraphQLContext } from '../../';
import type { DBUser } from 'shared/types';
import type { PaginationOptions } from '../../utils/paginate-arrays';
import { encode, decode } from '../../utils/base64';
const {
  getViewableThreadsByUser,
  getPublicThreadsByUser,
  getPublicParticipantThreadsByUser,
  getViewableParticipantThreadsByUser,
} = require('../../models/thread');

export default (
  { id }: DBUser,
  {
    first,
    after,
    kind,
  }: { ...PaginationOptions, kind: 'creator' | 'participant' },
  { user }: GraphQLContext
) => {
  const currentUser = user;
  const cursor = decode(after);
  // Get the index from the encoded cursor, asdf234gsdf-2 => ["-2", "2"]
  const lastDigits = cursor.match(/-(\d+)$/);
  const lastThreadIndex =
    lastDigits && lastDigits.length > 0 && parseInt(lastDigits[1], 10);
  // if a logged in user is viewing the profile, handle logic to get viewable threads

  let getThreads;
  if (currentUser) {
    getThreads =
      kind === 'creator'
        ? // $FlowIssue
          getViewableThreadsByUser(id, currentUser.id, {
            first,
            after: lastThreadIndex,
          })
        : // $FlowIssue
          getViewableParticipantThreadsByUser(id, currentUser.id, {
            first,
            after: lastThreadIndex,
          });
  } else {
    getThreads =
      kind === 'creator'
        ? // $FlowIssue
          getPublicThreadsByUser(id, { first, after: lastThreadIndex })
        : // $FlowIssue
          getPublicParticipantThreadsByUser(id, {
            first,
            after: lastThreadIndex,
          });
  }

  return getThreads.then(result => ({
    pageInfo: {
      // $FlowFixMe => super weird
      hasNextPage: result && result.length >= first,
    },
    edges: result.map((thread, index) => ({
      cursor: encode(`${thread.id}-${lastThreadIndex + index + 1}`),
      node: thread,
    })),
  }));
};