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
use std::borrow::Cow;

use async_graphql::dynamic;
use async_graphql::dynamic::ValueAccessor;
use async_graphql::Context;
use async_graphql::UploadValue;

use crate::errors::InputValueError;
use crate::errors::InputValueResult;
use crate::from_value::FromValue;
use crate::registry::Registry;
use crate::types::InputTypeName;
use crate::types::Register;
use crate::types::TypeName;

pub struct Upload(usize);

impl TypeName for Upload {
    fn get_type_name() -> Cow<'static, str> {
        "Upload".into()
    }
}
impl InputTypeName for Upload {}

impl Upload {
    /// Get the upload value.
    pub fn value(&self, ctx: &Context<'_>) -> std::io::Result<UploadValue> {
        ctx.query_env
            .uploads
            .get(self.0)
            .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::Other, "Upload not found"))?
            .try_clone()
    }
}

impl FromValue for Upload {
    fn from_value(value: async_graphql::Result<ValueAccessor>) -> InputValueResult<Self> {
        const PREFIX: &str = "#__graphql_file__:";
        let value = value?;
        let value = value.string()?;

        if let Some(filename) = value.strip_prefix(PREFIX) {
            let index = filename.parse::<usize>().map_err(|_| {
                async_graphql::Error::new(
                    "Invalid upload value, expected #__graphql_file__:index format",
                )
            })?;
            return Ok(Upload(index));
        }
        Err(InputValueError::custom(
            "Invalid upload value, expected #__graphql_file__:index format",
        ))
    }
}

impl Register for Upload {
    fn register(registry: Registry) -> Registry {
        let upload = dynamic::Scalar::new("Upload");
        registry.register_type(upload)
    }
}