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

defineCachedFunction ignores function name #3019

Open
IlyaSemenov opened this issue Jan 24, 2025 · 0 comments
Open

defineCachedFunction ignores function name #3019

IlyaSemenov opened this issue Jan 24, 2025 · 0 comments

Comments

@IlyaSemenov
Copy link

Environment

nitropack 2.10.4

Reproduction

https://stackblitz.com/edit/github-9uizvfes?file=server%2Froutes%2Findex.ts

Misbehaving code from the repro:

async function _foo() {
  return 'FOO';
}

const foo = defineCachedFunction(_foo);

async function _bar() {
  await new Promise((resolve) => setTimeout(resolve, 1));
  return 'BAR';
}

const bar = defineCachedFunction(_bar);

async function main() {
  // Expected: FOO BAR
  // Actual result: FOO FOO
  console.log(await foo());
  await new Promise((resolve) => setTimeout(resolve, 100));
  console.log(await bar());
}

main();

Describe the bug

defineCachedFunction is supposed to guess cache key from the function name, and only use _ as a fall back:

Guessed from function name if not provided, and falls back to '_' otherwise.

However, name is never taken from the function, _ is always used. This is due to bug where the default is taken before looking up function name:

opts = { ...defaultCacheOptions(), ...opts };
const pending: { [key: string]: Promise<T> } = {};
// Normalize cache params
const group = opts.group || "nitro/functions";
const name = opts.name || fn.name || "_";

As you can see opts.name is taken first, which comes from defaultCacheOptions(), which always returns { name: "_" }.

function defaultCacheOptions() {
return {
name: "_",
base: "/cache",
swr: true,
maxAge: 1,
} as const;
}

Additional context

No response

Logs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants