2
2
3
3
RethinkDb offers a batching method called ` getAll ` but there are a few caveats :
4
4
* Order of results is not guaranteed ([ rethinkdb/rethinkdb #5187 ] ( https://github.com/rethinkdb/rethinkdb/issues/5187 ) )
5
- * Non-existent keys will not return and empty record
6
- Assuming a table ` example_table ` with those records :
5
+ * Non-existent keys will not return an empty record
6
+
7
+ For example, against a table ` example_table ` with these records:
7
8
``` js
8
9
[
9
10
{" id" : 1 , " name" : " Document 1" },
10
11
{" id" : 2 , " name" : " Document 2" }
11
12
]
12
13
```
13
- A query ` r.getAll(1, 2, 3) ` could return such an array :
14
+ A query ` r.getAll(1, 2, 3) ` could return:
14
15
``` js
15
16
[
16
17
{" id" : 2 , " name" : " Document 2" },
17
18
{" id" : 1 , " name" : " Document 1" }
18
19
]
19
20
```
20
21
21
- In essence , this naive implementation won't work :
22
+ Because query keys and values are associated by position in the dataloader cache , this naive implementation won't work (with the same table as above) :
22
23
``` js
23
24
var r = require (' rethinkdb' );
24
25
var db = await r .connect ();
25
26
26
27
var batchLoadFn = keys => db .table (' example_table' ).getAll (... keys).then (res => res .toArray ());
27
28
var exampleLoader = new DataLoader (batchLoadFn);
28
29
29
- await exampleLoader .loadMany ([1 , 2 , 3 ]); // Throws, values length !== keys length
30
+ await exampleLoader .loadMany ([1 , 2 , 3 ]); // Throws values length !== keys length
30
31
31
32
await exampleLoader .loadMany ([1 , 2 ]);
32
33
await exampleLoader .load (1 ); // {"id": 2, "name": "Document 2"}
33
34
```
34
35
35
36
A solution is to normalize results returned by ` getAll ` to match the structure of supplied ` keys ` .
36
37
37
- To achieve this efficiently, we first write an indexing function. This function will return a Map indexing results.
38
- Parameters :
39
- * ` results ` : Array of RethinkDb results
40
- * ` indexField ` : String indicating which field was used as index for this batch query
41
- * ` cacheKeyFn ` : Optional function used to serialize non-scalar index field values
38
+ To achieve this efficiently, we first write an indexing function. This function will return a ` Map ` indexing results.
39
+ Parameters:
40
+ * ` results ` : Array of RethinkDb results
41
+ * ` indexField ` : String indicating which field was used as index for this batch query
42
+ * ` cacheKeyFn ` : Optional function used to serialize non-scalar index field values
42
43
``` js
43
44
function indexResults (results , indexField , cacheKeyFn = key => key ) {
44
45
var indexedResults = new Map ();
@@ -58,7 +59,7 @@ function normalizeRethinkDbResults(keys, indexField, cacheKeyFn = key => key) {
58
59
}
59
60
```
60
61
61
- Full dataloader implementation :
62
+ Full dataloader implementation:
62
63
``` js
63
64
var r = require (' rethinkdb' );
64
65
var db = await r .connect ();
0 commit comments