@@ 1,4 1,8 @@
# Key/Value Store
-* To store a value POST to the server at /[key] with the data in the body
-* To retrieve a value GET from the server at /[key] and the data will be returned in the body
+## Store a value
+* Send a POST request to `/<key>` with the value in the request body.
+* Send a GET request to `/<key>/<value>`.
+
+## Retrieve a value
+* Send a GET reques to `/<key>`. The value will be returned in the response body.
@@ 6,27 6,41 @@ const PORT = 24673;
let store = new Map();
-server.get(({path}, {send}) => {
- if (!path.length)
+function get(send, key) {
+ if (!key)
return send('Bad Request -- No key specified', 400, 'text/plain');
- let key = path[0];
-
if (store.has(key)) {
return send(store.get(key), 200, 'text/plain');
} else {
return send('Bad Request -- Key not found', 404, 'text/plain');
}
-});
+}
-server.post(({path, body}, {send}) => {
- if (!path.length)
+function set(send, key, value) {
+ if (!key)
return send('Bad Request -- No key specified', 400, 'text/plain');
+ store.set(key, value);
+ return send('OK -- Value saved', 200, 'text/plain');
+}
+
+server.get(({path}, {send}) => {
+ let key = path[0];
+ let value = path[1];
+
+ if (value) {
+ set(send, key, value);
+ } else {
+ get(send, key);
+ }
+});
+
+server.post(({path, body}, {send}) => {
let key = path[0];
+ let value = String.fromCharCode(...body); // bytes to string
- store.set(key, String.fromCharCode(...body));
- return send('OK -- Value saved', 200, 'text/plain');
+ set(send, key, value);
});
server.listen(PORT);