Files
moloapp/example/app/FormatsDemo.cpp
T

167 lines
6.1 KiB
C++
Raw Normal View History

#include "App.hpp"
#include "FormUi.hpp"
#include "../fw/Negotiate.hpp"
#include "../fw/Router.hpp"
#include "../fw/StaticFiles.hpp"
#include "../fw/Templates.hpp"
#include "../fw/Validate.hpp"
namespace molo::example::app {
namespace {
fw::Model contact_model() {
return fw::Model(
{{"name", fw::FieldType::String, true, 1, 80, 0, 0, false, ""},
{"email", fw::FieldType::Email, true, 3, 120, 0, 0, false, ""},
{"message", fw::FieldType::String, true, 1, 2000, 0, 0, false, ""}});
}
fw::Model user_model() {
fw::Field age{"age", fw::FieldType::Integer, true, 0, 0, 0, 150, true, ""};
return fw::Model(
{{"username", fw::FieldType::String, true, 3, 40, 0, 0, false, ""},
{"email", fw::FieldType::Email, true, 3, 120, 0, 0, false, ""},
age});
}
FormView contact_view() {
FormView v;
v.title = "Contact";
v.action = "/forms/contact";
v.fields = {{"name", "Name", "text", ""},
{"email", "Email", "email", ""},
{"message", "Message", "textarea", ""}};
return v;
}
FormView user_view() {
FormView v;
v.title = "Validate a user";
v.action = "/validate/user";
v.submit = "Validate";
v.fields = {{"username", "Username", "text", "3 to 40 characters"},
{"email", "Email", "email", ""},
{"age", "Age", "number", "whole number, 0 to 150"}};
return v;
}
} // namespace
void register_formats_demo(fw::Router& router, Services& services) {
fw::Environment* env = services.templates.get();
std::map<std::string, std::string> embedded = services.embedded;
std::string static_root = services.static_root;
router.get("/templates/page", "template-page", [env](fw::Request req) {
(void)req;
fw::TemplateCtx ctx;
ctx["title"] = std::string("Templates");
ctx["heading"] = std::string("Template demo");
ctx["author"] = std::string("ada");
ctx["snippet"] = std::string("<b>bold</b>");
fw::TemplateList items;
items.push_back({{"name", "extends"}, {"kind", "inheritance"}});
items.push_back({{"name", "include"}, {"kind", "partial"}});
items.push_back({{"name", "for"}, {"kind", "loop"}});
ctx["items"] = items;
return fw::Response(200, env->render("page.html", ctx),
"text/html; charset=utf-8");
});
router.get("/formats/data", "formats", [](fw::Request req) {
std::vector<std::string> offers = {"application/json", "application/xml",
"text/html", "text/plain"};
std::string pick =
fw::negotiate(req.headers.get("Accept"), offers);
if (pick == "application/json")
return fw::Response(
200, "{\"format\":\"json\",\"value\":42}", "application/json");
if (pick == "application/xml")
return fw::Response(200, "<data><value>42</value></data>",
"application/xml");
if (pick == "text/html")
return fw::Response(200, "<p>value: 42</p>",
"text/html; charset=utf-8");
return fw::Response(200, "value: 42", "text/plain; charset=utf-8");
});
router.get("/forms/contact", "contact-get", [env](fw::Request req) {
(void)req;
FormView view = contact_view();
return fw::Response(200, env->render("form_page.html", view.ctx()),
"text/html; charset=utf-8");
});
router.post("/forms/contact", "contact-post", [env](fw::Request req) -> fw::Response {
fw::Form form(contact_model());
FormView view = contact_view();
try {
auto clean = form.bind(req);
if (!wants_html(req))
return fw::JsonResponse("{\"ok\":true,\"name\":\"" +
fw::json_escape(clean["name"]) + "\"}",
200);
view.done = true;
view.notice = "Thanks " + clean["name"] + ", message received.";
} catch (const fw::ValidationError& e) {
if (!wants_html(req)) return fw::JsonResponse(e.to_json(), 422);
view.values = fw::parse_form(req.body);
view.error = &e;
return fw::Response(422, env->render("form_page.html", view.ctx()),
"text/html; charset=utf-8");
}
return fw::Response(200, env->render("form_page.html", view.ctx()),
"text/html; charset=utf-8");
});
router.get("/validate/user", "validate-user-form", [env](fw::Request req) {
(void)req;
FormView view = user_view();
return fw::Response(200, env->render("form_page.html", view.ctx()),
"text/html; charset=utf-8");
});
router.post("/validate/user", "validate-user", [env](fw::Request req) -> fw::Response {
fw::Model model = user_model();
auto input = fw::parse_json_object_flat(req.body);
if (input.empty()) input = fw::parse_form(req.body);
const bool html = req.headers.get("Accept").find("text/html") !=
std::string::npos;
try {
auto clean = model.validate(input);
if (html) {
FormView view = user_view();
view.done = true;
view.notice = "User " + clean["username"] + " is valid.";
return fw::Response(200, env->render("form_page.html", view.ctx()),
"text/html; charset=utf-8");
}
return fw::JsonResponse(
"{\"ok\":true,\"username\":\"" +
fw::json_escape(clean["username"]) + "\"}",
200);
} catch (const fw::ValidationError& e) {
if (!html) return fw::JsonResponse(e.to_json(), 422);
FormView view = user_view();
view.values = input;
view.error = &e;
return fw::Response(422, env->render("form_page.html", view.ctx()),
"text/html; charset=utf-8");
}
});
router.get("/static/{name}", "static", [static_root](fw::Request req) {
return fw::serve_disk_file(static_root, req.param_or("name", ""));
});
router.get("/embedded/{name}", "embedded", [embedded](fw::Request req) {
return fw::serve_embedded(embedded, req.param_or("name", ""));
});
router.get("/redirect/here", "redirect", [](fw::Request req) {
bool permanent = req.query_or("mode", "temp") == "perm";
return fw::Response(fw::RedirectResponse("/health", permanent));
});
}
} // namespace molo::example::app