magpie
Loading...
Searching...
No Matches
MiddlewareProcessor.hpp
1#pragma once
2
3#include "magpie/data/CommonData.hpp"
4#include "magpie/middlewares/Middleware.hpp"
5#include "magpie/routing/BaseRoute.hpp"
6
7namespace magpie {
8
9template <data::IsCommonData ContextType>
10class MiddlewareProcessor : public IMiddlewareProcessor<ContextType> {
11private:
13 std::vector<Middlewares<ContextType>*> middlewareGroups;
14
15 size_t middlewareBlock;
16 size_t currPtr;
17
18 const std::vector<std::string_view>& requestedPath;
19 ContextType* ctx;
20 Request& req;
21 Response& res;
22
23 bool invoked = false;
24
25public:
26 [[nodiscard("Discarding the processor means no routing happens")]]
27 MiddlewareProcessor(
29 std::vector<Middlewares<ContextType>*>&& middlewares,
30 const std::vector<std::string_view>& requestedPath, // used for template shit in the Route
31 ContextType* ctx,
32 Request& req,
33 Response& res
34 ) :
35 route(route),
36 middlewareGroups(std::move(middlewares)),
37 middlewareBlock(0),
38 currPtr(0),
39 requestedPath(requestedPath),
40 ctx(ctx),
41 req(req),
42 res(res)
43 {}
44
45 void invokeRoute() override {
46 auto first = getNext();
47 if (first) {
48 first->onRequest(
49 this, ctx, req, res
50 );
51 }
52
53 }
54
55 Middleware<ContextType>* getNext() override {
56 if (middlewareBlock >= middlewareGroups.size()) {
57 if (invoked) {
58 throw std::runtime_error(
59 "Do not invoke next twice"
60 );
61 }
62 invoked = true;
63 this->route->invoke(
64 requestedPath,
65 ctx,
66 req,
67 res
68 );
69 return nullptr;
70 }
71 auto* currBlock = middlewareGroups.at(middlewareBlock);
72 if (
73 // Should never happen
74 currBlock == nullptr
75 // Block empty or ptr exceeds middleware
76 || currPtr >= currBlock->middlewares.size()
77 ) {
78 // Increment block, reset ptr, try again
79 ++middlewareBlock;
80 currPtr = 0;
81 return getNext();
82 }
83
84 return currBlock->middlewares.at(currPtr++).get();
85 }
86
87};
88
89}
Definition Middleware.hpp:73
Definition BaseRoute.hpp:16
Definition Middleware.hpp:16
Definition Middleware.hpp:145
Definition Request.hpp:11
Definition Response.hpp:13