|
| 1 | +# frozen_string_literal: true |
| 2 | +# |
| 3 | +# Copyright, 2019, by Samuel G. D. Williams. <http://www.codeotaku.com> |
| 4 | +# |
| 5 | +# Permission is hereby granted, free of charge, to any person obtaining a copy |
| 6 | +# of this software and associated documentation files (the "Software"), to deal |
| 7 | +# in the Software without restriction, including without limitation the rights |
| 8 | +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 9 | +# copies of the Software, and to permit persons to whom the Software is |
| 10 | +# furnished to do so, subject to the following conditions: |
| 11 | +# |
| 12 | +# The above copyright notice and this permission notice shall be included in |
| 13 | +# all copies or substantial portions of the Software. |
| 14 | +# |
| 15 | +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 16 | +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 17 | +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 18 | +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 19 | +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 20 | +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 21 | +# THE SOFTWARE. |
| 22 | + |
| 23 | +require_relative '../protocol' |
| 24 | + |
| 25 | +module Async |
| 26 | + module HTTP |
| 27 | + module Mock |
| 28 | + class Cache |
| 29 | + Key = Struct.new(:method, :authority, :path, :headers, :body) do |
| 30 | + def self.for(request) |
| 31 | + self.new(request.method, request.authority, request.path, request.headers, request.body) |
| 32 | + end |
| 33 | + end |
| 34 | + |
| 35 | + def initialize(store = {}) |
| 36 | + @internet = Async::HTTP::Internet.new |
| 37 | + @store = store |
| 38 | + end |
| 39 | + |
| 40 | + attr :store |
| 41 | + |
| 42 | + def fetch(request) |
| 43 | + @cache.fetch(Key.for(request)) do |key| |
| 44 | + endpoint = @internet.endpoint_for(request) |
| 45 | + response = @internet.client_for(endpoint).call(request) |
| 46 | + response.body = Body::Buffered.wrap(response.body) |
| 47 | + |
| 48 | + @cache[key] = response |
| 49 | + end |
| 50 | + end |
| 51 | + |
| 52 | + def store(request, response) |
| 53 | + @cache[Key.for(request)] = response |
| 54 | + end |
| 55 | + |
| 56 | + def clear |
| 57 | + @cache.clear |
| 58 | + end |
| 59 | + end |
| 60 | + end |
| 61 | + end |
| 62 | +end |
0 commit comments