Skip to content

Commit 9b7639d

Browse files
tab00cvburgess
authored andcommitted
Added check for database client in getBatched() (#11)
- Fix for responses from sqlite and mssql drivers [#9]
1 parent 410b33b commit 9b7639d

File tree

4 files changed

+1050
-688
lines changed

4 files changed

+1050
-688
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
# Changelog
22

3+
## v0.1.7 - 24-04-2019
4+
5+
- Fix for responses from sqlite and mssql drivers [#9]
6+
37
## v0.1.6 - 05-04-2019
48

59
- Fix issue setting TTL on cache requests [#15]

SQLCache.js

Lines changed: 32 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,42 @@ const DataLoader = require("dataloader");
44
class SQLCache {
55
constructor(cache = new InMemoryLRUCache(), knex) {
66
this.cache = cache;
7+
this.knex = knex;
78
this.loader = new DataLoader(rawQueries =>
89
Promise.all(rawQueries.map(rawQuery => knex.raw(rawQuery)))
910
);
1011
}
1112

13+
normalizeDBResult(result) {
14+
switch (this.knex.client) {
15+
case "postgres":
16+
return result && result.rows;
17+
case "mssql":
18+
return result;
19+
case "sqlite3":
20+
return result;
21+
// TODO: Test and implement remaining clients
22+
case "mysql":
23+
case "mysql2":
24+
case "oracledb":
25+
case "redshift":
26+
default:
27+
return result;
28+
}
29+
}
30+
31+
getCacheKeyForQuery(query) {
32+
const queryString = query.toString();
33+
return `sqlcache:${queryString}`;
34+
}
35+
1236
getBatched(query) {
1337
const queryString = query.toString();
14-
return this.loader.load(queryString).then(result => result && result.rows);
38+
return this.loader.load(queryString).then(this.normalizeDBResult);
1539
}
1640

1741
getCached(query, ttl) {
18-
const queryString = query.toString();
19-
const cacheKey = `sqlcache:${queryString}`;
42+
const cacheKey = this.getCacheKeyForQuery(query);
2043

2144
return this.cache.get(cacheKey).then(entry => {
2245
if (entry) return Promise.resolve(entry);
@@ -28,18 +51,15 @@ class SQLCache {
2851
}
2952

3053
getBatchedAndCached(query, ttl) {
31-
const queryString = query.toString();
32-
const cacheKey = `sqlcache:${queryString}`;
54+
const cacheKey = this.getCacheKeyForQuery(query);
3355

3456
return this.cache.get(cacheKey).then(entry => {
3557
if (entry) return Promise.resolve(entry);
36-
return this.loader
37-
.load(queryString)
38-
.then(result => result && result.rows)
39-
.then(rows => {
40-
if (rows) this.cache.set(cacheKey, rows, { ttl });
41-
return Promise.resolve(rows);
42-
});
58+
59+
return this.getBatched(query).then(rows => {
60+
if (rows) this.cache.set(cacheKey, rows, { ttl });
61+
return Promise.resolve(rows);
62+
});
4363
});
4464
}
4565
}

0 commit comments

Comments
 (0)