From 2b57afbc4aa3260892ac27d74b1dd5fdb2c335df Mon Sep 17 00:00:00 2001 From: Niklas Fondberg Date: Thu, 8 Apr 2021 16:17:33 +0200 Subject: [PATCH] Add caching possibility to raw queries too --- src/datasources/BaseSQLDataSource.ts | 32 ++++++++++++++++++++++++++++ src/datasources/order-api.ts | 15 +++++++------ 2 files changed, 41 insertions(+), 6 deletions(-) create mode 100644 src/datasources/BaseSQLDataSource.ts diff --git a/src/datasources/BaseSQLDataSource.ts b/src/datasources/BaseSQLDataSource.ts new file mode 100644 index 0000000..9d3fd8e --- /dev/null +++ b/src/datasources/BaseSQLDataSource.ts @@ -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); + }); + }); + } +} diff --git a/src/datasources/order-api.ts b/src/datasources/order-api.ts index 09e39bf..8dda540 100644 --- a/src/datasources/order-api.ts +++ b/src/datasources/order-api.ts @@ -1,4 +1,4 @@ -import { SQLDataSource } from 'datasource-sql'; +import { BaseSQLDataSource } from './BaseSQLDataSource'; import { camelcase } from 'stringcase'; import { Address, @@ -10,7 +10,8 @@ import { import { Maybe } from './types'; const MINUTE = 60; -export class OrderAPI extends SQLDataSource { +export class OrderAPI extends BaseSQLDataSource { + cache: any; constructor(config) { super(config); } @@ -100,10 +101,12 @@ export class OrderAPI extends SQLDataSource { } async getOrderRows(orderId: number): Promise> { - // const fields = await this.knex.select('*').from('order-row_fields'); - const fieldsRes = await this.knex - .raw('SELECT * from "order-row_fields"') - .then((data) => data.rows); + const fieldsRes = await this.cacheQuery( + 120, + this.knex + .raw('SELECT * from "order-row_fields"') + .then((data) => data.rows), + ); const fields = fieldsRes.reduce((obj, item) => { obj[item.fieldid] = item.name;