added a simple middleware implementation

This commit is contained in:
Dominik Tomičević 2015-10-13 23:01:20 +02:00
parent 6dd0e9cb0c
commit e71d302251
5 changed files with 57 additions and 0 deletions

View File

@ -40,6 +40,9 @@ public:
// for(key, value in body)
// node->properties[key] = value;
// TODO parse json body and put into the node
// commit the transaction
db->tx_engine.commit(t);

View File

@ -19,6 +19,7 @@ struct Request
std::map<std::string, std::string> headers;
// todo rename this body
std::string body;
};

35
speedy/middleware.hpp Normal file
View File

@ -0,0 +1,35 @@
#ifndef MEMGRAPH_SPEEDY_MIDDLEWARE_HPP
#define MEMGRAPH_SPEEDY_MIDDLEWARE_HPP
#include "request.hpp"
#include "response.hpp"
namespace sp
{
class Middlewares
{
public:
using middleware_cb_t = std::function<bool(sp::Request&, sp::Response&)>;
bool run(sp::Request& req, sp::Response& res)
{
for(auto& middleware : middlewares)
if(!middleware(req, res))
return false;
return true;
}
void push_back(middleware_cb_t cb)
{
middlewares.push_back(cb);
}
private:
std::vector<middleware_cb_t> middlewares;
};
}
#endif

View File

@ -13,6 +13,9 @@ class Request : public http::Request
public:
using http::Request::Request;
// todo json body insitu parsing
// http://rapidjson.org/md_doc_dom.html
std::vector<std::string> params;
};

View File

@ -17,6 +17,8 @@
#include "request.hpp"
#include "response.hpp"
#include "middleware.hpp"
namespace sp
{
@ -35,6 +37,11 @@ public:
Speedy(Speedy&) = delete;
Speedy(Speedy&&) = delete;
void use(Middlewares::middleware_cb_t cb)
{
middlewares.push_back(cb);
}
void get(const std::string& path, server_t::request_cb_t cb)
{
router.insert(R3::Method::GET, join(prefix, path), cb);
@ -60,6 +67,13 @@ public:
router.compile();
server.listen(ip, [this](Request& req, Response& res) {
// run middlewares
auto result = middlewares.run(req, res);
// if they signaled false, stop the further execution
if(!result)
return;
auto route = router.match(R3::to_r3_method(req.method), req.url);
if(!route.exists())
@ -74,6 +88,7 @@ private:
server_t server;
std::string prefix;
R3 router;
Middlewares middlewares;
std::string join(const std::string& prefix, const std::string& path)
{