Skip to main content

larastvel_core/models/
jsonapi.rs

1use std::collections::{HashMap, HashSet};
2
3use axum::body::Body;
4use axum::http::header::CONTENT_TYPE;
5use axum::http::Response as AxumResponse;
6use serde::Serialize;
7use serde_json::{json, Value};
8
9/// Parsed JSON:API query string context — the Rust equivalent of Laravel's
10/// automatic handling of `?include=` and `?fields[type]=` parameters.
11///
12/// Parse it from a request's query string and pass it to a
13/// [`JsonApiItem`] / [`JsonApiCollection`] via [`JsonApiItem::with_query`]:
14///
15/// ```rust,ignore
16/// let query = JsonApiQuery::parse(uri.query().unwrap_or(""));
17/// PostResource::make(post).with_query(&query).include("author", ...)
18/// ```
19///
20/// The default (or [`JsonApiQuery::ignored`]) query performs no filtering and
21/// no relationship inclusion — the equivalent of Laravel's
22/// `ignoreFieldsAndIncludesInQueryString()`.
23#[derive(Debug, Clone, Default)]
24pub struct JsonApiQuery {
25    fields: HashMap<String, HashSet<String>>,
26    includes: HashSet<String>,
27}
28
29impl JsonApiQuery {
30    /// Parse `include` / `fields[type]` parameters from a raw query string.
31    ///
32    /// Example: `include=author,comments&fields[posts]=title,created_at`.
33    pub fn parse(raw: &str) -> Self {
34        let mut query = Self::default();
35        for pair in raw.split('&') {
36            if pair.is_empty() {
37                continue;
38            }
39            let (key, value) = match pair.split_once('=') {
40                Some((k, v)) => (k, v),
41                None => (pair, ""),
42            };
43            if key == "include" {
44                for inc in value.split(',').filter(|s| !s.is_empty()) {
45                    query.includes.insert(inc.to_string());
46                }
47            } else if let Some(rest) = key.strip_prefix("fields[") {
48                if let Some(type_) = rest.strip_suffix(']') {
49                    query.fields.entry(type_.to_string()).or_default().extend(
50                        value
51                            .split(',')
52                            .filter(|s| !s.is_empty())
53                            .map(str::to_string),
54                    );
55                }
56            }
57        }
58        query
59    }
60
61    /// A query that ignores the query string entirely — full attributes,
62    /// no relationship inclusion (Laravel's `ignoreFieldsAndIncludesInQueryString`).
63    pub fn ignored() -> Self {
64        Self::default()
65    }
66
67    /// Whether the given relationship path was requested via `include=`.
68    ///
69    /// Nested paths imply their ancestors: requesting `author.posts` also
70    /// includes `author`.
71    pub fn includes(&self, path: &str) -> bool {
72        if self.includes.contains(path) {
73            return true;
74        }
75        let prefix = format!("{path}.");
76        self.includes.iter().any(|inc| inc.starts_with(&prefix))
77    }
78
79    /// The sparse fieldset requested for a resource type, if any.
80    pub fn fieldset(&self, type_: &str) -> Option<&HashSet<String>> {
81        self.fields.get(type_)
82    }
83
84    /// Filter an `attributes` object by the sparse fieldset for `type_`.
85    ///
86    /// Per the JSON:API spec this only ever filters `attributes`, never
87    /// `relationships`.
88    pub fn filter_attributes(&self, type_: &str, attributes: Value) -> Value {
89        match self.fields.get(type_) {
90            Some(fields) => match attributes {
91                Value::Object(map) => Value::Object(
92                    map.into_iter()
93                        .filter(|(key, _)| fields.contains(key))
94                        .collect(),
95                ),
96                other => other,
97            },
98            None => attributes,
99        }
100    }
101
102    /// Whether any include requests are present.
103    pub fn has_includes(&self) -> bool {
104        !self.includes.is_empty()
105    }
106}
107
108/// Laravel's `whenIncluded()` — emit a relationship value only when the
109/// client requested it via `?include=`.
110pub fn when_included(query: &JsonApiQuery, relationship: &str, value: Value) -> Option<Value> {
111    query.includes(relationship).then_some(value)
112}
113
114/// Laravel's `whenNotIncluded()` — emit a relationship value only when the
115/// client did *not* request it via `?include=`.
116pub fn when_not_included(query: &JsonApiQuery, relationship: &str, value: Value) -> Option<Value> {
117    (!query.includes(relationship)).then_some(value)
118}
119
120/// The Rust equivalent of Laravel 13's `Illuminate\Http\Resources\JsonApi\JsonApiResource`.
121///
122/// Implementors define how a model is transformed into a JSON:API resource
123/// object (`id`, `type`, `attributes`, `relationships`, `links`, `meta`).
124/// Sparse fieldsets and compound documents are handled automatically.
125///
126/// # Example
127///
128/// ```rust,ignore
129/// struct PostResource;
130///
131/// impl JsonApiResource<Post> for PostResource {
132///     fn attributes(model: &Post) -> Value {
133///         json!({ "title": model.title, "body": model.body })
134///     }
135///
136///     fn relationships(model: &Post, query: &JsonApiQuery) -> Value {
137///         json!({
138///             "author": when_included(query, "author", json!({
139///                 "type": "users", "id": model.author_id.to_string(),
140///             })),
141///         })
142///     }
143/// }
144/// ```
145pub trait JsonApiResource<T: Serialize + Send + Sync + 'static>: Sized {
146    /// The resource's `attributes` object (required).
147    fn attributes(model: &T) -> Value;
148
149    /// The resource's `id`. Defaults to the model's serialized `id` field
150    /// stringified, per the spec (ids must be strings).
151    fn id(model: &T) -> String {
152        match serde_json::to_value(model)
153            .ok()
154            .and_then(|value| value.get("id").cloned())
155        {
156            Some(Value::String(s)) => s,
157            Some(value) => value.to_string(),
158            None => String::new(),
159        }
160    }
161
162    /// The resource's `type`. Defaults to the model's type name lowercased,
163    /// e.g. `User` → `user`. Override for pluralised / custom types.
164    fn type_() -> String {
165        let full = std::any::type_name::<T>();
166        let last = full.rsplit("::").next().unwrap_or(full);
167        let last = last.split('<').next().unwrap_or(last);
168        last.to_ascii_lowercase()
169    }
170
171    /// The resource's `relationships` object. Use [`when_included`] /
172    /// [`when_not_included`] to make entries conditional on the request.
173    fn relationships(_model: &T, _query: &JsonApiQuery) -> Value {
174        json!({})
175    }
176
177    /// The resource's `links` object (e.g. a `self` link).
178    fn links(_model: &T) -> Value {
179        json!({})
180    }
181
182    /// The resource's `meta` object.
183    fn meta(_model: &T) -> Value {
184        json!({})
185    }
186
187    /// Create a single-resource document builder.
188    fn make(model: T) -> JsonApiItem<T, Self> {
189        JsonApiItem {
190            inner: model,
191            query: JsonApiQuery::default(),
192            included: vec![],
193            additional: Value::Object(Default::default()),
194            _marker: std::marker::PhantomData,
195        }
196    }
197
198    /// Create a collection document builder.
199    fn collection(models: Vec<T>) -> JsonApiCollection<T, Self> {
200        JsonApiCollection {
201            inner: models,
202            query: JsonApiQuery::default(),
203            included: vec![],
204            links: Value::Object(Default::default()),
205            meta: Value::Object(Default::default()),
206            _marker: std::marker::PhantomData,
207        }
208    }
209}
210
211type Included = Vec<Value>;
212
213type IncludedEntry = (
214    String,
215    Box<dyn Fn(&JsonApiQuery) -> Vec<Value> + Send + Sync>,
216);
217
218fn resource_object<T: Serialize + Send + Sync + 'static, R: JsonApiResource<T>>(
219    model: &T,
220    query: &JsonApiQuery,
221) -> Value {
222    let mut object = json!({
223        "id": R::id(model),
224        "type": R::type_(),
225        "attributes": query.filter_attributes(&R::type_(), R::attributes(model)),
226    });
227    let relationships = filter_null_entries(R::relationships(model, query));
228    if !is_empty_object(&relationships) {
229        object["relationships"] = relationships;
230    }
231    let links = R::links(model);
232    if !is_empty_object(&links) {
233        object["links"] = links;
234    }
235    let meta = R::meta(model);
236    if !is_empty_object(&meta) {
237        object["meta"] = meta;
238    }
239    object
240}
241
242fn is_empty_object(value: &Value) -> bool {
243    value.as_object().is_none_or(|map| map.is_empty())
244}
245
246/// Remove `null` entries (conditional values that were not requested),
247/// mirroring Laravel's handling of conditional relationships.
248fn filter_null_entries(value: Value) -> Value {
249    match value {
250        Value::Object(map) => {
251            Value::Object(map.into_iter().filter(|(_, v)| !v.is_null()).collect())
252        }
253        other => other,
254    }
255}
256
257fn included_resource_objects(included: &[IncludedEntry], query: &JsonApiQuery) -> Included {
258    let mut seen: HashSet<(String, String)> = HashSet::new();
259    let mut objects: Vec<Value> = Vec::new();
260    for (path, resolve) in included {
261        if !query.includes(path) {
262            continue;
263        }
264        for object in resolve(query) {
265            let key = (
266                object
267                    .get("type")
268                    .and_then(Value::as_str)
269                    .unwrap_or_default()
270                    .to_string(),
271                object
272                    .get("id")
273                    .and_then(Value::as_str)
274                    .unwrap_or_default()
275                    .to_string(),
276            );
277            if seen.insert(key) {
278                objects.push(object);
279            }
280        }
281    }
282    objects
283}
284
285/// A single-resource JSON:API document builder.
286///
287/// ```rust,ignore
288/// let query = JsonApiQuery::parse("include=author&fields[posts]=title");
289/// let doc = PostResource::make(post)
290///     .with_query(&query)
291///     .include("author", AuthorResource::make(author))
292///     .to_array();
293/// ```
294pub struct JsonApiItem<T: Serialize + Send + Sync + 'static, R: JsonApiResource<T>> {
295    inner: T,
296    query: JsonApiQuery,
297    included: Vec<IncludedEntry>,
298    additional: Value,
299    _marker: std::marker::PhantomData<R>,
300}
301
302impl<T: Serialize + Send + Sync + 'static, R: JsonApiResource<T>> JsonApiItem<T, R> {
303    /// Apply the parsed query string context (sparse fieldsets, includes).
304    pub fn with_query(mut self, query: &JsonApiQuery) -> Self {
305        self.query = query.clone();
306        self
307    }
308
309    /// Ignore the query string — return full attributes and no includes.
310    pub fn ignore_query_string(mut self) -> Self {
311        self.query = JsonApiQuery::ignored();
312        self
313    }
314
315    /// Register a related single resource to appear in the top-level
316    /// `included` array when `path` is requested via `?include=`.
317    pub fn include<
318        T2: Serialize + Send + Sync + 'static,
319        R2: JsonApiResource<T2> + Send + Sync + 'static,
320    >(
321        mut self,
322        path: &str,
323        child: JsonApiItem<T2, R2>,
324    ) -> Self {
325        let path = path.to_string();
326        self.included
327            .push((path, Box::new(move |query| child.resource_objects(query))));
328        self
329    }
330
331    /// Register a related collection to appear in the top-level `included`
332    /// array when `path` is requested via `?include=`.
333    pub fn include_collection<
334        T2: Serialize + Send + Sync + 'static,
335        R2: JsonApiResource<T2> + Send + Sync + 'static,
336    >(
337        mut self,
338        path: &str,
339        child: JsonApiCollection<T2, R2>,
340    ) -> Self {
341        let path = path.to_string();
342        self.included
343            .push((path, Box::new(move |query| child.resource_objects(query))));
344        self
345    }
346
347    /// Merge additional top-level keys (e.g. `meta`, `links`) into the
348    /// document — the equivalent of Laravel's `additional()`.
349    pub fn additional(mut self, data: Value) -> Self {
350        self.additional = data;
351        self
352    }
353
354    /// Build the resource object.
355    pub fn resource_object(&self, query: &JsonApiQuery) -> Value {
356        resource_object::<T, R>(&self.inner, query)
357    }
358
359    /// The resource objects for the document (itself).
360    pub fn resource_objects(&self, query: &JsonApiQuery) -> Vec<Value> {
361        vec![self.resource_object(query)]
362    }
363
364    /// Render the full document: `{ "data": {...}, "included": [...] }`.
365    pub fn to_array(&self) -> Value {
366        let mut document = json!({ "data": self.resource_object(&self.query) });
367        let included = included_resource_objects(&self.included, &self.query);
368        if !included.is_empty() {
369            document["included"] = Value::Array(included);
370        }
371        merge_document(&mut document, &self.additional);
372        document
373    }
374
375    /// Render the document as a pretty-printed JSON string.
376    pub fn to_json(&self) -> Result<String, serde_json::Error> {
377        serde_json::to_string_pretty(&self.to_array())
378    }
379
380    /// Consume the builder and return the inner model.
381    pub fn into_inner(self) -> T {
382        self.inner
383    }
384}
385
386/// A collection-resource JSON:API document builder.
387///
388/// ```rust,ignore
389/// let doc = PostResource::collection(posts)
390///     .with_query(&query)
391///     .include("author", AuthorResource::make(author))
392///     .with_links(json!({ "self": "/api/posts" }))
393///     .to_array();
394/// ```
395pub struct JsonApiCollection<T: Serialize + Send + Sync + 'static, R: JsonApiResource<T>> {
396    inner: Vec<T>,
397    query: JsonApiQuery,
398    included: Vec<IncludedEntry>,
399    links: Value,
400    meta: Value,
401    _marker: std::marker::PhantomData<R>,
402}
403
404impl<T: Serialize + Send + Sync + 'static, R: JsonApiResource<T>> JsonApiCollection<T, R> {
405    /// Apply the parsed query string context (sparse fieldsets, includes).
406    pub fn with_query(mut self, query: &JsonApiQuery) -> Self {
407        self.query = query.clone();
408        self
409    }
410
411    /// Ignore the query string — return full attributes and no includes.
412    pub fn ignore_query_string(mut self) -> Self {
413        self.query = JsonApiQuery::ignored();
414        self
415    }
416
417    /// Register a related single resource for the top-level `included` array.
418    pub fn include<
419        T2: Serialize + Send + Sync + 'static,
420        R2: JsonApiResource<T2> + Send + Sync + 'static,
421    >(
422        mut self,
423        path: &str,
424        child: JsonApiItem<T2, R2>,
425    ) -> Self {
426        let path = path.to_string();
427        self.included
428            .push((path, Box::new(move |query| child.resource_objects(query))));
429        self
430    }
431
432    /// Register a related collection for the top-level `included` array.
433    pub fn include_collection<
434        T2: Serialize + Send + Sync + 'static,
435        R2: JsonApiResource<T2> + Send + Sync + 'static,
436    >(
437        mut self,
438        path: &str,
439        child: JsonApiCollection<T2, R2>,
440    ) -> Self {
441        let path = path.to_string();
442        self.included
443            .push((path, Box::new(move |query| child.resource_objects(query))));
444        self
445    }
446
447    /// Set the top-level `links` object (e.g. pagination links).
448    pub fn with_links(mut self, links: Value) -> Self {
449        self.links = links;
450        self
451    }
452
453    /// Set additional top-level `meta` (merged with the automatic `count`).
454    pub fn with_meta(mut self, meta: Value) -> Self {
455        self.meta = meta;
456        self
457    }
458
459    /// The resource objects for every model in the collection.
460    pub fn resource_objects(&self, query: &JsonApiQuery) -> Vec<Value> {
461        self.inner
462            .iter()
463            .map(|model| resource_object::<T, R>(model, query))
464            .collect()
465    }
466
467    /// Render the full document: `{ "data": [...], "meta": { "count": N },
468    /// "links": {...}, "included": [...] }`.
469    pub fn to_array(&self) -> Value {
470        let mut document = json!({
471            "data": self.resource_objects(&self.query),
472            "meta": {
473                "count": self.inner.len(),
474            },
475        });
476        merge_document_at(&mut document, &self.links, "links");
477        merge_document_at(&mut document, &self.meta, "meta");
478        let included = included_resource_objects(&self.included, &self.query);
479        if !included.is_empty() {
480            document["included"] = Value::Array(included);
481        }
482        document
483    }
484
485    /// Render the document as a pretty-printed JSON string.
486    pub fn to_json(&self) -> Result<String, serde_json::Error> {
487        serde_json::to_string_pretty(&self.to_array())
488    }
489
490    /// Consume the builder and return the inner models.
491    pub fn into_inner(self) -> Vec<T> {
492        self.inner
493    }
494}
495
496fn merge_document(document: &mut Value, source: &Value) {
497    if let Value::Object(ref mut target) = document {
498        if let Value::Object(ref source_map) = source {
499            for (key, value) in source_map {
500                target.insert(key.clone(), value.clone());
501            }
502        }
503    }
504}
505
506fn merge_document_at(document: &mut Value, source: &Value, key: &str) {
507    if let Value::Object(ref mut target) = document {
508        if let Value::Object(ref source_map) = source {
509            let existing = target.get_mut(key).and_then(|value| value.as_object_mut());
510            match existing {
511                Some(existing) => {
512                    for (k, v) in source_map {
513                        existing.insert(k.clone(), v.clone());
514                    }
515                }
516                None => {
517                    target.insert(key.to_string(), source.clone());
518                }
519            }
520        }
521    }
522}
523
524fn into_response(document: Value) -> AxumResponse<Body> {
525    AxumResponse::builder()
526        .status(axum::http::StatusCode::OK)
527        .header(CONTENT_TYPE, "application/vnd.api+json")
528        .body(Body::from(
529            serde_json::to_vec(&document).unwrap_or_default(),
530        ))
531        .unwrap_or_default()
532}
533
534impl<T: Serialize + Send + Sync + 'static, R: JsonApiResource<T>> axum::response::IntoResponse
535    for JsonApiItem<T, R>
536{
537    fn into_response(self) -> AxumResponse<Body> {
538        into_response(self.to_array())
539    }
540}
541
542impl<T: Serialize + Send + Sync + 'static, R: JsonApiResource<T>> axum::response::IntoResponse
543    for JsonApiCollection<T, R>
544{
545    fn into_response(self) -> AxumResponse<Body> {
546        into_response(self.to_array())
547    }
548}
549
550// ============================================================================
551// TESTS
552// ============================================================================
553
554#[cfg(test)]
555mod tests {
556    use super::*;
557    use serde::Serialize;
558
559    #[derive(Debug, Clone, Serialize)]
560    struct Post {
561        id: u64,
562        title: String,
563        body: String,
564        author_id: u64,
565        secret_note: String,
566    }
567
568    #[derive(Debug, Clone, Serialize)]
569    struct Author {
570        id: u64,
571        name: String,
572        twitter_handle: String,
573    }
574
575    #[derive(Debug, Clone, Serialize)]
576    struct Comment {
577        id: u64,
578        body: String,
579    }
580
581    struct PostResource;
582
583    impl JsonApiResource<Post> for PostResource {
584        fn attributes(model: &Post) -> Value {
585            json!({
586                "title": model.title,
587                "body": model.body,
588                "secret_note": model.secret_note,
589            })
590        }
591
592        fn relationships(model: &Post, query: &JsonApiQuery) -> Value {
593            json!({
594                "author": when_included(query, "author", json!({
595                    "data": { "type": "authors", "id": model.author_id.to_string() },
596                })),
597                "comments": when_included(query, "comments", json!({
598                    "data": json!([]),
599                })),
600            })
601        }
602
603        fn links(model: &Post) -> Value {
604            json!({ "self": format!("/api/posts/{}", model.id) })
605        }
606    }
607
608    struct AuthorResource;
609
610    impl JsonApiResource<Author> for AuthorResource {
611        fn attributes(model: &Author) -> Value {
612            json!({ "name": model.name, "twitter_handle": model.twitter_handle })
613        }
614    }
615
616    struct CommentResource;
617
618    impl JsonApiResource<Comment> for CommentResource {
619        fn attributes(model: &Comment) -> Value {
620            json!({ "body": model.body })
621        }
622    }
623
624    fn post() -> Post {
625        Post {
626            id: 1,
627            title: "Hello".into(),
628            body: "World".into(),
629            author_id: 7,
630            secret_note: "hidden".into(),
631        }
632    }
633
634    #[test]
635    fn test_query_parse_include_and_fields() {
636        let query =
637            JsonApiQuery::parse("include=author,comments&fields[posts]=title&fields[authors]=name");
638        assert!(query.includes("author"));
639        assert!(query.includes("comments"));
640        assert!(!query.includes("tags"));
641        assert_eq!(query.fieldset("posts").unwrap().len(), 1);
642        assert!(query.fieldset("posts").unwrap().contains("title"));
643        assert!(query.fieldset("authors").unwrap().contains("name"));
644        assert!(query.fieldset("users").is_none());
645    }
646
647    #[test]
648    fn test_query_parse_nested_includes_imply_ancestors() {
649        let query = JsonApiQuery::parse("include=author.posts");
650        assert!(query.includes("author"));
651        assert!(query.includes("author.posts"));
652        assert!(!query.includes("comments"));
653    }
654
655    #[test]
656    fn test_query_default_is_ignored() {
657        let query = JsonApiQuery::ignored();
658        assert!(!query.has_includes());
659        assert!(query.fieldset("posts").is_none());
660    }
661
662    #[test]
663    fn test_default_id_and_type() {
664        let item = PostResource::make(post());
665        let object = item.resource_object(&JsonApiQuery::default());
666        assert_eq!(object["id"], json!("1"));
667        assert_eq!(object["type"], json!("post"));
668    }
669
670    #[test]
671    fn test_custom_id_and_type_overrides() {
672        struct CustomResource;
673        impl JsonApiResource<Author> for CustomResource {
674            fn attributes(model: &Author) -> Value {
675                json!({ "name": model.name })
676            }
677            fn id(_model: &Author) -> String {
678                "custom-id".into()
679            }
680            fn type_() -> String {
681                "people".into()
682            }
683        }
684        let author = Author {
685            id: 3,
686            name: "Tim".into(),
687            twitter_handle: "@tim".into(),
688        };
689        let object = CustomResource::make(author).resource_object(&JsonApiQuery::default());
690        assert_eq!(object["id"], json!("custom-id"));
691        assert_eq!(object["type"], json!("people"));
692    }
693
694    #[test]
695    fn test_resource_object_shape() {
696        let object = PostResource::make(post()).resource_object(&JsonApiQuery::default());
697        assert_eq!(object["attributes"]["title"], json!("Hello"));
698        assert_eq!(object["links"]["self"], json!("/api/posts/1"));
699        assert!(object.get("relationships").is_none());
700        assert!(object.get("meta").is_none());
701    }
702
703    #[test]
704    fn test_sparse_fieldsets_filter_attributes_only() {
705        let query = JsonApiQuery::parse("include=author&fields[post]=title&fields[author]=name");
706        let object = PostResource::make(post()).resource_object(&query);
707        assert_eq!(object["attributes"], json!({ "title": "Hello" }));
708        let author = Author {
709            id: 7,
710            name: "Tim".into(),
711            twitter_handle: "@tim".into(),
712        };
713        let author_object = AuthorResource::make(author).resource_object(&query);
714        assert_eq!(author_object["attributes"], json!({ "name": "Tim" }));
715    }
716
717    #[test]
718    fn test_relationships_require_include_request() {
719        let query = JsonApiQuery::parse("include=author");
720        let object = PostResource::make(post()).resource_object(&query);
721        assert!(object["relationships"]["author"]["data"]["id"] == json!("7"));
722        assert!(object["relationships"]["comments"]["data"].is_null());
723    }
724
725    #[test]
726    fn test_compound_document_dedupes_included() {
727        let query = JsonApiQuery::parse("include=author,comments");
728        let author = Author {
729            id: 7,
730            name: "Tim".into(),
731            twitter_handle: "@tim".into(),
732        };
733        let comments = vec![
734            Comment {
735                id: 1,
736                body: "First".into(),
737            },
738            Comment {
739                id: 2,
740                body: "Second".into(),
741            },
742        ];
743        let doc = PostResource::make(post())
744            .with_query(&query)
745            .include("author", AuthorResource::make(author.clone()))
746            .include("author", AuthorResource::make(author))
747            .include_collection("comments", CommentResource::collection(comments))
748            .to_array();
749        let included = doc["included"].as_array().unwrap();
750        assert_eq!(included.len(), 3);
751        assert!(included
752            .iter()
753            .any(|r| r["type"] == "author" && r["id"] == "7"));
754        assert!(included
755            .iter()
756            .any(|r| r["type"] == "comment" && r["id"] == "1"));
757        assert!(included
758            .iter()
759            .any(|r| r["type"] == "comment" && r["id"] == "2"));
760        assert!(doc["data"]["relationships"]["author"]["data"]["id"] == json!("7"));
761    }
762
763    #[test]
764    fn test_included_respects_sparse_fieldsets() {
765        let query = JsonApiQuery::parse("include=author&fields[author]=name");
766        let author = Author {
767            id: 7,
768            name: "Tim".into(),
769            twitter_handle: "@tim".into(),
770        };
771        let doc = PostResource::make(post())
772            .with_query(&query)
773            .include("author", AuthorResource::make(author))
774            .to_array();
775        let included = doc["included"].as_array().unwrap();
776        assert_eq!(included[0]["attributes"], json!({ "name": "Tim" }));
777    }
778
779    #[test]
780    fn test_no_included_when_not_requested() {
781        let query = JsonApiQuery::parse("fields[post]=title");
782        let author = Author {
783            id: 7,
784            name: "Tim".into(),
785            twitter_handle: "@tim".into(),
786        };
787        let doc = PostResource::make(post())
788            .with_query(&query)
789            .include("author", AuthorResource::make(author))
790            .to_array();
791        assert!(doc.get("included").is_none());
792    }
793
794    #[test]
795    fn test_ignore_query_string() {
796        let query = JsonApiQuery::parse("include=author&fields[post]=title");
797        let author = Author {
798            id: 7,
799            name: "Tim".into(),
800            twitter_handle: "@tim".into(),
801        };
802        let doc = PostResource::make(post())
803            .with_query(&query)
804            .ignore_query_string()
805            .include("author", AuthorResource::make(author))
806            .to_array();
807        assert!(doc.get("included").is_none());
808        assert_eq!(
809            doc["data"]["attributes"],
810            json!({ "title": "Hello", "body": "World", "secret_note": "hidden" })
811        );
812    }
813
814    #[test]
815    fn test_collection_shape_meta_and_links() {
816        let posts = vec![post()];
817        let doc = PostResource::collection(posts)
818            .with_links(json!({ "self": "/api/posts" }))
819            .with_meta(json!({ "total": 42 }))
820            .to_array();
821        assert_eq!(doc["data"].as_array().unwrap().len(), 1);
822        assert_eq!(doc["meta"]["count"], json!(1));
823        assert_eq!(doc["meta"]["total"], json!(42));
824        assert_eq!(doc["links"]["self"], json!("/api/posts"));
825    }
826
827    #[test]
828    fn test_collection_compound_document() {
829        let query = JsonApiQuery::parse("include=author");
830        let author = Author {
831            id: 7,
832            name: "Tim".into(),
833            twitter_handle: "@tim".into(),
834        };
835        let doc = PostResource::collection(vec![post()])
836            .with_query(&query)
837            .include("author", AuthorResource::make(author))
838            .to_array();
839        assert_eq!(
840            doc["data"][0]["relationships"]["author"]["data"]["id"],
841            json!("7")
842        );
843        assert_eq!(doc["included"][0]["type"], json!("author"));
844    }
845
846    #[test]
847    fn test_additional_merges_top_level() {
848        let doc = PostResource::make(post())
849            .additional(json!({ "meta": { "requested_at": "2026-01-01" } }))
850            .to_array();
851        assert_eq!(doc["meta"]["requested_at"], json!("2026-01-01"));
852    }
853
854    #[test]
855    fn test_when_not_included_helper() {
856        let query = JsonApiQuery::parse("include=author");
857        assert!(when_not_included(&query, "comments", json!({})).is_some());
858        assert!(when_not_included(&query, "author", json!({})).is_none());
859        assert!(when_included(&query, "author", json!({})).is_some());
860        assert!(when_included(&query, "comments", json!({})).is_none());
861    }
862
863    #[test]
864    fn test_into_response_content_type() {
865        use axum::response::IntoResponse;
866        let response = PostResource::make(post()).into_response();
867        assert_eq!(
868            response.headers().get(CONTENT_TYPE).unwrap(),
869            "application/vnd.api+json"
870        );
871        let body_bytes = tokio::runtime::Runtime::new()
872            .unwrap()
873            .block_on(axum::body::to_bytes(response.into_body(), 64 * 1024))
874            .unwrap();
875        let parsed: Value = serde_json::from_slice(&body_bytes).unwrap();
876        assert_eq!(parsed["data"]["type"], json!("post"));
877    }
878
879    #[test]
880    fn test_into_inner() {
881        let item = PostResource::make(post());
882        assert_eq!(item.into_inner().id, 1);
883        let collection = PostResource::collection(vec![post()]);
884        assert_eq!(collection.into_inner().len(), 1);
885    }
886
887    // -----------------------------------------------------------------------
888    // #[json_api_resource] macro tests
889    // -----------------------------------------------------------------------
890
891    use larastvel_macros::json_api_resource;
892
893    struct PostApiResource;
894
895    #[json_api_resource(Post)]
896    impl PostApiResource {
897        fn attributes(model: &Post) -> Value {
898            json!({ "title": model.title })
899        }
900
901        fn id(model: &Post) -> String {
902            format!("post-{}", model.id)
903        }
904
905        fn type_() -> String {
906            "articles".into()
907        }
908
909        fn relationships(model: &Post, query: &JsonApiQuery) -> Value {
910            json!({
911                "author": when_included(query, "author", json!({
912                    "data": { "type": "authors", "id": model.author_id.to_string() },
913                })),
914            })
915        }
916    }
917
918    #[test]
919    fn test_json_api_resource_macro() {
920        let query = JsonApiQuery::parse("include=author");
921        let object = PostApiResource::make(post()).resource_object(&query);
922        assert_eq!(object["id"], json!("post-1"));
923        assert_eq!(object["type"], json!("articles"));
924        assert_eq!(object["attributes"], json!({ "title": "Hello" }));
925        assert_eq!(object["relationships"]["author"]["data"]["id"], json!("7"));
926    }
927}