added a simple middleware implementation
This commit is contained in:
parent
6dd0e9cb0c
commit
e71d302251
@ -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);
|
||||
|
||||
|
@ -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
35
speedy/middleware.hpp
Normal 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
|
@ -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;
|
||||
};
|
||||
|
||||
|
@ -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)
|
||||
{
|
||||
|
Loading…
Reference in New Issue
Block a user