forked from surrealdb/surrealdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.rs
62 lines (57 loc) · 1.67 KB
/
request.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
use crate::rpc::failure::Failure;
use crate::rpc::format::cbor::Cbor;
use crate::rpc::format::msgpack::Pack;
use once_cell::sync::Lazy;
use surrealdb::sql::Part;
use surrealdb::sql::{Array, Value};
pub static ID: Lazy<[Part; 1]> = Lazy::new(|| [Part::from("id")]);
pub static METHOD: Lazy<[Part; 1]> = Lazy::new(|| [Part::from("method")]);
pub static PARAMS: Lazy<[Part; 1]> = Lazy::new(|| [Part::from("params")]);
pub struct Request {
pub id: Option<Value>,
pub method: String,
pub params: Array,
}
impl TryFrom<Cbor> for Request {
type Error = Failure;
fn try_from(val: Cbor) -> Result<Self, Failure> {
<Cbor as TryInto<Value>>::try_into(val).map_err(|_| Failure::INVALID_REQUEST)?.try_into()
}
}
impl TryFrom<Pack> for Request {
type Error = Failure;
fn try_from(val: Pack) -> Result<Self, Failure> {
<Pack as TryInto<Value>>::try_into(val).map_err(|_| Failure::INVALID_REQUEST)?.try_into()
}
}
impl TryFrom<Value> for Request {
type Error = Failure;
fn try_from(val: Value) -> Result<Self, Failure> {
// Fetch the 'id' argument
let id = match val.pick(&*ID) {
v if v.is_none() => None,
v if v.is_null() => Some(v),
v if v.is_uuid() => Some(v),
v if v.is_number() => Some(v),
v if v.is_strand() => Some(v),
v if v.is_datetime() => Some(v),
_ => return Err(Failure::INVALID_REQUEST),
};
// Fetch the 'method' argument
let method = match val.pick(&*METHOD) {
Value::Strand(v) => v.to_raw(),
_ => return Err(Failure::INVALID_REQUEST),
};
// Fetch the 'params' argument
let params = match val.pick(&*PARAMS) {
Value::Array(v) => v,
_ => Array::new(),
};
// Return the parsed request
Ok(Request {
id,
method,
params,
})
}
}