Skip to content

Instantly share code, notes, and snippets.

@lemonmade
Created October 23, 2017 14:23
Show Gist options
  • Save lemonmade/a976dc5c38ebd590c1dc06cce0affa0d to your computer and use it in GitHub Desktop.
Save lemonmade/a976dc5c38ebd590c1dc06cce0affa0d to your computer and use it in GitHub Desktop.
import {DataProxy} from 'apollo-client/data/proxy';
import {
ApolloClient,
} from 'apollo-client';
import {DocumentNode} from 'graphql';
import {get} from 'lodash';
import {Status} from '../network';
import stagedFileUploadMutation, {StagedFileUploadMutationData} from './StagedFileUploadMutation.graphql';
export type UploadImageOptions = Partial<StagedFileUploadMutationData.Variables['input']>;
export enum UploadImageStatus {
Success,
StagedUploadFailed,
FinalUploadFailed,
}
export type UploadImageResult =
{status: UploadImageStatus.StagedUploadFailed} |
{status: UploadImageStatus.FinalUploadFailed} |
{status: UploadImageStatus.Success, path: string};
export async function uploadImage(image: File, client: ApolloClient, options: UploadImageOptions): Promise<UploadImageResult> {
const stagedUploadTargetResponse = await client.mutate<StagedFileUploadMutationData>({
mutation: stagedFileUploadMutation,
variables: {
input: {
filename: image.name,
mimeType: image.type,
resource: 'PRODUCT_IMAGE',
...options,
},
},
});
const {data: {stagedUploadTargetGenerate: stagedUploadTargetGenerateData}} = stagedUploadTargetResponse;
if (stagedUploadTargetGenerateData == null) {
return {status: UploadImageStatus.StagedUploadFailed};
}
const {parameters} = stagedUploadTargetGenerateData;
const imagePath = parameters.find(({name}) => name === 'path');
if (imagePath == null) {
return {status: UploadImageStatus.StagedUploadFailed};
}
const headers = new Headers();
parameters.forEach((parameter) => {
const {name, value} = parameter;
headers.append(name, value);
});
const response = await fetch(stagedUploadTargetGenerateData.url, {
headers,
method: 'PUT',
body: image,
credentials: 'include',
});
return response.status === Status.Success
? {status: UploadImageStatus.Success, path: imagePath.value}
: {status: UploadImageStatus.FinalUploadFailed};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment