use crate::{registry, Context, InputValueError, InputValueResult, InputValueType, Type, Value};
use futures::AsyncRead;
use std::borrow::Cow;
use std::fs::File;
use std::io::Read;
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(feature = "nightly", 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 Type for Upload {
fn type_name() -> Cow<'static, str> {
Cow::Borrowed("Upload")
}
fn create_type_info(registry: &mut registry::Registry) -> String {
registry.create_type::<Self, _>(|_| registry::MetaType::Scalar {
name: Self::type_name().to_string(),
description: None,
is_valid: |value| matches!(value, Value::String(_)),
})
}
}
impl InputValueType for Upload {
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 s.starts_with(PREFIX) {
return Ok(Upload(s[PREFIX.len()..].parse::<usize>().unwrap()));
}
}
Err(InputValueError::expected_type(value))
}
fn to_value(&self) -> Value {
Value::Null
}
}