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

Using with GraphQL #114

Closed
dtrinh100 opened this issue Aug 5, 2020 · 2 comments
Closed

Using with GraphQL #114

dtrinh100 opened this issue Aug 5, 2020 · 2 comments
Labels

Comments

@dtrinh100
Copy link

dtrinh100 commented Aug 5, 2020

So I tried using this middleware with a graphQL API and I have been getting back a syntax error after the limit has been reached instead of a limit reached message. I am using gqlgen and based on their documentation, I should have been able to use this middleware without any issues, so I am not certain of what is causing my error of:

{
  "error": "JSON.parse: unexpected character at line 1 column 1 of the JSON data"
}

when the limit is reached.

My code looks like this:

      rate, err := limiter.NewRateFromFormatted("5-S")
	if err != nil {
		logger.Panic("Problem setting rate: ", err)
	}

	store := memory.NewStore()

	instance := limiter.New(store, rate)

	middleware := mhttp.NewMiddleware(instance)

	router := chi.NewRouter()

	router.Use(middleware.Handler)

       router.Handle("/graphql", rootResolver)

What should I do in this case?

Update:

This workaround seems to work:

middleware := mhttp.NewMiddleware(instance, mhttp.WithLimitReachedHandler(limitHandler))

func limitHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	w.Write([]byte(`{"message": "Limit Reached!"}`))
}

This seems to return the proper response, but sometimes I see a signal: terminated message in my terminal when the limit has been reached, not sure if this is suppose to happen?

@novln
Copy link
Contributor

novln commented Aug 5, 2020

Hello,

I honestly don't know how GraphQL works and how you should respond, network wise, to propagate an error.
However, you should use WithLimitReachedHandler to override the default implementation.
With the error JSON.parse: unexpected character at line 1 column 1 of the JSON data I'm guessing that GraphQL expect a JSON, which isn't the case in the default handler, we simply return a plain text, that's why you have this error.

For your last point, I have no idea what you're talking about. This error is also cryptic, so without any investigation on your part, I'm afraid I can't help you.

Cheers,

@novln novln added the question label Aug 5, 2020
@novln
Copy link
Contributor

novln commented Aug 25, 2020

Closing since there is no update on this issue.

@novln novln closed this as completed Aug 25, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants