Repository navigation
Query cache support #3164
|
It would be nice if queries would get out of the box support for caching, it's a pain to make a wrapper since you'd have to make sure the function you create accepts the right types. The syntax could be something like: const users = await client.settings.find({
select: { x: true },
where: { id },
cache: true // defaults to x ms
})
// Custom time
const users = await client.settings.find({
select: { x: true },
where: { id },
cache: 60000 // cache for 1 minute / Maybe an options object for custom cache storage keys?
})The cache could default to memory and a custom solution could be added in schema.prisma datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
datasource cache {
provider = "redis"
url = env("CACHE_URL")
}Any thoughts? |
Replies: 5 comments 4 replies
|
It can be a full-fledged feature request or this can also be a middleware #3107 |
|
We would love to see a caching layer on top of Prisma, any update here? |
This comment was marked as off-topic.
This comment was marked as off-topic.
|
I solved this issue by wrapping a DynamoDB table around my Prisma integrations. This way I get to determine which Prisma DB queries are cached and for how long (TTL). For an e-commerce platform I have a lot of semi-static data like categories and tags, and with Dynamo I cache these for 6 hrs. Example Prisma query function for getting active categories, decorated with DynamoDB caching: import { CACHE_KEY_CATEGORIES } from '../config/constants';
import { get, set } from './dynamo-db-cache';
export const getActiveCategories = async (): Promise<Category[]> => {
const fromCache: any = await get(CACHE_KEY_CATEGORIES);
if (fromCache) {
return fromCache;
}
const data: category[] = await prisma.category.findMany({
orderBy: {
name: 'asc',
},
where: {
visible: {
equals: true,
},
},
});
await set(CACHE_KEY_CATEGORIES, data);
return data;
};Then I would have enabled TTL on my table via Serverless e.g And the DynamoDB cashing and TTL logic: import {
DeleteItemCommand,
DynamoDBClient,
GetItemCommand,
PutItemCommand,
} from '@aws-sdk/client-dynamodb';
import { marshall, unmarshall } from '@aws-sdk/util-dynamodb';
import createHttpError from 'http-errors';
import parse from 'parse-duration';
let client: DynamoDBClient;
export const getClientInstance = (): DynamoDBClient => {
if (client) {
return client;
}
client = new DynamoDBClient({ region: process.env.AWS_REGION });
return client;
};
export const get = async (
pk: string,
client = getClientInstance(),
tableName = process.env.CACHING_TABLE_NAME,
): Promise<any> => {
if (!tableName) {
throw createHttpError(500, {
detail: 'Missing required env var CACHING_TABLE_NAME',
});
}
const command = new GetItemCommand({
TableName: tableName,
Key: marshall({ pk }),
ConsistentRead: true,
});
const data = await client.send(command);
const { Item } = data;
if (!Item) {
return undefined;
}
const exp: string | undefined = Item.ttl.S;
if (exp && hasExpired(exp)) {
await deleteItem(pk);
return undefined;
}
return JSON.parse(unmarshall(Item).response);
};
export const set = async (
pk: string,
response: Record<string, any>,
ttl = '6h',
client = getClientInstance(),
tableName = process.env.CACHING_TABLE_NAME,
): Promise<any> => {
const document = {
pk,
response: JSON.stringify(response),
ttl: getExpiryDate(ttl),
};
const command: PutItemCommand = new PutItemCommand({
TableName: tableName,
Item: marshall(document),
});
try {
await client.send(command);
return response;
} catch (error) {
const { name, message } = error as any;
console.log(`Error setting cache item ${name}`, message);
throw error;
}
};
export const deleteItem = async (
pk: string,
client = getClientInstance(),
tableName = process.env.CACHING_TABLE_NAME,
) => {
const command: DeleteItemCommand = new DeleteItemCommand({
TableName: tableName,
Key: marshall({ pk }),
ConditionExpression: 'attribute_exists(pk)',
});
try {
await client.send(command);
} catch (error) {
console.log('Error removing item from DynamoDb cache table', error);
throw error;
}
};
/**
* Returns expiry timestamp from TTL
* @param {number} ttl e.g '6h'
* @returns {string} e.g "2022-02-15T05:36:06.795Z"
*/
export const getExpiryDate = (ttl: string): string => {
const now = new Date();
now.setSeconds(now.getSeconds() + parse(ttl, 's'));
return now.toISOString();
};
/**
* Examine if the DynamoDB expiresAt field has expired
* We need this check because we cannot rely on DynamoDB to purge automatically (up to 48 hrs latency)
* @param {string} timestamp ISO date string e.g 2022-01-11T11:32:00.000Z
* @param {Date=} now
* @returns {boolean}
*/
export const hasExpired = (timestamp: string, now: Date = new Date()) =>
new Date(timestamp).getTime() < now.getTime(); |
|
Hi there, To keep our discussions organized and focused on the most relevant topics, we’re reviewing and tidying up our backlog. As part of this process, we’re closing discussions that have already been marked as answered but remain open. If this discussion still requires further input or clarification, feel free to reopen it or start a new one with updated details. Your contributions are invaluable to the community, and we’re here to help! For more details about our priorities and vision for the future of Prisma ORM, check out our latest blog post: https://www.prisma.io/blog/prisma-orm-manifesto. Thank you for your understanding and ongoing support of the Prisma community! |
It can be a full-fledged feature request or this can also be a middleware #3107