fastify-autoload icon indicating copy to clipboard operation
fastify-autoload copied to clipboard

setNotFoundHandler is not encapsulated when called inside autohooks.js

Open felixmosh opened this issue 2 years ago • 4 comments

Prerequisites

  • [X] I have written a descriptive issue title
  • [X] I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.22.2

Plugin version

4.5.1

Node.js version

18.7

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

20.04

Description

Using autoload & autohooks.js inside a folder, when defining setNotFoundHandler inside autohooks.js, & defining prefix on the autoload options, the defined setNotFoundHandler leaks outside of the prefix.

Steps to Reproduce

Assume the following folder structure.

├── index.ts
├── plugins
│   ├── renderer.ts
│   └── routes.ts
├── routes
│   ├── api
│   │   ├── alive-route.ts
│   │   └── autohooks.ts
│   └── renderer.ts
// plugins/routes.ts
export const routesPlugin: FastifyPluginCallback = async function routesPlugin(instance) {
  instance.route(rendererRoute);

  instance.register(autoload, {
    dir: path.join(__dirname, '../routes/api'),
    forceESM: true,
    autoHooks: true,
    cascadeHooks: true,
    options: { prefix: env.API_PATH }, // this is the autoload prefix its value is `/api`
  });
};
// routes/api/autohooks.ts
const autoHooks: FastifyPluginAsync = async function autoHooks(instance) {
  instance.setNotFoundHandler(() => {
    throw new ActionNotFound();
  });
}

export default autoHooks;

When calling to /api/not-exists it shows the ActionNotFound error (as expected) but, when calling /not-exists it also shows the ActionNotFound error, evenough, the not found handler is defined inside the prefix /api.

I've tried even to add encapsulate: true to autoload options, without luck.

Expected Behavior

From Fastify docs, it specifies that if there is a prefix defined, setNotFoundHandler should be encapsulated to this prefix.

AutoLoad should enforce the same thing.

felixmosh avatar Sep 12 '23 14:09 felixmosh

Thanks for reporting! Would you like to send a Pull Request to address this issue? Remember to add unit tests.

Eomm avatar Nov 12 '23 11:11 Eomm

Are you still interested in fixing this @Eomm?

jean-michelet avatar Mar 11 '24 10:03 jean-michelet

Thank you team🙏🏼

felixmosh avatar May 03 '24 04:05 felixmosh

Sorry, we had to revert this change.

See #380 and #383

jean-michelet avatar Jun 17 '24 08:06 jean-michelet