lib/jsonapionify/api/server/request.rb in jsonapionify-0.9.0 vs lib/jsonapionify/api/server/request.rb in jsonapionify-0.9.1
- old
+ new
@@ -1,8 +1,9 @@
require 'rack/request'
require 'rack/utils'
require 'rack/mock'
+require 'mime-types'
module JSONAPIonify::Api
class Server::Request < Rack::Request
def self.env_for(url, method, options = {})
options[:method] = method
@@ -13,11 +14,11 @@
env_headers = env.select do |name, _|
name.start_with?('HTTP_') && !%w{HTTP_VERSION}.include?(name)
end.each_with_object({}) do |(name, value), hash|
hash[name[5..-1].gsub('_', '-').downcase] = value
end
- env_headers['content-type'] = content_type
+ env_headers['content-type'] = content_type if content_type
Rack::Utils::HeaderHash.new(env_headers)
end
def http_string
# GET /path/file.html HTTP/1.0
@@ -42,24 +43,37 @@
value
ensure
body.rewind
end
+ def extension
+ ext = File.extname(path)
+ return nil unless ext
+ ext = ext[0] == '.' ? ext[1..-1] : ext
+ ext.to_s.empty? ? nil : ext
+ end
+
def content_type
super.try(:split, ';').try(:first)
end
- def accept
- accepts = (headers['accept'] || '*/*').split(',')
- accepts.to_a.sort_by! do |accept|
- _, *media_type_params = accept.split(';')
- rqf = media_type_params.find { |mtp| mtp.start_with? 'q=' }
- -(rqf ? rqf[2..-1].to_f : 1.0)
- end.map do |accept|
- mime, *media_type_params = accept.split(';')
- media_type_params.reject! { |mtp| mtp.start_with? 'q=' }
- [mime, *media_type_params].join(';')
+ def accept_params
+ @accept_params ||= begin
+ ext_mime = MIME::Types.type_for(path)[0]&.content_type
+ accepts = (headers['accept'] || ext_mime || '*/*').split(',')
+ types = [ext_mime].compact | accepts
+ types.each_with_object({}) do |type, list|
+ list[Server::MediaType.type(type)] = Server::MediaType.params(type)
+ end
end
+ end
+
+ def jsonapi_params
+ accept_params['application/vnd.api+json'] || {}
+ end
+
+ def accept
+ @accept ||= accept_params.keys
end
def authorizations
parts = headers['authorization'].to_s.split(' ')
parts.length == 2 ? Rack::Utils::HeaderHash.new([parts].to_h) : {}