Загрузить файл с помощью apollo-upload-client и graphql-yoga 3.x
В версиях 3.x для загрузки файлов graphql-yoga используется скалярный тип File для запросов, но apollo-upload-client использует Upload , так как я могу заставить его работать с этими фреймворками?
1 ответ
Это не по теме, но вы можете сделать более простое решение, просто отправив файл. Вам нужно удалить apollo-upload-client из списка. Также на бэкенде. Пример загрузки чистого файла.
схема.graphql
scalar File
extend type Mutation {
profileImageUpload(file: File!): String!
}
резольвер.ts
profileImageUpload: async (_, { file }: { file: File }) => {
// get readableStream from blob
const readableStream = file.stream()
const stream = readableStream.getReader()
console.log('file', file.type)
let _file: Buffer | undefined
while (true) {
// for each iteration: value is the next blob fragment
const { done, value } = await stream.read()
if (done) {
// no more data in the stream
console.log('all blob processed.')
break
}
if (value)
_file = Buffer.concat([_file || Buffer.alloc(0), Buffer.from(value)])
}
if (_file) {
const image = sharp(_file)
const metadata = await image.metadata()
console.log(metadata, 'metadata')
try {
const image = await sharp(_file).resize(600, 600).webp().toBuffer()
fs.writeFileSync('test.webp', image)
console.log(image, 'image')
}
catch (error) {
console.error(error)
}
}
return 'a'
},