adonisjs / transmit

A Server-Sent-Event module for AdonisJS
MIT License
65 stars 4 forks source link

Throttle Configuration in Transmit routeHandlerModifier Results in Error #26

Closed joaosilva0345 closed 2 months ago

joaosilva0345 commented 2 months ago

Package version

1.0.2

Describe the bug

I am facing an issue when using the Transmit package along with the Limiter in AdonisJS 6. Below is a detailed description of the problem and the relevant code:

In the config/transmit.ts file, I am trying to add throttle using the routeHandlerModifier() method as per the documentation:

// config/transmit.ts
import { defineConfig } from '@adonisjs/transmit'
import { throttle } from '#start/limiter'

export default defineConfig({
  pingInterval: false,
  transport: null,
  routeHandlerModifier(route) {
    route.use(throttle)
  },
})

However, on the line route.use(throttle), I am encountering the following error:

TypeError: Cannot read properties of undefined (reading 'define')

   at <anonymous> start\limiter.ts:3
   1|  import limiter from '@adonisjs/limiter/services/main'
   2|  
 > 3|  export const throttle = limiter.define('global', () => {
   4|    return limiter.allowRequests(10).every('1 minute')
   5|  })
   6| 

Below is the code from the start/limiter.ts file:

// start/limiter.ts
import limiter from '@adonisjs/limiter/services/main'

export const throttle = limiter.define('global', () => {
  return limiter.allowRequests(10).every('1 minute')
})

The throttle works perfectly fine on routes defined in start/routes.ts, but when trying to use it in config/transmit.ts, the above error is thrown.

Could you please help me understand what is causing this issue? Is there any modification needed in the code or configuration to resolve this error?

Thank you in advance for your help!

Reproduction repo

No response

RomainLanz commented 2 months ago

Hey @joaosilva0345! 👋🏻

Import limiter inside the callback, not at the top of the file.

thetutlage commented 2 months ago

@RomainLanz How about removing the route configuration from the config file and instead provide a programmatic API for the same? Something like.

transmit.configureRoute((route) => {
})

This way this code could live in start/transmit.ts file

RomainLanz commented 2 months ago

Yeah, that would be a nice addition

joaosilva0345 commented 2 months ago

Hey @joaosilva0345! 👋🏻

Import limiter inside the callback, not at the top of the file.

Hi Thank you for the solution! I followed your suggestion to import the limiter inside the callback, and it worked perfectly.

I really thought I had already tested this approach, but I was mistaken. I went through several different attempts at solutions, and the correct one was right in front of me.

Thank you again for your help!