-
-
Save menjaraz/2773b27d654c1120b8b7632e4ea74159 to your computer and use it in GitHub Desktop.
Vibe.d REST API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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