Upload file in GraphQL and apollo-server

24 views Asked by At

I have a Graphql server with Apollo-server and I have an API client in React, I have a form in React to send files, I stock them in a useState to send all in the mutation. In my research I saw I need to use "graphql-upload" and "apollo-upload-client" to do that, so I tried to use it but it doesn't work... nothing happen on back...

So this is the schema: I use scalar Upload but I don't know if I must make it or if it's directly in graphql-upload?

scalar Upload
input MediaInput {
    file: Upload!
    name: String!
    lastModified: Int!
    size: Int!
}
input CreateRequestInput {
    urgent: Boolean!
    title: String! @length(max: 255)
    message: String!
    localization: Coordinates!
    range: Int!
    user_id: Int!
    job_id: Int!
    media: [MediaInput!]
}
extend type Mutation{
    # Request mutations
    createRequest(input: CreateRequestInput!): Request
}

Front side:

<input 
id="file" 
className="input" 
name="text" 
type="file"
multiple={true} 
onChange={handleFileChange}
accept=".jpg,.jpeg,.png,.pdf" 
/>
const [file, setFile] = useState<File[]>([]);

createRequest({
    variables: {
        input: {
        urgent: urgent,
        title: DOMPurify.sanitize(titleRequest ?? ''),
        message: DOMPurify.sanitize(descriptionRequest ?? ''),
        localization: location,
        range: radius / 1000,
        job_id: Number(selectedJob),
        user_id: id,
        media: [{
            file: file[0],
            name: file[0].name,
            lastModified: Math.floor(file[0].lastModified / 1000),
            size: file[0].size,
        }]
    }
}

If I do file: null that work but if I send file that doesn't work...

I try to separate mutation but same error. I install apollo-upload-client

import { RouterProvider } from 'react-router-dom';
import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';
// @ts-expect-error - no types available
import createUploadLink from 'apollo-upload-client/createUploadLink.mjs';
import ReactDOM from 'react-dom/client';
import { router } from './routes';

import './styles/index.scss';

// create a client
const client = new ApolloClient({
    uri: 'http://localhost:3000/',
    credentials: 'include',
    cache: new InMemoryCache(),
    link: createUploadLink({uri: 'http://localhost:3000/', credentials: 'include'})
});

// create a root
const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);


// render element in the DOM
root.render(
    <ApolloProvider client={client}>
        <RouterProvider router={router} />
    </ApolloProvider>,
);

I don't know if I must do something in the index router to accept files or other?

0

There are 0 answers