-
Notifications
You must be signed in to change notification settings - Fork 5
/
BaseRequestHandler.cpp
63 lines (57 loc) · 2.03 KB
/
BaseRequestHandler.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//
// Created by victor on 11/7/17.
//
#include <folly/FBString.h>
#include "BaseRequestHandler.h"
namespace restdbxx {
bool BaseRequestHandler::not_found() const {
using namespace proxygen;
auto db = DbManager::get_instance();
return (this->_method == HTTPMethod::GET || this->_method == HTTPMethod::PUT
|| this->_method == HTTPMethod::DELETE) && !db->path_exists(this->_path);
}
void BaseRequestHandler::sendEmptyContentResponse(int status, const std::string &message) const {
proxygen::ResponseBuilder(downstream_)
.status(status, message)
.sendWithEOM();
}
void BaseRequestHandler::sendJsonResponse(const folly::dynamic &json, int status, const std::string &message) const {
auto jsonStr = toPrettyJson(json);
proxygen::ResponseBuilder(downstream_)
.status(status, message)
.header(proxygen::HTTP_HEADER_CONTENT_TYPE, "application/json")
.header(proxygen::HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN, "*")
.body(jsonStr.c_str())
.sendWithEOM();
}
void BaseRequestHandler::sendStringResponse(const std::string &body, int status, const std::string &message) const {
proxygen::ResponseBuilder(downstream_)
.status(status, message)
.body(body)
.sendWithEOM();
}
BaseRequestHandler::BaseRequestHandler() : RequestHandler(), _body(folly::IOBuf::create(1024)) {
}
folly::Try<folly::dynamic> BaseRequestHandler::parseBody() {
// if (_body) {
// std::string body_str = val->moveToFbString().toStdString();//->cloneCoalescedAsValue().toStdString();
auto func = [b = _body->cloneCoalesced()]() {
if (!b) {
throw std::runtime_error("empty body");
}
std::string p(reinterpret_cast<const char *>(b->data()), b->length());
//auto clone = _body->clone();
return folly::parseJson(p);
};
return folly::makeTryWith(func);
// }
//else return folly::Try::(std::runtime_error("empty body"));
}
void BaseRequestHandler::onBody(std::unique_ptr<folly::IOBuf> body) noexcept {
if (_body) {
_body->prependChain(std::move(body));
} else {
_body = std::move(body);
}
}
}