1
1
const bsonUrlEncoding = require ( './bsonUrlEncoding' ) ;
2
2
const objectPath = require ( 'object-path' ) ;
3
3
4
+ /**
5
+ * Helper function to encode pagination tokens.
6
+ *
7
+ * NOTE: this function modifies the passed-in `response` argument directly.
8
+ *
9
+ * @param {Object } params
10
+ * * @param {String } paginatedField
11
+ * @param {Object } response The response
12
+ * @param {String? } previous
13
+ * @param {String? } next
14
+ *
15
+ * @returns void
16
+ */
17
+ function encodePaginationTokens ( params , response ) {
18
+ const shouldSecondarySortOnId = params . paginatedField !== '_id' ;
19
+
20
+ if ( response . previous ) {
21
+ const previousPaginatedField = objectPath . get ( response . previous , params . paginatedField ) ;
22
+ if ( shouldSecondarySortOnId ) {
23
+ response . previous = bsonUrlEncoding . encode ( [ previousPaginatedField , response . previous . _id ] ) ;
24
+ } else {
25
+ response . previous = bsonUrlEncoding . encode ( previousPaginatedField ) ;
26
+ }
27
+ }
28
+ if ( response . next ) {
29
+ const nextPaginatedField = objectPath . get ( response . next , params . paginatedField ) ;
30
+ if ( shouldSecondarySortOnId ) {
31
+ response . next = bsonUrlEncoding . encode ( [ nextPaginatedField , response . next . _id ] ) ;
32
+ } else {
33
+ response . next = bsonUrlEncoding . encode ( nextPaginatedField ) ;
34
+ }
35
+ }
36
+ }
37
+
4
38
module . exports = {
5
39
/**
6
40
* Parses the raw results from a find or aggregate query and generates a response object that
@@ -13,7 +47,6 @@ module.exports = {
13
47
*/
14
48
prepareResponse ( results , params ) {
15
49
const hasMore = results . length > params . limit ;
16
- const shouldSecondarySortOnId = params . paginatedField !== '_id' ;
17
50
// Remove the extra element that we added to 'peek' to see if there were more entries.
18
51
if ( hasMore ) results . pop ( ) ;
19
52
@@ -31,26 +64,13 @@ module.exports = {
31
64
hasNext,
32
65
} ;
33
66
34
- if ( response . previous ) {
35
- const previousPaginatedField = objectPath . get ( response . previous , params . paginatedField ) ;
36
- if ( shouldSecondarySortOnId ) {
37
- response . previous = bsonUrlEncoding . encode ( [ previousPaginatedField , response . previous . _id ] ) ;
38
- } else {
39
- response . previous = bsonUrlEncoding . encode ( previousPaginatedField ) ;
40
- }
41
- }
42
- if ( response . next ) {
43
- const nextPaginatedField = objectPath . get ( response . next , params . paginatedField ) ;
44
- if ( shouldSecondarySortOnId ) {
45
- response . next = bsonUrlEncoding . encode ( [ nextPaginatedField , response . next . _id ] ) ;
46
- } else {
47
- response . next = bsonUrlEncoding . encode ( nextPaginatedField ) ;
48
- }
49
- }
67
+ encodePaginationTokens ( params , response ) ;
50
68
51
69
return response ;
52
70
} ,
53
71
72
+ encodePaginationTokens,
73
+
54
74
/**
55
75
* Generates a `$sort` object given the parameters
56
76
*
0 commit comments