forked from cvburgess/SQLDataSource
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
55 lines (43 loc) · 1.33 KB
/
index.js
File metadata and controls
55 lines (43 loc) · 1.33 KB
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
const crypto = require("crypto");
const { DataSource } = require("apollo-datasource");
const { InMemoryLRUCache } = require("apollo-server-caching");
const Knex = require("knex");
const knexTinyLogger = require("knex-tiny-logger").default;
const { DEBUG } = process.env;
let hasLogger = false;
class SQLDataSource extends DataSource {
constructor(knexConfig) {
super();
this.context;
this.cache;
this.db = Knex(knexConfig);
const _this = this;
if (!this.db.cache) {
Knex.QueryBuilder.extend("cache", function(ttl) {
return _this.cacheQuery(ttl, this);
});
}
}
initialize(config) {
this.context = config.context;
this.cache = config.cache || new InMemoryLRUCache();
if (DEBUG && !hasLogger) {
hasLogger = true; // Prevent duplicate loggers
knexTinyLogger(this.db); // Add a logging utility for debugging
}
}
cacheQuery(ttl = 5, query) {
const cacheKey = crypto
.createHash("sha1")
.update(query.toString())
.digest("base64");
return this.cache.get(cacheKey).then(entry => {
if (entry) return Promise.resolve(JSON.parse(entry));
return query.then(rows => {
if (rows) this.cache.set(cacheKey, JSON.stringify(rows), { ttl });
return Promise.resolve(rows);
});
});
}
}
module.exports = { SQLDataSource };