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);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { SQLDataSource } from 'datasource-sql';
|
import { BaseSQLDataSource } from './BaseSQLDataSource';
|
||||||
import { camelcase } from 'stringcase';
|
import { camelcase } from 'stringcase';
|
||||||
import {
|
import {
|
||||||
Address,
|
Address,
|
||||||
@@ -10,7 +10,8 @@ import {
|
|||||||
import { Maybe } from './types';
|
import { Maybe } from './types';
|
||||||
|
|
||||||
const MINUTE = 60;
|
const MINUTE = 60;
|
||||||
export class OrderAPI extends SQLDataSource {
|
export class OrderAPI extends BaseSQLDataSource {
|
||||||
|
cache: any;
|
||||||
constructor(config) {
|
constructor(config) {
|
||||||
super(config);
|
super(config);
|
||||||
}
|
}
|
||||||
@@ -100,10 +101,12 @@ export class OrderAPI extends SQLDataSource {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async getOrderRows(orderId: number): Promise<Array<OrderRow>> {
|
async getOrderRows(orderId: number): Promise<Array<OrderRow>> {
|
||||||
// const fields = await this.knex.select('*').from('order-row_fields');
|
const fieldsRes = await this.cacheQuery(
|
||||||
const fieldsRes = await this.knex
|
120,
|
||||||
|
this.knex
|
||||||
.raw('SELECT * from "order-row_fields"')
|
.raw('SELECT * from "order-row_fields"')
|
||||||
.then((data) => data.rows);
|
.then((data) => data.rows),
|
||||||
|
);
|
||||||
|
|
||||||
const fields = fieldsRes.reduce((obj, item) => {
|
const fields = fieldsRes.reduce((obj, item) => {
|
||||||
obj[item.fieldid] = item.name;
|
obj[item.fieldid] = item.name;
|
||||||
|
|||||||
Reference in New Issue
Block a user