-
Notifications
You must be signed in to change notification settings - Fork 1
/
json.rs
44 lines (37 loc) · 1.21 KB
/
json.rs
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
use std::{
convert::{TryFrom, TryInto},
iter::FromIterator,
};
use crate::services::format::http;
use access_json::JSONQuery;
use async_trait::async_trait;
use crate::services::{Fields, Handler, ServiceError, ServiceResult};
pub struct JsonHandler {
prog: JSONQuery,
}
impl JsonHandler {
pub fn new(path: String) -> Self {
Self {
prog: JSONQuery::parse(path.as_str()).unwrap(),
}
}
}
#[async_trait]
impl Handler for JsonHandler {
fn from_payload(&self, buf: bytes::Bytes) -> ServiceResult<Fields> {
use bytes::Buf;
log::info!("{}", String::from_utf8(buf.to_vec()).unwrap());
let json: serde_json::Value = serde_json::from_reader(buf.reader())?;
let pr = self.prog.execute(&json)?;
let result = pr.ok_or(ServiceError::new("no result"))?;
Ok(serde_json::value::from_value(result)?)
}
async fn to_payload(&self, fields: &Fields) -> ServiceResult<bytes::Bytes> {
match serde_json::to_vec(fields) {
Ok(data) => Ok(bytes::Bytes::from_iter(data)),
Err(e) => Err(ServiceError::new(
format!("to_payload json failed: {}", e.to_string()).as_str(),
)),
}
}
}