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

Merge GET and POST parameters whin router parameters #23

Merged
merged 1 commit into from
Aug 1, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 25 additions & 3 deletions lib/web_pipe/conn.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ module WebPipe
class Conn < Dry::Struct
include ConnSupport::Types

# Env's key used to retrieve params set by the router.
#
# @see #router_params
ROUTER_PARAMS_KEY = 'router.params'

# @!attribute [r] env
#
# Rack env hash.
Expand Down Expand Up @@ -260,14 +265,31 @@ def url
request.url
end

# GET and POST params merged in a hash.
# *Params* in rack env's 'router.params' key.
#
# Routers used to map routes to applications build with
# {WebPipe} have the option to introduce extra params through
# setting env's 'router.params' key. These parameters will be
# merged with GET and POST ones when calling {#params}.
#
# This kind of functionality is usually implemented from the
# router side allowing the addition of variables in the route
# definition, e.g.:
#
# @example
# /user/:id/update
def router_params
env.fetch(ROUTER_PARAMS_KEY, Types::EMPTY_HASH)
end

# GET, POST and {#router_params} merged in a hash.
#
# @return [Params]
#
# @example
# { 'id' => 1, 'name' => 'Joe' }
# { 'id' => '1', 'name' => 'Joe' }
def params
request.params
request.params.merge(router_params)
end

# Sets response status code.
Expand Down
31 changes: 30 additions & 1 deletion spec/unit/web_pipe/conn_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,26 @@ def build(env)
end
end

describe '#router_params' do
it "returns env's router.params key" do
env = default_env.merge(
'router.params' => { 'id' => '1' }
)

conn = build(env)

expect(conn.router_params).to eq({ 'id' => '1' })
end

it "returns empty hash when key is not present" do
conn = build(default_env)

expect(conn.router_params).to eq({})
end
end

describe '#params' do
it 'returns request params' do
it 'includes request params' do
env = default_env.merge(
Rack::QUERY_STRING => 'foo=bar'
)
Expand All @@ -74,6 +92,17 @@ def build(env)

expect(conn.params).to eq({ 'foo' => 'bar'})
end

it "includes router params" do
env = default_env.merge(
Rack::QUERY_STRING => 'foo=bar',
'router.params' => { 'id' => '1' }
)

conn = build(env)

expect(conn.params).to eq({ 'foo' => 'bar', 'id' => '1'})
end
end

describe 'set_status' do
Expand Down