-
Notifications
You must be signed in to change notification settings - Fork 3
/
arango-datasource.js
102 lines (91 loc) · 2.31 KB
/
arango-datasource.js
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
const { DataSource } = require('apollo-datasource');
const hash = require('object-hash');
/**
* An ArangoDb implementation of the Apollo DataSource.
*
* @class ArangoDataSource
* @extends {DataSource}
*/
class ArangoDataSource extends DataSource {
/**
* Creates an instance of ArangoDataSource.
* @param {Database} db
* @memberof ArangoDataSource
*/
constructor(db) {
super();
this.db = db;
}
/**
* Initializes the DataSource.
*
* Called at the beginning of each request.
*
* @param {*} config A configuration object that provides access to the shared cache and request context.
* @memberof ArangoDataSource
*/
initialize(config) {
this.cache = config.cache;
}
/**
* Query the database.
*
* Options:
* useCache: check the cache first and update
*
* @param {*} query The query to use
* @returns {*} A list of results that match the query
* @memberof ArangoDataSource
*/
async query(query, { useCache } = { useCache: true }) {
if (useCache) {
const cachedValue = await this.queryCached(query);
if (cachedValue) {
return cachedValue;
}
}
const cursor = await this.db.query(query);
const result = await cursor.all();
if (useCache && result) {
await this.addToCache(query, result);
}
return result;
}
/**
* Compute the key for a given query
*
* @private
* @param {*} query The query to compute the key for
* @returns {string} A string key for the query
* @memberof ArangoDataSource
*/
getCacheKeyForQuery(query) {
return hash(query);
}
/**
* Check the cache for previously saved results for the given query
*
* @private
* @param {*} query The query to check for
* @returns {*} The results saved to the cache
* @memberof ArangoDataSource
*/
async queryCached(query) {
const key = this.getCacheKeyForQuery(query);
return this.cache.get(key);
}
/**
* Add a result set to the cache using the query as a key
*
* @param {*} query The query to key by
* @param {*} result The results to add to the cache
* @memberof ArangoDataSource
*/
async addToCache(query, result) {
const key = this.getCacheKeyForQuery(query);
await this.cache.set(key, result);
}
}
module.exports = {
ArangoDataSource: ArangoDataSource,
};