[英]How to Process Uploaded Image with Graphql Apollo with SharpJS in NodeJS?
I have a graphql mutation that gets an image from the frontend, and that then is processed and optimized on my server.我有一个 graphql 突变,它从前端获取图像,然后在我的服务器上进行处理和优化。
But I can't figure out how to pass my image to sharp.但我不知道如何将我的图像传递给清晰的图像。
Here is my code:这是我的代码:
const Mutation = {
createImage: async (_, { data }) => {
const { file } = data
const image = await file
console.log(image)
const sharpImage = sharp(image)
}
}
I know the code doesn't work and sharp
throws an error saying that the input is invalid.我知道代码不起作用,并且会
sharp
一个错误,指出输入无效。 So how can I work with createReadStream
and to create an instance of sharp
?那么如何使用
createReadStream
并创建一个sharp
实例?
When I console.log(image)
, here is what I see:当我
console.log(image)
,这是我看到的:
image {
filename: 'image.png',
mimetype: 'image/png',
encoding: '7bit',
createReadStream: [Function: createReadStream]
}
Thanks a lot in advance!提前非常感谢!
So I figured out the solution to my question.所以我想出了我的问题的解决方案。
First, I found out that I needed to add scalar Upload
to typeDefs
.首先,我发现我需要将
scalar Upload
添加到typeDefs
。
Then, I need to add a resolver for Upload
like this:然后,我需要为
Upload
添加一个解析器,如下所示:
const { GraphQLUpload } = require('graphql-upload');
const server = new ApolloServer({
resolvers: {
Upload: GraphQLUpload,
}
})
Then in my resolver, here is what I had to do:然后在我的解析器中,这是我必须做的:
// this is a utility function to promisify the stream and store the image in a buffer, which then is passed to sharp
const streamToString = (stream) => {
const chunks = [];
return new Promise((resolve, reject) => {
stream.on('data', (chunk) => chunks.push(Buffer.from(chunk)));
stream.on('error', (err) => reject(err));
stream.on('end', () => resolve(Buffer.concat(chunks)));
})
}
const Mutation = {
createImage: async (_, { data }) => {
const { file } = data
const { createReadStream } = await file
const image = await streamToString(createReadStream())
const sharpImage = sharp(image)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.