Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
require 'json'
module Middlewares
class Mentekun
CONFIG = {
users: {
read: [
{ methods: [:get], path: '/api/users' },
{ methods: [:get], path: %r{/api/users/\d+} },
],
write: [
{ methods: [:post], path: '/api/users' },
{ methods: [:put, :delete], path: '%r{/api/users/\d+}' }
]
},
articles: {
read: [
{ methods: [:get], path: '/api/articles' },
{ methods: [:get], path: %r{/api/articles/\d+} },
],
write: [
{ methods: [:post], path: '/api/articles' },
{ methods: [:put, :delete], path: '%r{/api/articles/\d+}' }
]
},
}
DEFAULT = {
status: 500,
content_type: 'application/json',
body: { error: 'not in service' }.to_json
}
def initialize(app)
@app = app
end
def call(env)
method = env['REQUEST_METHOD'].downcase.to_sym
path = env['PATH_INFO']
mr = maintenance_renponse(method, path)
if mr.length.positive?
return [
DEFAULT[:status],
{ "Content-Type" => DEFAULT[:content_type], 'Content-Length' => DEFAULT[:body].bytesize.to_s },
[DEFAULT[:body]]
]
end
@app.call(env)
end
private
# モック実装
def enabled_mainte_mode
[:users_all, :articles_write]
end
def maintenance_renponse(method, path)
enabled_cfg = if enabled_mainte_mode.include? :all
CONFIG.values.inject([]) do |a, p|
a + p.values
end
else
enabled_mainte_mode.inject([]) do |a, mode|
resource, action = *mode.to_s.split('_').map(&:to_sym)
if action == :all
a + CONFIG[resource].values
else
a + CONFIG[resource][action]
end
end
end
enabled_cfg.flatten!
enabled_cfg.select do |c|
c[:methods].include?(method) && (c[:path] == path || c[:path].match(path))
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment