hapi icon indicating copy to clipboard operation
hapi copied to clipboard

Issue with authentication option on Routes from an external module

Open tomcphr opened this issue 3 years ago • 3 comments

Support plan

  • is this issue currently blocking your project? (yes/no): no
  • is this issue affecting a production system? (yes/no): no

Context

  • node version: 16.18.1
  • module version with issue: Hapi 21.1.0
  • last module version without issue: Unsure
  • environment (e.g. node, browser, native): Node
  • used with (e.g. hapi application, another framework, standalone, ...): TypeScript
  • any other relevant information: I can get this to currently work by defining the auth parameter as such false as const but I'm not sure if that's the right thing to do or not.

What are you trying to achieve or the steps to reproduce?

Define multiple routes in an external module via an array of ServerRoute-like objects and disable authentication on specific routes

index.ts

import * as Hapi from '@hapi/hapi';
import Routes from './Routes';

const hapi = Hapi.server({port: 5000});
hapi.route(Routes);
hapi.start();

routes.ts

export default [
    {
        method: 'GET',
        path: '/users',
        handler: () => {}
    },
    {
        method: 'POST',
        path: '/users/login',
        handler: () => {},
        options: {
            auth: false
        }
    },
];

What was the result you got?

When compiling the TypeScript to JavaScript, TSC gives this error:

Types of property 'auth' are incompatible.
Type 'boolean' is not assignable to type 'string | false | RouteOptionsAccess'.

image

What result did you expect?

No type issue. The routes setup successfully.

tomcphr avatar Dec 29 '22 11:12 tomcphr

For now you might work around this by telling the type system that you intend to specifically pass false and not a boolean:

    options: {
        auth: false as const
    }

Part of the issue here is that typescript is doing its best to infer the type of the export. If you give it a little information, this is another way to address the issue:

const routes: ServerRoute[] = [/* ... */]
export default routes

devinivy avatar Dec 29 '22 14:12 devinivy

Thanks for the reply @devinivy

Defining the type in the module seems to be the best solution, is there a way to fix this in the definitions or is it just a TypeScript "issue"

tomcphr avatar Dec 29 '22 22:12 tomcphr

It is typescript's normal behavior, I don't see an obvious fix for this. You could put the as const on the whole array but you might run into other problems then.

Marsup avatar Jan 03 '23 17:01 Marsup