async-graphql/src/types/upload.rs

106 lines
3.0 KiB
Rust
Raw Normal View History

2020-09-06 05:38:31 +00:00
use crate::parser::types::UploadValue;
2020-09-06 06:16:36 +00:00
use crate::{registry, InputValueError, InputValueResult, InputValueType, Type, Value};
2020-03-14 03:46:20 +00:00
use std::borrow::Cow;
2020-05-11 09:13:50 +00:00
use std::io::Read;
2020-03-14 03:46:20 +00:00
2020-03-30 14:02:43 +00:00
/// Uploaded file
2020-03-14 03:46:20 +00:00
///
2020-03-30 14:02:43 +00:00
/// **Reference:** <https://github.com/jaydenseric/graphql-multipart-request-spec>
///
///
/// Graphql supports file uploads via `multipart/form-data`.
/// Enable this feature by accepting an argument of type `Upload` (single file) or
/// `Vec<Upload>` (multiple files) in your mutation like in the example blow.
///
///
/// # Example
2020-04-28 07:41:31 +00:00
/// *[Full Example](<https://github.com/async-graphql/examples/blob/master/models/files/src/lib.rs>)*
2020-03-30 14:02:43 +00:00
///
/// ```
/// use async_graphql::*;
2020-03-30 14:02:43 +00:00
///
/// struct MutationRoot;
///
/// #[Object]
2020-03-30 14:02:43 +00:00
/// impl MutationRoot {
/// async fn upload(&self, file: Upload) -> bool {
/// println!("upload: filename={}", file.filename());
2020-03-30 14:02:43 +00:00
/// true
/// }
/// }
///
/// ```
/// # Example Curl Request
2020-03-30 14:36:27 +00:00
/// Assuming you have defined your MutationRoot like in the example above,
2020-03-30 14:31:38 +00:00
/// you can now upload a file `myFile.txt` with the below curl command:
2020-03-30 14:02:43 +00:00
///
/// ```curl
2020-03-30 14:47:17 +00:00
/// curl 'localhost:8000' \
2020-03-30 14:02:43 +00:00
/// --form 'operations={
/// "query": "mutation ($file: Upload!) { upload(file: $file) }",
/// "variables": { "file": null }}' \
/// --form 'map={ "0": ["variables.file"] }' \
/// --form '0=@myFile.txt'
/// ```
2020-05-11 09:13:50 +00:00
pub struct Upload(UploadValue);
impl Upload {
2020-03-20 03:56:08 +00:00
/// Filename
2020-05-11 09:13:50 +00:00
pub fn filename(&self) -> &str {
self.0.filename.as_str()
}
2020-03-20 03:56:08 +00:00
/// Content type, such as `application/json`, `image/jpg` ...
2020-05-11 09:13:50 +00:00
pub fn content_type(&self) -> Option<&str> {
self.0.content_type.as_deref()
}
2020-09-17 03:22:09 +00:00
/// Returns the size of the file, in bytes.
pub fn size(&self) -> std::io::Result<u64> {
self.0.content.metadata().map(|meta| meta.len())
}
/// Convert to a `Read`.
///
/// **Note**: this is a *synchronous/blocking* reader.
pub fn into_read(self) -> impl Read + Sync + Send + 'static {
self.0.content
}
#[cfg(feature = "unblock")]
#[cfg_attr(feature = "nightly", doc(cfg(feature = "unblock")))]
/// Convert to a `AsyncRead`.
2020-09-18 07:14:40 +00:00
pub fn into_async_read(self) -> impl futures::AsyncRead + Sync + Send + 'static {
blocking::Unblock::new(self.0.content)
}
2020-03-14 03:46:20 +00:00
}
2020-09-06 05:38:31 +00:00
impl Type for Upload {
2020-03-14 03:46:20 +00:00
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 {
2020-03-14 03:46:20 +00:00
name: Self::type_name().to_string(),
description: None,
2020-09-08 10:07:32 +00:00
is_valid: |value| matches!(value, Value::Upload(_)),
2020-03-14 03:46:20 +00:00
})
}
}
2020-09-06 05:38:31 +00:00
impl InputValueType for Upload {
fn parse(value: Option<Value>) -> InputValueResult<Self> {
let value = value.unwrap_or_default();
if let Value::Upload(upload) = value {
Ok(Upload(upload))
} else {
Rework errors This completely overhauls the error system used in async-graphql. - `Error` has been renamed to `ServerError` and `FieldError` has been renamed to just `Error`. This is because `FieldError` is by far the most common error that users will have to use so it makes sense to use the most obvious error name. Also, the current name didn't make sense as it was used for things other than field errors, such as the data callback for websockets. - `ServerError` has been made completely opaque. Before it was an enum of all the possible errors, but now it just contains an error message, the locations, the path and extensions. It is a shame that we lose information, it makes more sense as _conceptually_ GraphQL does not provide that information. It also frees us to change the internals of async-graphql a lot more. - The path of errors is no longer an opaque JSON value but a regular type, `Vec<PathSegment>`. The type duplication of `PathSegment` and `QueryPathSegment` is unfortunate, I plan to work on this in the future. - Now that `ServerError` is opaque, `RuleError` has been removed from the public API, making it simpler. - Additionally `QueryError` has been completely removed. Instead the error messages are constructed ad-hoc; I took care to never repeat an error message. - Instead of constructing field-not-found errors inside the implementations of field resolvers they now return `Option`s, where a `None` value is representative of the field not being found. - As an unfortunate consequence of the last change, self-referential types based on the output of a subscription resolver can no longer be created. This does not mean anything for users, but causes lifetime issues in the implementation of merged objects. I fixed it with a bit of a hack, but this'll have to be looked into further. - `InputValueError` now has a generic parameter - it's kind of weird but it's necessary for ergonomics. It also improves error messages. - The `ErrorExtensions` trait has been removed. I didn't think the `extend` method was necessary since `From` impls exist. But the ergonomics are still there with a new trait `ExtendError`, which is implemented for both errors and results. - `Response` now supports serializing multiple errors. This allows for nice things like having multiple validation errors not be awkwardly shoved into a single error. - When an error occurs in execution, data is sent as `null`. This is slightly more compliant with the spec but the algorithm described in <https://spec.graphql.org/June2018/#sec-Errors-and-Non-Nullability> has yet to be implemented.
2020-09-29 19:06:44 +00:00
Err(InputValueError::expected_type(value))
2020-03-14 03:46:20 +00:00
}
}
fn to_value(&self) -> Value {
Value::Null
}
2020-03-14 03:46:20 +00:00
}