Created
November 24, 2020 03:00
-
-
Save hulucc/40ce9dddeacc4bf1ee434a834c776849 to your computer and use it in GitHub Desktop.
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
// @ts-nocheck | |
import { extractFiles } from 'extract-files' | |
import { Upload } from 'graphql-upload' | |
import FormData from './form' | |
import { print } from 'graphql' | |
import { AsyncExecutor, Subscriber } from '@graphql-tools/delegate'; | |
export async function buildUploadExecutor(endpoint: string, customFetch: any, extraHeaders: any) : Promise<{ executor: AsyncExecutor; subscriber: Subscriber }> { | |
const executor = async ({ document, variables }: any) => { | |
const vars = Object.assign({}, variables) | |
const { clone, files } = extractFiles(vars, 'variables', (v: any) => v instanceof Upload) | |
const map = Object.fromEntries(Array.from(files.values()).map((p, i) => [i, p])) | |
const uploads = new Map(Array.from(files.keys()).map((u, i) => [i, u])) | |
const form = new FormData() | |
form.append('operations', JSON.stringify({ | |
query: print(document), | |
variables: clone, | |
})) | |
form.append('map', JSON.stringify(map)) | |
for (let [i, u] of uploads) { | |
const upload = await u.promise | |
const stream = upload.createReadStream() | |
form.append(i.toString(), stream, { | |
filename: upload.filename, | |
contentType: upload.mimetype, | |
}) | |
} | |
const result = await customFetch(endpoint, { | |
method: 'POST', | |
headers: extraHeaders, | |
body: form, | |
}); | |
return result.json(); | |
} | |
return { | |
executor: executor, | |
subscriber: null, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment