Add caching possibility to raw queries too
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
import { SQLDataSource } from 'datasource-sql';
|
||||
const { InMemoryLRUCache } = require('apollo-server-caching');
|
||||
import crypto from 'crypto';
|
||||
|
||||
export class BaseSQLDataSource extends SQLDataSource {
|
||||
cache: any;
|
||||
constructor(config) {
|
||||
super(config);
|
||||
this.cache = config.cache || new InMemoryLRUCache();
|
||||
}
|
||||
|
||||
async 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);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user