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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
//! # `vld_web::tungstenite` — validated WebSocket messages for `vld`
//!
//! Decode, encode and answer [`tungstenite::Message`]s whose payload is a
//! JSON message. Works with tungstenite 0.26 – 0.30 (the dependency is
//! `>=0.26, <0.31`, no default features), so it serves
//! [tokio-tungstenite](https://docs.rs/tokio-tungstenite) and
//! [async-tungstenite](https://docs.rs/async-tungstenite) too: both
//! re-export the same `Message` type (`tokio_tungstenite::tungstenite::Message`)
//! — use the tungstenite version your WebSocket crate depends on.
//!
//! | Function | Use case |
//! |---|---|
//! | [`decode`] | Validate an incoming text / binary frame (`None` for ping, pong, close and raw frames) |
//! | [`encode`] | Validate an outgoing value against its own schema and build a text frame |
//! | [`error_message`] | A text frame with the HTTP 422 body, to answer an invalid message |
//!
//! Malformed JSON is a single `parse_error` issue at path `""`, as for HTTP
//! JSON bodies; the error frame body is the
//! [422 body](crate::common#error-bodies) of the HTTP modules.
//!
//! # Example
//!
//! ```
//! use tungstenite::Message;
//!
//! vld::schema! {
//! #[derive(Debug)]
//! pub struct Chat {
//! pub room: String => vld::string().min(1),
//! pub text: String => vld::string().min(1).max(500),
//! }
//! }
//!
//! let incoming = Message::text(r#"{"room": "general", "text": "hi"}"#);
//! let chat: Chat = vld_web::tungstenite::decode(&incoming).unwrap().unwrap();
//! assert_eq!(chat.room, "general");
//!
//! let bad = Message::text(r#"{"room": "", "text": "hi"}"#);
//! let err = vld_web::tungstenite::decode::<Chat>(&bad).unwrap_err();
//! let reply = vld_web::tungstenite::error_message(&err); // send it back
//! assert!(reply.to_text().unwrap().contains(r#""path":".room""#));
//!
//! assert!(vld_web::tungstenite::decode::<Chat>(&Message::Ping(Default::default()))
//! .unwrap()
//! .is_none());
//! ```
//!
//! Guide: <https://s00d.github.io/vld/integrations/web/websocket>
use Message;
use VldError;
use VldParse;
/// Validate the JSON payload of a text or binary frame.
///
/// `Ok(None)` for ping, pong, close and raw frames (let the WebSocket
/// library handle them); `Err` when the payload is not JSON or fails `T`'s
/// schema.
/// Serialize `value` to a JSON text frame after checking the JSON against
/// `T`'s own schema (so a server never sends what its clients would reject).
/// A text frame with the HTTP 422 body:
/// `{"error": "Validation failed", "issues": [{"path", "message", "code"}]}`.
/// Prelude — import everything you need.