|
1 | 1 | import binascii |
| 2 | +from typing import Any, Collection, Optional, TypeVar |
2 | 3 |
|
3 | 4 | from ..utils.base64 import base64, unbase64 |
4 | | -from .connectiontypes import Connection, PageInfo, Edge |
| 5 | +from .connectiontypes import ( |
| 6 | + Connection, ConnectionArguments, ConnectionCursor, Edge, PageInfo) |
5 | 7 |
|
| 8 | +__all__ = [ |
| 9 | + 'connection_from_array', 'connection_from_array_slice', |
| 10 | + 'cursor_for_object_in_connection', 'cursor_to_offset', |
| 11 | + 'get_offset_with_default', 'offset_to_cursor' |
| 12 | +] |
6 | 13 |
|
7 | | -def connection_from_list( |
8 | | - data, args=None, |
9 | | - connection_type=None, edge_type=None, pageinfo_type=None): |
10 | | - """ |
11 | | - A simple function that accepts an array and connection arguments, and returns |
12 | | - a connection object for use in GraphQL. It uses array offsets as pagination, |
13 | | - so pagination will only work if the array is static. |
| 14 | +T = TypeVar('T') |
| 15 | + |
| 16 | + |
| 17 | +def connection_from_array( |
| 18 | + data: Collection, args: ConnectionArguments) -> Connection: |
| 19 | + """Create a connection argument from a collection. |
| 20 | +
|
| 21 | + A simple function that accepts a collection (e.g. a Python list) and connection |
| 22 | + arguments, and returns a connection object for use in GraphQL. It uses array |
| 23 | + offsets as pagination, so pagination will only work if the array is static. |
14 | 24 | """ |
15 | | - _len = len(data) |
16 | | - return connection_from_list_slice( |
17 | | - data, |
18 | | - args, |
19 | | - connection_type=connection_type, |
20 | | - edge_type=edge_type, |
21 | | - pageinfo_type=pageinfo_type, |
| 25 | + return connection_from_array_slice( |
| 26 | + data, args, |
22 | 27 | slice_start=0, |
23 | | - list_length=_len, |
24 | | - list_slice_length=_len, |
| 28 | + array_length=len(data), |
25 | 29 | ) |
26 | 30 |
|
27 | 31 |
|
28 | | -def connection_from_list_slice( |
29 | | - list_slice, args=None, |
30 | | - connection_type=None, edge_type=None, pageinfo_type=None, |
31 | | - slice_start=0, list_length=0, list_slice_length=None): |
32 | | - """ |
33 | | - Given a slice (subset) of an array, returns a connection object for use in |
34 | | - GraphQL. |
35 | | - This function is similar to `connectionFromArray`, but is intended for use |
| 32 | +def connection_from_array_slice( |
| 33 | + array_slice: Collection, args: ConnectionArguments, |
| 34 | + slice_start: int, array_length: int |
| 35 | + ) -> Connection: |
| 36 | + """Given a slice of a collection, returns a connection object for use in GraphQL. |
| 37 | +
|
| 38 | + This function is similar to `connection_from_array`, but is intended for use |
36 | 39 | cases where you know the cardinality of the connection, consider it too large |
37 | | - to materialize the entire array, and instead wish pass in a slice of the |
| 40 | + to materialize the entire collection, and instead wish pass in a slice of the |
38 | 41 | total result large enough to cover the range specified in `args`. |
39 | 42 | """ |
40 | | - connection_type = connection_type or Connection |
41 | | - edge_type = edge_type or Edge |
42 | | - pageinfo_type = pageinfo_type or PageInfo |
43 | | - |
44 | | - args = args or {} |
45 | | - |
46 | 43 | before = args.get('before') |
47 | 44 | after = args.get('after') |
48 | 45 | first = args.get('first') |
49 | 46 | last = args.get('last') |
50 | | - if list_slice_length is None: |
51 | | - list_slice_length = len(list_slice) |
52 | | - slice_end = slice_start + list_slice_length |
53 | | - before_offset = get_offset_with_default(before, list_length) |
| 47 | + slice_end = slice_start + len(array_slice) |
| 48 | + before_offset = get_offset_with_default(before, array_length) |
54 | 49 | after_offset = get_offset_with_default(after, -1) |
55 | 50 |
|
56 | | - start_offset = max( |
57 | | - slice_start - 1, |
58 | | - after_offset, |
59 | | - -1 |
60 | | - ) + 1 |
61 | | - end_offset = min( |
62 | | - slice_end, |
63 | | - before_offset, |
64 | | - list_length |
65 | | - ) |
| 51 | + start_offset = max(slice_start - 1, after_offset, -1) + 1 |
| 52 | + end_offset = min(slice_end, before_offset, array_length) |
| 53 | + |
66 | 54 | if isinstance(first, int): |
67 | | - end_offset = min( |
68 | | - end_offset, |
69 | | - start_offset + first |
70 | | - ) |
| 55 | + if first < 0: |
| 56 | + raise ValueError("Argument 'first' must be a non-negative integer.") |
| 57 | + |
| 58 | + end_offset = min(end_offset, start_offset + first) |
71 | 59 | if isinstance(last, int): |
72 | | - start_offset = max( |
73 | | - start_offset, |
74 | | - end_offset - last |
75 | | - ) |
| 60 | + if last < 0: |
| 61 | + raise ValueError("Argument 'last' must be a non-negative integer.") |
| 62 | + |
| 63 | + start_offset = max(start_offset, end_offset - last) |
76 | 64 |
|
77 | 65 | # If supplied slice is too large, trim it down before mapping over it. |
78 | | - _slice = list_slice[ |
| 66 | + trimmed_slice = array_slice[ |
79 | 67 | max(start_offset - slice_start, 0): |
80 | | - list_slice_length - (slice_end - end_offset) |
| 68 | + len(array_slice) - (slice_end - end_offset) |
81 | 69 | ] |
| 70 | + |
82 | 71 | edges = [ |
83 | | - edge_type( |
84 | | - node=node, |
85 | | - cursor=offset_to_cursor(start_offset + i) |
| 72 | + Edge( |
| 73 | + node=value, |
| 74 | + cursor=offset_to_cursor(start_offset + index) |
86 | 75 | ) |
87 | | - for i, node in enumerate(_slice) |
| 76 | + for index, value in enumerate(trimmed_slice) |
88 | 77 | ] |
89 | 78 |
|
90 | 79 | first_edge_cursor = edges[0].cursor if edges else None |
91 | 80 | last_edge_cursor = edges[-1].cursor if edges else None |
92 | 81 | lower_bound = after_offset + 1 if after else 0 |
93 | | - upper_bound = before_offset if before else list_length |
| 82 | + upper_bound = before_offset if before else array_length |
94 | 83 |
|
95 | | - return connection_type( |
| 84 | + return Connection( |
96 | 85 | edges=edges, |
97 | | - page_info=pageinfo_type( |
98 | | - start_cursor=first_edge_cursor, |
99 | | - end_cursor=last_edge_cursor, |
100 | | - has_previous_page=isinstance(last, int) and start_offset > lower_bound, |
101 | | - has_next_page=isinstance(first, int) and end_offset < upper_bound |
| 86 | + pageInfo=PageInfo( |
| 87 | + startCursor=first_edge_cursor, |
| 88 | + endCursor=last_edge_cursor, |
| 89 | + hasPreviousPage=isinstance(last, int) and start_offset > lower_bound, |
| 90 | + hasNextPage=isinstance(first, int) and end_offset < upper_bound |
102 | 91 | ) |
103 | 92 | ) |
104 | 93 |
|
105 | 94 |
|
106 | 95 | PREFIX = 'arrayconnection:' |
107 | 96 |
|
108 | 97 |
|
109 | | -def offset_to_cursor(offset): |
110 | | - """ |
111 | | - Creates the cursor string from an offset. |
112 | | - """ |
113 | | - return base64(PREFIX + str(offset)) |
| 98 | +def offset_to_cursor(offset: int) -> ConnectionCursor: |
| 99 | + """Create the cursor string from an offset.""" |
| 100 | + return base64(f"{PREFIX}{offset}") |
114 | 101 |
|
115 | 102 |
|
116 | | -def cursor_to_offset(cursor): |
117 | | - """ |
118 | | - Rederives the offset from the cursor string. |
119 | | - """ |
| 103 | +def cursor_to_offset(cursor: ConnectionCursor) -> Optional[int]: |
| 104 | + """Rederive the offset from the cursor string.""" |
120 | 105 | try: |
121 | 106 | return int(unbase64(cursor)[len(PREFIX):]) |
122 | 107 | except binascii.Error: |
123 | 108 | return None |
124 | 109 |
|
125 | 110 |
|
126 | | -def cursor_for_object_in_connection(data, _object): |
127 | | - """ |
128 | | - Return the cursor associated with an object in an array. |
129 | | - """ |
130 | | - if _object not in data: |
| 111 | +def cursor_for_object_in_connection(data: Collection, obj: T) -> Optional[Any]: |
| 112 | + """Return the cursor associated with an object in a collection.""" |
| 113 | + try: |
| 114 | + # noinspection PyUnresolvedReferences |
| 115 | + offset = data.index(obj) # type: ignore |
| 116 | + except AttributeError: # collection does not have an index method |
| 117 | + for offset, value in data: |
| 118 | + if value == obj: |
| 119 | + return offset |
| 120 | + return None |
| 121 | + except ValueError: |
131 | 122 | return None |
| 123 | + else: |
| 124 | + return offset_to_cursor(offset) |
132 | 125 |
|
133 | | - offset = data.index(_object) |
134 | | - return offset_to_cursor(offset) |
135 | 126 |
|
| 127 | +def get_offset_with_default(cursor: ConnectionCursor = None, default_offset=0) -> int: |
| 128 | + """Get offset from a given cursor and a default. |
136 | 129 |
|
137 | | -def get_offset_with_default(cursor=None, default_offset=0): |
138 | | - """ |
139 | | - Given an optional cursor and a default offset, returns the offset |
140 | | - to use; if the cursor contains a valid offset, that will be used, |
| 130 | + Given an optional cursor and a default offset, return the offset to use; |
| 131 | + if the cursor contains a valid offset, that will be used, |
141 | 132 | otherwise it will be the default. |
142 | 133 | """ |
143 | 134 | if not isinstance(cursor, str): |
144 | 135 | return default_offset |
145 | 136 |
|
146 | 137 | offset = cursor_to_offset(cursor) |
147 | | - try: |
148 | | - return int(offset) |
149 | | - except (TypeError, ValueError): |
150 | | - return default_offset |
| 138 | + return default_offset if offset is None else offset |
0 commit comments