Browse Source

Create JSON helper

master
Dylan Baker 3 years ago
parent
commit
5218d1d4c8
2 changed files with 22 additions and 13 deletions
  1. 2
    1
      src/middleware.rs
  2. 20
    12
      src/routes.rs

+ 2
- 1
src/middleware.rs View File

64
             let body: String = routes::render_template("error.html", &context)?;
64
             let body: String = routes::render_template("error.html", &context)?;
65
             res.set_body(body);
65
             res.set_body(body);
66
             res.set_status(status);
66
             res.set_status(status);
67
+            res.set_content_type(mime::HTML);
67
         }
68
         }
68
         None => match res.status() {
69
         None => match res.status() {
69
             StatusCode::NotFound => {
70
             StatusCode::NotFound => {
70
                 context.insert("error", "Page not found");
71
                 context.insert("error", "Page not found");
71
                 res.set_body(routes::render_template("error.html", &context)?);
72
                 res.set_body(routes::render_template("error.html", &context)?);
73
+                res.set_content_type(mime::HTML);
72
             }
74
             }
73
             _ => {}
75
             _ => {}
74
         },
76
         },
75
     };
77
     };
76
 
78
 
77
-    res.set_content_type(mime::HTML);
78
     Ok(res)
79
     Ok(res)
79
 }
80
 }

+ 20
- 12
src/routes.rs View File

1
 use chrono::prelude::Local;
1
 use chrono::prelude::Local;
2
 use serde::{Deserialize, Serialize};
2
 use serde::{Deserialize, Serialize};
3
 use tera::{Context, Tera};
3
 use tera::{Context, Tera};
4
+use tide::convert::json;
4
 use tide::http::mime;
5
 use tide::http::mime;
5
 use tide::{Redirect, Request, Response, Result, StatusCode};
6
 use tide::{Redirect, Request, Response, Result, StatusCode};
6
 use uuid::Uuid;
7
 use uuid::Uuid;
19
     let posts: Vec<Post> = fs::get_all_posts().await?;
20
     let posts: Vec<Post> = fs::get_all_posts().await?;
20
     let mut context = Context::new();
21
     let mut context = Context::new();
21
     context.insert("posts", &posts);
22
     context.insert("posts", &posts);
22
-    render_response("index.html", &context, req)
23
+    render_html_response("index.html", &context, req)
23
 }
24
 }
24
 
25
 
25
 pub async fn single_post(req: Request<State>) -> Result {
26
 pub async fn single_post(req: Request<State>) -> Result {
27
     let post_id = req.param("id")?;
28
     let post_id = req.param("id")?;
28
     let post = fs::get_one_post(post_id).await?;
29
     let post = fs::get_one_post(post_id).await?;
29
     context.insert("post", &post);
30
     context.insert("post", &post);
30
-    render_response("single.html", &context, req)
31
+    render_html_response("single.html", &context, req)
31
 }
32
 }
32
 
33
 
33
 pub async fn edit_post(req: Request<State>) -> Result {
34
 pub async fn edit_post(req: Request<State>) -> Result {
36
     let mut post = fs::get_one_post(post_id).await?;
37
     let mut post = fs::get_one_post(post_id).await?;
37
     post.body = post.body.replace("<br>", "\n");
38
     post.body = post.body.replace("<br>", "\n");
38
     context.insert("post", &post);
39
     context.insert("post", &post);
39
-    render_response("edit.html", &context, req)
40
+    render_html_response("edit.html", &context, req)
40
 }
41
 }
41
 
42
 
42
 pub async fn create_post(mut req: Request<State>) -> Result {
43
 pub async fn create_post(mut req: Request<State>) -> Result {
59
     let id: String = req.param("id")?;
60
     let id: String = req.param("id")?;
60
     fs::delete_post(id)?;
61
     fs::delete_post(id)?;
61
     req.session_mut().insert("flash_success", String::from("Post deleted successfully"))?;
62
     req.session_mut().insert("flash_success", String::from("Post deleted successfully"))?;
62
-    let mut res = Response::new(StatusCode::Ok);
63
-    res.set_body("{\"success\": \"true\"}");
64
-    res.set_content_type(mime::JSON);
65
-    Ok(res)
63
+    render_json_response(json!({ "success": "true" }))
66
 }
64
 }
67
 
65
 
68
 pub async fn login_page(req: Request<State>) -> Result {
66
 pub async fn login_page(req: Request<State>) -> Result {
69
-    render_response("login.html", &Context::new(), req)
67
+    render_html_response("login.html", &Context::new(), req)
70
 }
68
 }
71
 
69
 
72
 pub async fn login(mut req: Request<State>) -> Result {
70
 pub async fn login(mut req: Request<State>) -> Result {
92
     Ok(Redirect::new("/").into())
90
     Ok(Redirect::new("/").into())
93
 }
91
 }
94
 
92
 
95
-pub fn render_response(
93
+pub fn render_html_response(
96
     template: &str,
94
     template: &str,
97
     context: &Context,
95
     context: &Context,
98
     req: Request<State>,
96
     req: Request<State>,
114
     Ok(res)
112
     Ok(res)
115
 }
113
 }
116
 
114
 
115
+pub fn render_json_response(json: serde_json::Value) -> Result<Response> {
116
+    let res = Response::builder(StatusCode::Ok)
117
+        .body(json)
118
+        .content_type(mime::JSON)
119
+        .build();
120
+
121
+    Ok(res)
122
+}
123
+
124
+fn redirect(path: &str) -> Result<Response> {
125
+    Ok(Redirect::new(path).into())
126
+}
127
+
117
 pub fn render_template(template: &str, context: &Context) -> Result<String> {
128
 pub fn render_template(template: &str, context: &Context) -> Result<String> {
118
     let tera = Tera::new("templates/**/*.html")?;
129
     let tera = Tera::new("templates/**/*.html")?;
119
     let html = tera.render(template, &context)?;
130
     let html = tera.render(template, &context)?;
120
     Ok(html)
131
     Ok(html)
121
 }
132
 }
122
 
133
 
123
-fn redirect(path: &str) -> Result<Response> {
124
-    Ok(Redirect::new(path).into())
125
-}
126
 
134
 
127
 fn prepare_flash_messages(mut req: Request<State>) -> Context {
135
 fn prepare_flash_messages(mut req: Request<State>) -> Context {
128
     let mut context = Context::new();
136
     let mut context = Context::new();

Loading…
Cancel
Save