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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
// Copyright 2024 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#![allow(clippy::module_name_repetitions)]

use mas_storage::Pagination;
use schemars::JsonSchema;
use serde::Serialize;
use ulid::Ulid;

use super::model::Resource;

/// Related links
#[derive(Serialize, JsonSchema)]
struct PaginationLinks {
    /// The canonical link to the current page
    #[serde(rename = "self")]
    self_: String,

    /// The link to the first page of results
    first: String,

    /// The link to the last page of results
    last: String,

    /// The link to the next page of results
    ///
    /// Only present if there is a next page
    #[serde(skip_serializing_if = "Option::is_none")]
    next: Option<String>,

    /// The link to the previous page of results
    ///
    /// Only present if there is a previous page
    #[serde(skip_serializing_if = "Option::is_none")]
    prev: Option<String>,
}

#[derive(Serialize, JsonSchema)]
struct PaginationMeta {
    /// The total number of results
    count: usize,
}

/// A top-level response with a page of resources
#[derive(Serialize, JsonSchema)]
pub struct PaginatedResponse<T> {
    /// Response metadata
    meta: PaginationMeta,

    /// The list of resources
    data: Vec<SingleResource<T>>,

    /// Related links
    links: PaginationLinks,
}

fn url_with_pagination(base: &str, pagination: Pagination) -> String {
    let (path, query) = base.split_once('?').unwrap_or((base, ""));
    let mut query = query.to_owned();

    if let Some(before) = pagination.before {
        query += &format!("&page[before]={before}");
    }

    if let Some(after) = pagination.after {
        query += &format!("&page[after]={after}");
    }

    let count = pagination.count;
    match pagination.direction {
        mas_storage::pagination::PaginationDirection::Forward => {
            query += &format!("&page[first]={count}");
        }
        mas_storage::pagination::PaginationDirection::Backward => {
            query += &format!("&page[last]={count}");
        }
    }

    // Remove the first '&'
    let query = query.trim_start_matches('&');

    format!("{path}?{query}")
}

impl<T: Resource> PaginatedResponse<T> {
    pub fn new(
        page: mas_storage::Page<T>,
        current_pagination: Pagination,
        count: usize,
        base: &str,
    ) -> Self {
        let links = PaginationLinks {
            self_: url_with_pagination(base, current_pagination),
            first: url_with_pagination(base, Pagination::first(current_pagination.count)),
            last: url_with_pagination(base, Pagination::last(current_pagination.count)),
            next: page.has_next_page.then(|| {
                url_with_pagination(
                    base,
                    current_pagination
                        .clear_before()
                        .after(page.edges.last().unwrap().id()),
                )
            }),
            prev: if page.has_previous_page {
                Some(url_with_pagination(
                    base,
                    current_pagination
                        .clear_after()
                        .before(page.edges.first().unwrap().id()),
                ))
            } else {
                None
            },
        };

        let data = page.edges.into_iter().map(SingleResource::new).collect();

        Self {
            meta: PaginationMeta { count },
            data,
            links,
        }
    }
}

/// A single resource, with its type, ID, attributes and related links
#[derive(Serialize, JsonSchema)]
struct SingleResource<T> {
    /// The type of the resource
    #[serde(rename = "type")]
    type_: &'static str,

    /// The ID of the resource
    #[schemars(with = "super::schema::Ulid")]
    id: Ulid,

    /// The attributes of the resource
    attributes: T,

    /// Related links
    links: SelfLinks,
}

impl<T: Resource> SingleResource<T> {
    fn new(resource: T) -> Self {
        let self_ = resource.path();
        Self {
            type_: T::KIND,
            id: resource.id(),
            attributes: resource,
            links: SelfLinks { self_ },
        }
    }
}

/// Related links
#[derive(Serialize, JsonSchema)]
struct SelfLinks {
    /// The canonical link to the current resource
    #[serde(rename = "self")]
    self_: String,
}

/// A top-level response with a single resource
#[derive(Serialize, JsonSchema)]
pub struct SingleResponse<T> {
    data: SingleResource<T>,
    links: SelfLinks,
}

impl<T: Resource> SingleResponse<T> {
    /// Create a new single response with the given resource and link to itself
    pub fn new(resource: T, self_: String) -> Self {
        Self {
            data: SingleResource::new(resource),
            links: SelfLinks { self_ },
        }
    }

    /// Create a new single response using the canonical path for the resource
    pub fn new_canonical(resource: T) -> Self {
        let self_ = resource.path();
        Self::new(resource, self_)
    }
}

/// A single error
#[derive(Serialize, JsonSchema)]
struct Error {
    /// A human-readable title for the error
    title: String,
}

impl Error {
    fn from_error(error: &(dyn std::error::Error + 'static)) -> Self {
        Self {
            title: error.to_string(),
        }
    }
}

/// A top-level response with a list of errors
#[derive(Serialize, JsonSchema)]
pub struct ErrorResponse {
    /// The list of errors
    errors: Vec<Error>,
}

impl ErrorResponse {
    /// Create a new error response from any Rust error
    pub fn from_error(error: &(dyn std::error::Error + 'static)) -> Self {
        let mut errors = Vec::new();
        let mut head = Some(error);
        while let Some(error) = head {
            errors.push(Error::from_error(error));
            head = error.source();
        }
        Self { errors }
    }
}