如何在 NodeJS 中使用带有 SharpJS 的 Graphql Apollo 处理上传的图像?

How to Process Uploaded Image with Graphql Apollo with SharpJS in NodeJS?

我有一个 graphql 突变,它从前端获取图像,然后在我的服务器上进行处理和优化。

但我不知道如何将我的图像传递给 sharp。

这是我的代码:

const Mutation = {
    createImage: async (_, { data }) => {
        const { file } = data
        const image = await file

        console.log(image)

        const sharpImage = sharp(image)
    }
}

我知道代码不起作用,sharp 抛出一个错误,指出输入无效。那么我如何使用 createReadStream 并创建 sharp 的实例?

当我 console.log(image) 时,这是我看到的:

image {
  filename: 'image.png',
  mimetype: 'image/png',
  encoding: '7bit',
  createReadStream: [Function: createReadStream]
}

提前致谢!

所以我找到了问题的解决方案。

首先,我发现我需要将 scalar Upload 添加到 typeDefs

然后,我需要像这样为 Upload 添加解析器:

const { GraphQLUpload } = require('graphql-upload');

const server = new ApolloServer({
  resolvers: {
    Upload: GraphQLUpload,
  }
})

然后在我的解析器中,这是我必须做的:

// 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)
    }
}