Skip to content

Commit 3f36093

Browse files
authored
Refactor parser/deserialization (jsonapi-rb#23)
Use before_action instead of middleware for deserialization.
1 parent dc373eb commit 3f36093

File tree

3 files changed

+11
-29
lines changed

3 files changed

+11
-29
lines changed

lib/jsonapi/rails/action_controller.rb

Lines changed: 5 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -32,29 +32,13 @@ def deserializable_relationship(key, options = {}, &block)
3232
def _deserializable(key, options, fallback, &block)
3333
options = options.dup
3434
klass = options.delete(:class) || Class.new(fallback, &block)
35-
use Deserialization, key, klass, options
36-
end
37-
end
3835

39-
class Deserialization
40-
REQUEST_PARAMETERS_KEY =
41-
'action_dispatch.request.request_parameters'.freeze
42-
def initialize(app, key, klass)
43-
@app = app
44-
@deserializable_key = key
45-
@deserializable_class = klass
46-
end
47-
48-
def call(env)
49-
request = Rack::Request.new(env)
50-
body = JSON.parse(request.body.read)
51-
deserializable = @deserializable_class.new(body)
52-
env[REVERSE_MAPPING_KEY] = deserializable.reverse_mapping
53-
(env[REQUEST_PARAMETERS_KEY] ||= {}).tap do |request_parameters|
54-
request_parameters[@deserializable_key] = deserializable.to_hash
36+
before_action(options) do |controller|
37+
resource = klass.new(controller.params[:_jsonapi].to_unsafe_hash)
38+
controller.request.env[REVERSE_MAPPING_KEY] =
39+
resource.reverse_mapping
40+
controller.params[key.to_sym] = resource.to_hash
5541
end
56-
57-
@app.call(env)
5842
end
5943
end
6044
end

lib/jsonapi/rails/parser.rb

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
1+
require 'jsonapi/deserializable'
2+
13
module JSONAPI
24
module Rails
3-
module_function
5+
PARSER = lambda do |body|
6+
data = JSON.parse(body)
7+
hash = { _jsonapi: data }
48

5-
def parser
6-
lambda do |body|
7-
data = JSON.parse(body)
8-
data = { _json: data } unless data.is_a?(Hash)
9-
data.with_indifferent_access
10-
end
9+
hash.with_indifferent_access
1110
end
1211
end
1312
end

lib/jsonapi/rails/railtie.rb

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ module JSONAPI
99
module Rails
1010
class Railtie < ::Rails::Railtie
1111
MEDIA_TYPE = 'application/vnd.api+json'.freeze
12-
PARSER = JSONAPI::Rails.parser
1312
RENDERERS = {
1413
jsonapi: JSONAPI::Rails.rails_renderer(SuccessRenderer),
1514
jsonapi_error: JSONAPI::Rails.rails_renderer(ErrorRenderer)

0 commit comments

Comments
 (0)