about summary refs log tree commit diff
path: root/src/routes/accessions.rs
blob: 0c46c739caf3f4157b30452a7eb8ad9de8cc2379 (plain)
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
//! Accessions domain endpoint: GeneNetwork accession numbers ("GN602").

use axum::Json;
use axum::extract::Path;
use axum::http::StatusCode;

use gnauth_macros::gnauth;

use crate::auth::AuthToken;
use crate::db;
use crate::error::{ApiError, Unauthorized};
use crate::response::{Ctx, Envelope, path_segment};

/// The number in "GN602" (the prefix is optional and case-insensitive).
fn parse_accession(text: &str) -> Option<u32> {
    let digits = match text.get(..2) {
        Some(prefix) if prefix.eq_ignore_ascii_case("gn") => &text[2..],
        _ => text,
    };
    digits.parse().ok()
}

#[utoipa::path(get, path = "/accessions/{accession}", summary = "Resolve a GeneNetwork accession number such as GN602 to its dataset", params(
    ("accession" = String, Path, description = "The accession number, with or without the GN prefix, e.g. GN602 or 602")
), responses(
    (status = 200, description = "The dataset the accession names, with its category and group", body = Envelope<db::Accession>),
    Unauthorized,
    (status = 400, description = "Not an accession number", body = ApiError),
    (status = 404, description = "No dataset has this accession", body = ApiError),
    (status = 500, description = "Database error", body = ApiError)
))]
#[gnauth(token_only)]
pub async fn accession(
    ctx: Ctx,
    Path(accession): Path<String>,
    _token: AuthToken,
) -> Result<Json<Envelope<db::Accession>>, ApiError> {
    let rid = ctx.request_info();
    let Some(number) = parse_accession(&accession) else {
        return Err(ApiError::new(
            StatusCode::BAD_REQUEST,
            "invalid_parameter",
            "Invalid parameter",
            format!("'{accession}' is not an accession number; expected e.g. GN602 or 602."),
            "accession",
        )
        .with_request_id(rid));
    };
    tokio::task::spawn_blocking(move || db::get_accession(number))
        .await
        .map_err(|e| {
            ApiError::new(
                StatusCode::INTERNAL_SERVER_ERROR,
                "internal_error",
                "Internal error",
                e.to_string(),
                "accession",
            )
            .with_request_id(rid.clone())
        })?
        .map_err(|e| ApiError::from_db(e, "accession").with_request_id(rid.clone()))?
        .map(|found| {
            let group = found.group.as_deref().map(path_segment);
            let name = path_segment(&found.name);
            let category = found.category.clone();
            let mut envelope = ctx.envelope(found).with_links(crate::suggest::root_links());
            if let Some(group) = &group {
                envelope = envelope.with_next(
                    &format!("/groups/{group}"),
                    "The group the dataset belongs to",
                );
            }
            match (category.as_deref(), &group) {
                (Some("probeset"), _) => {
                    envelope =
                        envelope.with_next(&format!("/datasets/{name}"), "The expression dataset");
                }
                (Some("publish"), Some(group)) => {
                    envelope = envelope.with_next(
                        &format!("/groups/{group}/traits"),
                        "The dataset's published traits (can be very large)",
                    );
                }
                _ => {}
            }
            Json(envelope)
        })
        .ok_or_else(|| {
            ApiError::new(
                StatusCode::NOT_FOUND,
                "accession_not_found",
                "Accession not found",
                format!("No dataset has accession {accession}."),
                "accession",
            )
            .with_request_id(rid)
        })
}

#[cfg(test)]
mod tests {
    use super::parse_accession;

    #[test]
    fn accessions_parse_with_or_without_the_gn_prefix() {
        assert_eq!(parse_accession("GN602"), Some(602));
        assert_eq!(parse_accession("gn602"), Some(602));
        assert_eq!(parse_accession("602"), Some(602));
        assert_eq!(parse_accession("GN"), None);
        assert_eq!(parse_accession("GNx"), None);
        assert_eq!(parse_accession("BXDPublish"), None);
        assert_eq!(parse_accession(""), None);
    }
}