lacoctelera/routes/recipe/
get.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
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
233
234
235
236
237
238
239
240
// Copyright 2024 Felipe Torres González
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

//! Example

use crate::{
    domain::{DataDomainError, RecipeQuery},
    routes::recipe::{
        get_recipe_from_db, search_recipe_by_category, search_recipe_by_name,
        search_recipe_by_rating,
    },
};
use actix_web::{
    get,
    web::{Data, Path, Query},
    HttpResponse,
};
use sqlx::MySqlPool;
use std::convert::TryFrom;
use std::error::Error;
use std::fmt::Display;
use tracing::{info, instrument};
use uuid::Uuid;

/// GET method for the /recipe endpoint (Public).
///
/// # Description
///
/// The GET method allows *searching* a recipe in the DB. It expects multiple attributes to filter the recipes in the
/// DB that shall be encoded in the url. The following keys can be used to perform a search:
/// - `name`: Use a string that can match the name of a recipe (or part of it).
/// - `tags`: Only recipes that contain all the included tags in the query will be returned by the API.
/// - `rating`: Recipes that are scored with a rating greater or equal to the given rating will be returned by the API.
///   See the schema `RecipeRating` for more details.
/// - `category`: Filter recipes using one of the available categories. See the schema `RecipeCategory` for more
///    details.
///
/// A query can be composed by many attributes. For example, consider this query:
///
/// ```bash
/// http://localhost:9090/recipe?name=margarita&tags=tequila&tags=reposado&rating=2
/// ```
///
/// Would return recipes that contain the string *margarita* in their name attribute; whose tags include *tequila* and
/// *reposado*; and, whose rating is greater or equal to 4 stars.
#[utoipa::path(
    get,
    path = "/recipe",
    tag = "Recipe",
    params(RecipeQuery),
    responses(
        (
            status = 200,
            description = "The query was executed successfully and produced some matches.",
            body = [Recipe],
            headers(
                ("Access-Control-Allow-Origin"),
                ("Content-Type"),
                ("Cache-Control"),
            )
        ),
        (
            status = 404,
            description = "The query was executed successfully but didn't produce any match.",
            headers(
                ("Content-Length"),
                ("Date"),
                ("Vary", description = "Origin,Access-Control-Request-Method,Access-Control-Request-Headers")
            ),
        ),
        (
            status = 429,
            description = "Too many requests",
            headers(
                ("Access-Control-Allow-Origin"),
                ("Retry-After"),
            )
        ),

    )
)]
#[get("")]
pub async fn search_recipe(
    req: Query<RecipeQuery>,
    pool: Data<MySqlPool>,
) -> Result<HttpResponse, Box<dyn Error>> {
    let search_type: SearchType = (&req.0).try_into().expect("Wrong query");

    info!("Recipe search ({search_type}) using: {{{}}}", req.0);

    let recipe_ids = match search_type {
        SearchType::ByName => {
            let search_token = match req.0.name {
                Some(name) => name,
                None => return Err(Box::new(DataDomainError::InvalidSearch)),
            };
            search_recipe_by_name(&pool, &search_token).await?
        }
        SearchType::ByCategory => {
            let search_token = match req.0.category {
                Some(category) => category,
                None => return Err(Box::new(DataDomainError::InvalidSearch)),
            };
            search_recipe_by_category(&pool, search_token).await?
        }
        SearchType::ByRating => {
            let search_token = match req.0.rating {
                Some(rating) => rating,
                None => return Err(Box::new(DataDomainError::InvalidSearch)),
            };
            search_recipe_by_rating(&pool, search_token).await?
        }
        SearchType::ByTags => return Ok(HttpResponse::NotImplemented().finish()),
        SearchType::Intersection => return Ok(HttpResponse::NotImplemented().finish()),
    };

    let mut recipes = Vec::new();

    for id in recipe_ids.iter() {
        recipes.push(get_recipe_from_db(&pool, id).await?)
    }

    if recipes.is_empty() {
        Ok(HttpResponse::Ok().json(recipes))
    } else {
        Ok(HttpResponse::NotFound().finish())
    }
}

/// Retrieve a recipe from the DB using its unique ID.
#[utoipa::path(
    get,
    context_path = "/recipe/",
    tag = "Recipe",
    responses(
        (
            status = 200,
            description = "The recipe identified by the given ID was found in the DB",
            body = Recipe,
            headers(
                ("Content-Length"),
                ("Content-Type"),
                ("Date"),
                ("Vary", description = "Origin,Access-Control-Request-Method,Access-Control-Request-Headers")
            ),
        ),
        (
            status = 404,
            description = "The given recipe's ID was not found in the DB.",
            headers(
                ("Content-Length"),
                ("Date"),
                ("Vary", description = "Origin,Access-Control-Request-Method,Access-Control-Request-Headers")
            ),
        ),
        (
            status = 429,
            description = "Too many requests",
            headers(
                ("Access-Control-Allow-Origin"),
                ("Retry-After"),
            )
        ),

    )

)]
#[instrument(skip(pool))]
#[get("{id}")]
pub async fn get_recipe(
    pool: Data<MySqlPool>,
    path: Path<(String,)>,
) -> Result<HttpResponse, Box<dyn Error>> {
    let recipe_id = Uuid::parse_str(&path.0).map_err(|_| DataDomainError::InvalidId)?;

    let recipe = get_recipe_from_db(&pool, &recipe_id).await?;

    match recipe {
        Some(recipe) => Ok(HttpResponse::Ok().json(recipe)),
        None => Ok(HttpResponse::NotFound().finish()),
    }
}

#[derive(Debug, Clone)]
enum SearchType {
    ByName,
    ByTags,
    ByRating,
    ByCategory,
    Intersection,
}

impl Display for SearchType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let ss = match self {
            SearchType::ByName => "ByName",
            SearchType::ByTags => "ByTags",
            SearchType::ByRating => "ByRating",
            SearchType::ByCategory => "ByCategory",
            SearchType::Intersection => "Intersection",
        };

        write!(f, "{ss}")
    }
}

fn multiple_choices(query: &RecipeQuery) -> bool {
    if (query.name.is_some()
        && (query.tags.is_some() || query.rating.is_some() || query.category.is_some()))
        || (query.tags.is_some() && (query.rating.is_some() || query.category.is_some()))
        || (query.rating.is_some() && query.category.is_some())
    {
        return true;
    }

    false
}

impl TryFrom<&RecipeQuery> for SearchType {
    type Error = String;

    fn try_from(query: &RecipeQuery) -> std::result::Result<Self, Self::Error> {
        if multiple_choices(query) {
            Ok(SearchType::Intersection)
        } else if query.name.is_some() {
            Ok(SearchType::ByName)
        } else if query.tags.is_some() {
            Ok(SearchType::ByTags)
        } else if query.rating.is_some() {
            Ok(SearchType::ByRating)
        } else if query.category.is_some() {
            Ok(SearchType::ByCategory)
        } else {
            Err("Invalid conversion".to_string())
        }
    }
}