Cleanup of code

This commit is contained in:
Niklas Fondberg
2021-07-07 17:11:37 +02:00
parent 267bc4f1c9
commit 32adee1bf4
5 changed files with 54 additions and 39 deletions
+34 -19
View File
@@ -2,6 +2,38 @@ import { SQLDataSource } from 'datasource-sql';
const { InMemoryLRUCache } = require('apollo-server-caching');
import crypto from 'crypto';
const MINUTE = 60;
export class RawBuilder {
_cache: any;
query: any;
constructor(knex, cache, query) {
this._cache = cache;
this.query = knex.raw(query);
}
async cache(ttl: number) {
const cacheKey = crypto
.createHash('sha1')
.update(this.query.toString())
.digest('base64');
return this._cache.get(cacheKey).then((entry) => {
if (entry) {
return Promise.resolve(JSON.parse(entry));
}
return this.query.then((rows) => {
if (rows) {
this._cache.set(cacheKey, JSON.stringify(rows), { ttl });
}
return Promise.resolve(rows);
});
});
}
}
export class BaseSQLDataSource extends SQLDataSource {
cache: any;
constructor(config) {
@@ -13,24 +45,7 @@ export class BaseSQLDataSource extends SQLDataSource {
return date.toISOString().split('T')[0];
}
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);
});
});
cachedRaw(query: string): RawBuilder {
return new RawBuilder(this.knex, this.cache, query);
}
}