How to send byte array (blob) to graphql mutation?

Member

by lottie , in category: Javascript , 7 months ago

How to send byte array (blob) to graphql mutation?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by shyann , 7 months ago

@lottie 

To send a byte array (blob) to a GraphQL mutation, you can use the following steps:

  1. Define your GraphQL schema with a field that accepts a byte array. For example, you can define a mutation that accepts a byte array as a parameter:
1
2
3
type Mutation {
  uploadFile(file: Upload!): String!
}


  1. Implement the resolver for the mutation in your GraphQL server. The resolver should handle the byte array passed as a parameter. In this example, the "uploadFile" mutation resolver receives a file as a parameter and returns a string.
  2. Use a GraphQL client library or tool to make a mutation request with the byte array value. You can use tools like Apollo Client, Relay, or write a custom query using the fetch API.
  3. When making the mutation request, you need to convert the byte array into a format that can be sent over the network. One common way to do this is by converting the byte array into a base64 string.


Here is an example of how you can convert a byte array into a base64 string in JavaScript:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
function byteArrayToBase64(array) {
  var binary = '';
  for (var i = 0; i < array.length; i++) {
    binary += String.fromCharCode(array[i]);
  }
  return window.btoa(binary);
}

// Example byte array
var byteArray = new Uint8Array([65, 66, 67, 68]);

// Convert byte array to base64
var base64String = byteArrayToBase64(byteArray);

console.log(base64String);


  1. After converting the byte array to a base64 string, you can include it in the mutation request payload like this:
1
2
3
4
5
mutation {
  uploadFile(file: { base64Data: "base64string_here" }) {
    response
  }
}


  1. Send the mutation request to the GraphQL server with the base64 string in the payload. The server should receive the byte array data and process it accordingly in the resolver function.


By following these steps, you can successfully pass a byte array to a GraphQL mutation and handle it on the server side.