Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Image/file upload mutation example? #24

Closed
Samuell1 opened this issue Jan 13, 2017 · 21 comments
Closed

Image/file upload mutation example? #24

Samuell1 opened this issue Jan 13, 2017 · 21 comments

Comments

@Samuell1
Copy link

No description provided.

@Samuell1 Samuell1 changed the title Image/file upload example mutation? Image/file upload mutation example? Jan 16, 2017
@Samuell1
Copy link
Author

@dsdjolence
Copy link

I have same problem. Example will help a lot.
@Samuell1 did you found something?

@Samuell1
Copy link
Author

@dsdjolence I using other endpoint to only upload files.

@Samuell1
Copy link
Author

I found for Apollo 2+ there is plugin that can allow upload files with GraphQL
Client: https://github.com/jaydenseric/apollo-upload-client
Server: https://github.com/jaydenseric/apollo-upload-server

@dohomi
Copy link
Contributor

dohomi commented Jul 26, 2018

@Samuell1 did you get this work with vue-apollo and apollo-upload-client? I currently try but the issue is that the variables upload array is always NULL instead of a File object. Would be great to see a working example with vue-apollo

@dohomi
Copy link
Contributor

dohomi commented Jul 26, 2018

nevermind just found the solution in the react examples.

@razorabhu1995
Copy link

@dohomi
same problem for me. "the variables upload array is always NULL instead of a File object. "

did you find the solution for vue-apollo or nuxt-community/apollo-module?

@dohomi
Copy link
Contributor

dohomi commented Aug 22, 2018

@razorabhu1995 the NULL client side debug is happening because the server already took over to process the data upload. As long you see the right mutation according to the apollo-upload-client it should work finde. apollo-module let you use file-upload out of the box (make sure you use the most recent version of all the modules - maybe remove node_modules and reinstall to make 100% sure that all packages are up-to-date)

@eddivalen
Copy link

eddivalen commented Jan 19, 2019

Hey @dohomi I'm still getting NULL when I try to upload a file.
This is my vue-apollo.js config

import Vue from 'vue'
import VueApollo from 'vue-apollo'
import { createApolloClient, restartWebsockets } from 'vue-cli-plugin-apollo/graphql-client'
import { createUploadLink } from 'apollo-upload-client'


// Install the vue plugin
Vue.use(VueApollo)

// Name of the localStorage item
const AUTH_TOKEN = 'auth_token'

// Http endpoint
const httpEndpoint = process.env.VUE_APP_GRAPHQL_HTTP
export const filesRoot = process.env.VUE_APP_FILES_ROOT || httpEndpoint.substr(0, httpEndpoint.indexOf('/graphql'))


Vue.prototype.$filesRoot = filesRoot

// Config
const defaultOptions = {
  // You can use `https` for secure connection (recommended in production)
  httpEndpoint,
  // You can use `wss` for secure connection (recommended in production)
  // Use `null` to disable subscriptions
  wsEndpoint: process.env.VUE_APP_GRAPHQL_WS || null,
  // LocalStorage token
  tokenName: AUTH_TOKEN,
  // Enable Automatic Query persisting with Apollo Engine
  persisting: false,
  // Use websockets for everything (no HTTP)
  // You need to pass a `wsEndpoint` for this to work
  websocketsOnly: false,
  // Is being rendered on the server?
  ssr: false,

  // Override default apollo link
  // note: don't override httpLink here, specify httpLink options in the
  // httpLinkOptions property of defaultOptions.
  // link: myLink
  defaultHttpLink: false,
  httpLinkOptions : {
      httpLink : createUploadLink({
      uri: httpEndpoint,
      })
  },

  // Override default cache
  // cache: myCache

  // Override the way the Authorization header is set
   getAuth: tokenName => {
     // get the authentication token from local storage if it exists
    const token = Vue.cookie.get(tokenName) ? 'JWT ' + Vue.cookie.get(tokenName) : null
    // return the headers to the context so httpLink can read them
    return  token || ''
   },

  // Additional ApolloClient options
  // apollo: { ... }

  // Client local data (see apollo-link-state)
  // clientState: { resolvers: { ... }, defaults: { ... } }
}
// Create apollo client

export const { apolloClient, wsClient } = createApolloClient({
  ...defaultOptions,
})

apolloClient.wsClient = wsClient


// Create vue apollo provider
export const apolloProvider = new VueApollo({
  defaultClient: apolloClient,
  connectToDevTools: true,
  defaultOptions: {
    $query: {
      // fetchPolicy: 'cache-and-network',
    },
  },
  errorHandler (error) {
    // eslint-disable-next-line no-console
    console.log('%cError', 'background: red; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;', error.message)
  },
})
// Call this in the Vue app file
export function createProvider (options = {}) {
 
  return apolloProvider
}

@Oluwasetemi
Copy link

Did anyone get this to work?

@alexsedeke
Copy link

apollo-upload-client does not have to be imported and integrated. It is already part of vue-apollo, and already integrated.So no need to do anything.

@vinceramcesoliveros
Copy link

but how do you exactly do it in vue-apollo? there is no documentation found in the apollo.vuejs.org .

@jongbonga
Copy link

apollo-upload-client does not have to be imported and integrated. It is already part of vue-apollo, and already integrated.So no need to do anything.

An example will be great :)

@eddivalen
Copy link

@jongbonga just pass a file parameter to your mutation something like this:

mutation uploadFile($id:String!,$file: Upload!){
    uploadFile(id: $id, file: $file){
      .
      .
      .
    }
}

@asolopovas
Copy link

Hi everyone, I get the following error when I pass file to mutation.

app.js:169321 Error: GraphQL error: Variable "$productImage" got invalid value []; Expected type Upload; Could not get uploaded file, be sure to conform to GraphQL multipart request specification: https://github.com/jaydenseric/graphql-multipart-request-spec Instead got: []
    at new ApolloError (app.js:4873)
    at Object.next (app.js:5812)
    at notifySubscription (app.js:181947)
    at onNotify (app.js:181991)
    at SubscriptionObserver.next (app.js:182047)
    at app.js:5674
    at Set.forEach (<anonymous>)
    at Object.next (app.js:5674)
    at notifySubscription (app.js:181947)
    at onNotify (app.js:181991)

Everything should be working but I can't seem to find any example has anyone of your succeeded in finding one??

@eddivalen
Copy link

Hey @asolopovas, can you put an example of your mutation? because it seems your passing an empty array.

@asolopovas
Copy link

here is the example of how I call my mutation:

await this.$apollo.mutate({
    mutation: require('@/app/graphql/mutations/CreateProduct.gql'),
    variables: {
        name: item.name,
        productImage: item.upload,
        units: item.units,
        price: item.price,
        category: item.category.id
    },
    context: {
        hasUpload: true
    }
})

when I console.log(item.upload) it outputs a File object.

here is the example of my mutation:

mutation(
    $name: String!
    $units: Int!
    $productImage: Upload!
    $price: Float!
    $category: ID!
) {
    createProduct(input: {
        name: $name
        units: $units
        productImage: $productImage
        price: $price
        category: { connect: $category }
    }) {
        id
        category {
            name
        }
    }
}

@asolopovas
Copy link

https://github.com/wolfiton/vue-upload helped me out a lot

@nyelnizy
Copy link

yarn add @apollo/client apollo-upload-client
in your vue-apollo.js file
import {createUploadLink} from 'apollo-upload-client'
then replace http link with createUploadLink({ uri: 'your uri'}),

This worked for me.

@kengres
Copy link

kengres commented Feb 19, 2023

As @alexsedeke mentioned, you don't need to add apollo-upload-client to your packages.
Simply create an ApolloClient and call your mutation with a file (or files) as your variables.

Note that the server you are calling must have configured an Upload integration.

// Cache
const cache = new InMemoryCache();

// Create the apollo client
export const apolloClient = new ApolloClient({
  uri: 'LINK TO YOUR GRAPHQL SERVER', // Replace here
  cache,
});

// Mutation
const UPLOAD_MUTATION = gql`
  mutation UploadFile($file: Upload!) {
    uploadFile(file: $file)
  }
`;

// Call mutation in V4 of VueApollo
const { mutate } = useMutation(UPLOAD_MUTATION);

// Make sure this is a file
mutate({ file });

// Or use the apolloClient
apolloClient.mutate({
  mutation: UPLOAD_MUTATION,
  variables: { file },
});

Hope it helps!

@DaveHOnCode
Copy link

As @alexsedeke mentioned, you don't need to add apollo-upload-client to your packages. Simply create an ApolloClient and call your mutation with a file (or files) as your variables.

Note that the server you are calling must have configured an Upload integration.

// Cache
const cache = new InMemoryCache();

// Create the apollo client
export const apolloClient = new ApolloClient({
  uri: 'LINK TO YOUR GRAPHQL SERVER', // Replace here
  cache,
});

// Mutation
const UPLOAD_MUTATION = gql`
  mutation UploadFile($file: Upload!) {
    uploadFile(file: $file)
  }
`;

// Call mutation in V4 of VueApollo
const { mutate } = useMutation(UPLOAD_MUTATION);

// Make sure this is a file
mutate({ file });

// Or use the apolloClient
apolloClient.mutate({
  mutation: UPLOAD_MUTATION,
  variables: { file },
});

Hope it helps!

AND

apollo-upload-client does not have to be imported and integrated. It is already part of vue-apollo, and already integrated.So no need to do anything.

are currently (Apollo Vuejs client V4) WRONG. You have to use the apollo-upload-client, for example like this:

const client = new ApolloClient({ 
  link: ApolloLink.from([ 
    // ... 
    new HttpLink({
      uri: '/graphql' 
    }) 
  ])
})

(Source: https://dev.to/marvinrabe/file-upload-with-vue-apollo-client-and-graphql-5emb)

Then you can use the normal mutation including the "Upload" Scalar.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests