Skip to content

Instantly share code, notes, and snippets.

@Yoric
Created May 26, 2011 13:51
Show Gist options
  • Save Yoric/993180 to your computer and use it in GitHub Desktop.
Save Yoric/993180 to your computer and use it in GitHub Desktop.
storage.opajs
/**
* Add a path called [/storage] to the schema of our graph database.
*
* This path is is a dictionary indexed by [string]s of values
* of type [option(string)], i.e. values that may either be
* a string or omitted. To find out whether the value is present,
* one should use pattern-matching - case [{some: ...}] if the
* value is present, [{none}] if the value is omitted.
*
* Note: db is a keyword.
*/
db {
option(string) /storage[string];
}
/**
* Handle requests.
*
* @param request The uri of the request. The URI is converted to
* a key in [/storage], the method determines what should be done,
* and in the case of [{post}] requests, the body is used to set
* the value in the db.
*
* @return If the request is rejected, [{method_not_allowed}].
* If the request is a successful [{get}], a "text/plain" resource
* with the value previously stored. If the request is a [{get}] to
* an unknown key, a [{wrong_address}].
* Otherwise, a [{success}].
*/
dispatch(request) {
key = List.to_string(request.uri.path);
match(request.method) {
case {some: {get}}:
match(/storage[key]) {
{none}: Resource.raw_status({wrong_address});
{some: value}: Resource.raw_response(value, "text/plain", {success});
}
case {some: {post}}:
/storage[key] <- request.body;
Resource.raw_status({success});
case {some: {delete}}:
Db.remove(@/storage[key]);
Resource.raw_status({success});
case *: Resource.raw_status({method_not_allowed});
}
}
/**
* Main entry point: launching the server.
*/
start_server(Server.simple_request_dispatch(dispatch)).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment