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
use std::{borrow::Cow, fs::File, io::Read};
#[cfg(feature = "unblock")]
use futures_util::io::AsyncRead;
use crate::{
registry, registry::MetaTypeId, Context, InputType, InputValueError, InputValueResult, Value,
};
pub struct UploadValue {
pub filename: String,
pub content_type: Option<String>,
pub content: File,
}
impl UploadValue {
pub fn try_clone(&self) -> std::io::Result<Self> {
Ok(Self {
filename: self.filename.clone(),
content_type: self.content_type.clone(),
content: self.content.try_clone()?,
})
}
pub fn into_read(self) -> impl Read + Sync + Send + 'static {
self.content
}
#[cfg(feature = "unblock")]
#[cfg_attr(docsrs, doc(cfg(feature = "unblock")))]
pub fn into_async_read(self) -> impl AsyncRead + Sync + Send + 'static {
blocking::Unblock::new(self.content)
}
pub fn size(&self) -> std::io::Result<u64> {
self.content.metadata().map(|meta| meta.len())
}
}
pub struct Upload(usize);
impl Upload {
pub fn value(&self, ctx: &Context<'_>) -> std::io::Result<UploadValue> {
ctx.query_env.uploads[self.0].try_clone()
}
}
impl InputType for Upload {
type RawValueType = Self;
fn type_name() -> Cow<'static, str> {
Cow::Borrowed("Upload")
}
fn create_type_info(registry: &mut registry::Registry) -> String {
registry.create_input_type::<Self, _>(MetaTypeId::Scalar, |_| registry::MetaType::Scalar {
name: Self::type_name().to_string(),
description: None,
is_valid: |value| matches!(value, Value::String(_)),
visible: None,
inaccessible: false,
tags: Default::default(),
specified_by_url: Some("https://github.com/jaydenseric/graphql-multipart-request-spec"),
})
}
fn parse(value: Option<Value>) -> InputValueResult<Self> {
const PREFIX: &str = "#__graphql_file__:";
let value = value.unwrap_or_default();
if let Value::String(s) = &value {
if let Some(filename) = s.strip_prefix(PREFIX) {
return Ok(Upload(filename.parse::<usize>().unwrap()));
}
}
Err(InputValueError::expected_type(value))
}
fn to_value(&self) -> Value {
Value::Null
}
fn as_raw_value(&self) -> Option<&Self::RawValueType> {
Some(self)
}
}