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

问题描述 投票:0回答:2

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

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

这是我的代码:

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]
}

提前非常感谢!

node.js graphql apollo-server sharp
2个回答
4
投票

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

首先,我发现我需要将

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

0
投票

Apollo 建议使用签名 URL,而不是通过突变上传文件。 https://www.apollographql.com/blog/backend/file-uploads/file-upload-best-practices/

这是由于 CSRF 风险和性能影响,特别是当应用程序扩展时。对于正确处理 CSRF 风险的应用程序来说,通过突变上传文件应该没问题。

© www.soinside.com 2019 - 2024. All rights reserved.