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) { super(config); this.cache = config.cache || new InMemoryLRUCache(); } getSQLDate(date: Date): string { return date.toISOString().split('T')[0]; } cachedRaw(query: string): RawBuilder { return new RawBuilder(this.knex, this.cache, query); } }