-2

If I wanted the user to take a picture on my ReactNative iOS app and send that to the server, how would it be defined in the graphQL schema?

  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Oct 30 '21 at 18:29

1 Answers1

0

When handling photo uploads from a React Native/GraphQl app, I follow a two-step process:

Step 1: GraphQl mutation to get the upload URL The client calls a GraphQl mutation, say addImage, passing along whatever arguments your backend needs to know about the photo. The mutation responds with (at minimum) with an upload URL String. The backend creates a database record with the photoID, userID, and the imageURL.

'''
returns an image upload URL to the client
'''
type Mutation {
  addImage(userID: String!): String
}

Step 2: Do the upload with a *non-GraphQL* post fetch The client uses fetch or something to post the image to the URL returned in step 1.

// the client upload function sends the image at fileUrl to the backendUrl

export const uploadJpeg = async (fileUrl: string, backendUrl: string): Promise<void> => {
  const resp = await fetch(fileUrl);
  const imageBody = await resp.blob();

  const options = {
    method: 'PUT',
    body: imageBody,
    headers: {
      Accept: 'application/json',
      'Content-Type': 'image/jpeg',
    },
  };

  fetch(backendUrl, options)
    .then((res) => res.json())
    .then((r) => console.log(r))
    .catch((error) => {
      console.log('error', error);
    });
};

Notes

Why can't I just upload the image using GraphQl in one step? You can, but probably shouldn't. GraphQl requests and responses send and receive only JSON data. It is technically possible for a GraphQl mutation to send a stringified Base64 serialised image in one step, but means extra work for your client, network and backend.

Why ask the backend for the URL? The point of addImage is to let your backend know about the image upload request and to control who uploads what. Don't expose client secrets or grant uncontrolled upload access to the client, or Bad Things can happen. The backend should return an obfuscated, short-lived URL. There are a million ways to do this. For instance, Cloudinary's signed upload or AWS S3 Presigned-URL help you generate secure upload URLs.

fedonev
  • 20,327
  • 2
  • 25
  • 34