Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(cache): allow setting custom getKey for defineCachedEventHandler #744

Merged
merged 6 commits into from
Dec 23, 2022
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 11 additions & 12 deletions src/runtime/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,10 +129,7 @@ export interface ResponseCacheEntry<T = any> {
}

export interface CachedEventHandlerOptions<T = any>
extends Omit<
CacheOptions<ResponseCacheEntry<T>>,
"getKey" | "transform" | "validate"
> {
extends Omit<CacheOptions<ResponseCacheEntry<T>>, "transform" | "validate"> {
headersOnly?: boolean;
}

Expand All @@ -142,14 +139,16 @@ export function defineCachedEventHandler<T = any>(
): EventHandler<T> {
const _opts: CacheOptions<ResponseCacheEntry<T>> = {
...opts,
getKey: (event) => {
const url = event.req.originalUrl || event.req.url;
const friendlyName = decodeURI(parseURL(url).pathname)
.replace(/[^\dA-Za-z]/g, "")
.slice(0, 16);
const urlHash = hash(url);
return `${friendlyName}.${urlHash}`;
},
getKey:
opts.getKey ||
((event) => {
const url = event.req.originalUrl || event.req.url;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we can call getKey inside this function? this way if it returns null, we can fallback to the default key behavior.

We also need to escape invalid chars also in all conditions (including ..) as they can lead to security issues.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I think it makes sense to call it inside and fallback to the default; as for the escaping of invalid chars, do you mean escaping them from the returned key?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, to only allow ascii charachters like later regex we have.

const friendlyName = decodeURI(parseURL(url).pathname)
.replace(/[^\dA-Za-z]/g, "")
.slice(0, 16);
const urlHash = hash(url);
return `${friendlyName}.${urlHash}`;
}),
validate: (entry) => {
if (entry.value.code >= 400) {
return false;
Expand Down