Created
August 1, 2019 23:42
-
-
Save rzane/5b70829091d8544a69b99845c77fd644 to your computer and use it in GitHub Desktop.
URQL file exchange (which doesn't work at all)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { print } from "graphql"; | |
import { pipe, map } from "wonka"; | |
import { Exchange, Operation } from "urql"; | |
type FetchExchangeFn = ( | |
operation: Operation, | |
options: RequestInit | |
) => RequestInit; | |
const createFetchExchange = (fn: FetchExchangeFn): Exchange => { | |
return ({ forward }) => { | |
return ops$ => | |
pipe( | |
ops$, | |
map(op => { | |
const fetchOptions = | |
typeof op.context.fetchOptions === "function" | |
? op.context.fetchOptions() | |
: op.context.fetchOptions || {}; | |
return { | |
...op, | |
context: { ...op.context, fetchOptions: fn(op, fetchOptions) } | |
}; | |
}), | |
forward | |
); | |
}; | |
}; | |
export const fileExchange = createFetchExchange((operation, options) => { | |
const body = new FormData(); | |
body.append("query", print(operation.query)); | |
body.append("variables", JSON.stringify(operation.variables)); | |
// Do the file extraction here and append the files to the form data. | |
return { | |
...options, | |
// Override the body that will be created in the `fetchExchange` | |
body, | |
headers: { | |
...options.headers, | |
// Here's the problem. When we send the request, it's important that a content-type header | |
// is NOT set. Otherwise the request will fail. Inside the `fetchExchange` the header is set | |
// to application/json and provides no way to unset it. | |
"content-type": "multipart/form-data" | |
} | |
}; | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment