Skip to content

Instantly share code, notes, and snippets.

@KoRiGaN
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KoRiGaN/9ca1a934a267823e6004 to your computer and use it in GitHub Desktop.
Save KoRiGaN/9ca1a934a267823e6004 to your computer and use it in GitHub Desktop.
Vibe.d REST API
import vibe.d;
import vibe.web.rest;
import std.array;
shared static this()
{
auto router = new URLRouter;
router.get("/", serveStaticFiles("./../client/index.html"))
.get("*", serveStaticFiles("./../client/"));
registerRestInterface(router, new MyAPIMock());
auto settings = new HTTPServerSettings;
settings.port = 8080;
listenHTTP(settings, router);
auto routes = router.getAllRoutes;
foreach(route; routes) {
logInfo(route.pattern);
}
logInfo("Please open http://127.0.0.1:8080/ in your browser.");
}
interface MyAPI
{
@property ResourceAPI resources();
}
interface ResourceAPI
{
Resource add(Resource _value);
Resource[] get();
Resource get(int id);
void remove(int id);
}
class MyAPIMock : MyAPI
{
private:
ResourceAPI _resourceAPI;
public:
this()
{
_resourceAPI = new ResourceMockAPI();
}
override:
@property ResourceAPI resources()
{
return _resourceAPI;
}
}
T extractJsonValue(T)(HTTPServerRequest req, HTTPServerResponse res)
{
return deserializeJson!T(req.json);
}
class ResourceMockAPI : ResourceAPI
{
private Resource[] _resources;
@before!(extractJsonValue!Resource)("_value")
Resource add(Resource _value) {
_value.id = _resources.length;
_resources ~= _value;
return _value;
}
Resource[] get() {
return _resources;
}
Resource get(int id) {
if(id >= 0 && id < _resources.length) {
return _resources[id];
} else {
Resource r = { 999 };
return r;
}
}
void remove(int id) {
if(id >= 0 && id < _resources.length)
_resources = _resources[0 .. id] ~ _resources[id + 1 .. _resources.length];
}
}
struct Resource {
ulong id;
string firstName;
string lastName;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment