Skip to content

setNotFoundHandler is not encapsulated when called inside autohooks.js #326

@felixmosh

Description

@felixmosh

Prerequisites

  • I have written a descriptive issue title
  • 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workinggood first issueGood for newcomers

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions