-
Notifications
You must be signed in to change notification settings - Fork 160
/
types.ex
77 lines (59 loc) · 1.91 KB
/
types.ex
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
defmodule Absinthe.Plug.Types do
@moduledoc """
This module provides GraphQL types that may be useful in Absinthe schema
and type modules.
## `:upload`
Absinthe.Plug can be used to upload files via GraphQL.
For example, the following schema includes a mutation field that accepts
multiple uploaded files as arguments (`:users` and `:metadata`):
```elixir
defmodule MyAppWeb.Schema do
use Absinthe.Schema
# Important: Needed to get the `:upload` type
import_types Absinthe.Plug.Types
mutation do
field :upload_file, :string do
arg :users, non_null(:upload)
arg :metadata, :upload
resolve fn args, _ ->
args.users # this is a `%Plug.Upload{}` struct.
{:ok, "success"}
end
end
end
end
```
To send a mutation that includes a file upload, you need to
use the `multipart/form-data` content type. For example, using `cURL`:
```shell
$ curl -X POST \
-F query='mutation { uploadFile(users: "users_csv", metadata: "metadata_json") }' \
-F users_csv=@users.csv \
-F metadata_json=@metadata.json \
localhost:4000/graphql
```
Note how there is a correspondence between the value of the `:users` argument
and the `-F` option indicating the associated file.
By treating uploads as regular arguments we get all the usual GraphQL argument
benefits (such as validation and documentation), something we wouldn't get if
we were merely putting them in the context.
"""
use Absinthe.Schema.Notation
alias Absinthe.Blueprint
@desc """
Represents an uploaded file.
"""
scalar :upload do
parse fn
%Blueprint.Input.String{value: value}, context ->
Map.fetch(context[:__absinthe_plug__][:uploads] || %{}, value)
%Blueprint.Input.Null{}, _ ->
{:ok, nil}
_, _ ->
:error
end
serialize fn _ ->
raise "The `:upload` scalar cannot be returned!"
end
end
end