如何在 Sinatra 中仅解析一次 JSON 请求正文并将其公开给所有路由? [英] How to parse JSON request body in Sinatra just once and expose it to all routes?

查看:32
本文介绍了如何在 Sinatra 中仅解析一次 JSON 请求正文并将其公开给所有路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 API,它接收一个 JSON 负载作为请求正文.

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

有什么好方法可以将其抽象出来,这样我就不需要为每条路线都这样做?我的一些路由比这更复杂,因此使用这种方法,request.body 会在每条路由中多次重新读取和重新解析,我想避免这种情况.

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.

有什么方法可以让 request_payload 神奇地对路由可用?像这样:

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

推荐答案

在处理程序之前使用 sinatra:

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.

这篇关于如何在 Sinatra 中仅解析一次 JSON 请求正文并将其公开给所有路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆