-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic.rs
More file actions
57 lines (48 loc) · 1.43 KB
/
basic.rs
File metadata and controls
57 lines (48 loc) · 1.43 KB
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
//! Basic example of using the JSON:API library
use rjapi::{JsonApiResource, JsonApiResponse, Resource};
use serde::Serialize;
use serde_json::json;
// A simple `Post` model
#[derive(Serialize)]
struct Post {
id: String,
title: String,
content: String,
created_at: String,
}
// Implementation of `JsonApiResource` for the `Post` model
impl JsonApiResource for Post {
const RESOURCE_TYPE: &'static str = "posts";
fn id(&self) -> String {
self.id.clone()
}
fn attributes(&self) -> serde_json::Value {
json!({
"title": self.title,
"content": self.content,
"created_at": self.created_at,
})
}
}
fn main() {
// Create an instance of the `Post` model
let post = Post {
id: "1".to_string(),
title: "Example Post".to_string(),
content: "This is an example post.".to_string(),
created_at: "2023-01-01T00:00:00Z".to_string(),
};
// Create a JSON:API resource from the `Post` model
let resource = Resource {
resource_type: Post::RESOURCE_TYPE.to_string(),
id: post.id(),
attributes: Some(post.attributes()),
relationships: None,
links: None,
meta: None,
};
// Create a JSON:API response using the builder
let response = JsonApiResponse::new(resource).build();
// Print the response
println!("{}", serde_json::to_string_pretty(&response).unwrap());
}