|
| 1 | +const { InMemoryLRUCache } = require("apollo-server-caching"); |
| 2 | +const DataLoader = require("dataloader"); |
| 3 | + |
| 4 | +class SQLCache { |
| 5 | + constructor(cache = new InMemoryLRUCache(), knex) { |
| 6 | + this.cache = cache; |
| 7 | + this.loader = new DataLoader(rawQueries => |
| 8 | + Promise.all(rawQueries.map(rawQuery => knex.raw(rawQuery))) |
| 9 | + ); |
| 10 | + } |
| 11 | + |
| 12 | + getBatched(query) { |
| 13 | + const queryString = query.toString(); |
| 14 | + return this.loader.load(queryString).then(result => result && result.rows); |
| 15 | + } |
| 16 | + |
| 17 | + getCached(query, ttl) { |
| 18 | + const queryString = query.toString(); |
| 19 | + const cacheKey = `sqlcache:${queryString}`; |
| 20 | + |
| 21 | + return this.cache.get(cacheKey).then(entry => { |
| 22 | + if (entry) return Promise.resolve(entry); |
| 23 | + return query.then(rows => { |
| 24 | + if (rows) this.cache.set(cacheKey, rows, ttl); |
| 25 | + return Promise.resolve(rows); |
| 26 | + }); |
| 27 | + }); |
| 28 | + } |
| 29 | + |
| 30 | + getBatchedAndCached(query, ttl) { |
| 31 | + const queryString = query.toString(); |
| 32 | + const cacheKey = `sqlcache:${queryString}`; |
| 33 | + |
| 34 | + return this.cache.get(cacheKey).then(entry => { |
| 35 | + 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 | + }); |
| 43 | + }); |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +module.exports = SQLCache; |
0 commit comments