From 486a1a17baef517703e34ecb2af90c9d5df6cff0 Mon Sep 17 00:00:00 2001 From: mo khan Date: Sat, 21 Nov 2020 16:36:54 -0700 Subject: refactor: extract render status methods --- lib/server.rb | 54 +++++++++++++++++------------------------------------- 1 file changed, 17 insertions(+), 37 deletions(-) (limited to 'lib/server.rb') diff --git a/lib/server.rb b/lib/server.rb index f465f7b..5b23066 100644 --- a/lib/server.rb +++ b/lib/server.rb @@ -10,60 +10,28 @@ class DataStorageServer @storage = storage end - # Download an Object - # - # GET /data/{repository}/{objectID} - # Response - # - # Status: 200 OK - # {object data} - # Objects that are not on the server will return a 404 Not Found. def get(path) oid = id_from(path) return not_found unless @storage.key?(oid) - ['200', {}, [@storage[oid]]] + ok(body: @storage[oid]) end - # Upload an Object - # - # Request - # PUT /data/{repository} - # - # my data - # - # Response - # - # Status: 201 Created - # {size, oid} - # Blobs can have a max size of MAX_BYTES bytes. - # If a blob exceeds this size then the blob is truncated - # and the first 1024 bytes are stored. def put(io) data = io.read(MAX_BYTES) - return ['400', {}, []] unless io.eof? + return bad_request unless io.eof? oid = Digest::SHA256.hexdigest(data) @storage[oid] = data - ['201', {}, [JSON.generate({ size: data.size, oid: oid })]] + render(status: '201', body: JSON.generate({ size: data.size, oid: oid })) end - # Delete an Object - # - # Request - # DELETE /data/{repository}/{oid} - # - # Response - # - # Status: 200 OK - # If the object identifer is unknown - # then a 404 status code is returned. def destroy(path) oid = id_from(path) return not_found unless @storage.key?(oid) @storage.delete(oid) - ['200', {}, []] + ok end def call(env) @@ -86,6 +54,18 @@ class DataStorageServer end def not_found - ['404', {}, []] + render(status: '404') + end + + def bad_request + render(status: '400') + end + + def ok(status: '200', headers: {}, body: nil) + render(status: status, headers: headers, body: body) + end + + def render(status:, headers: {}, body: nil) + [status, headers, [body].compact] end end -- cgit v1.2.3