@@ -4,19 +4,42 @@ const DataLoader = require("dataloader");
44class 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