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

3lxsmp7m  于 12个月前  发布在  Node.js
关注(0)|答案(2)|浏览(137)

我有一个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]
}


非常感谢提前!

bakd9h0s

bakd9h0s1#

所以我找到了我问题的答案。
首先,我发现我需要将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 streamToBuffer = (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 imageBuffer = await streamToBuffer(createReadStream())

        const sharpImage = sharp(imageBuffer)
    }
}

b4wnujal

b4wnujal2#

Apollo建议使用签名URL,而不是通过mutations上传文件。https://www.apollographql.com/blog/backend/file-uploads/file-upload-best-practices/
这是由于CSRF风险和性能影响,特别是当应用扩展时。对于正确处理CSRF风险的应用,通过突变上传文件应该是可以的。

相关问题