Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
762 views
in Technique[技术] by (71.8m points)

ruby - How to parse JSON request body in Sinatra just once and expose it to all routes?

I am writing an API and it receives a JSON payload as the request body.

To get at it currently, I am doing something like this:

post '/doSomething' do
    request.body.rewind
    request_payload = JSON.parse request.body.read

    #do something with request_payload
    body request_payload['someKey']
end

What's a good way to abstract this away so that I don't need to do it for each route? Some of my routes are more complicated than this, and as a result the request.body would get reread and reparsed several times per route with this approach, which I want to avoid.

Is there some way to make the request_payload just magically available to routes? Like this:

post '/doSomething' do
    #do something with request_payload, it's already parsed and available
    body request_payload['someKey']
end
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use a sinatra before handler:

before do
  request.body.rewind
  @request_payload = JSON.parse request.body.read
end

this will expose it to the current request handler. If you want it exposed to all handlers, put it in a superclass and extend that class in your handlers.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...