简体   繁体   English

使用 graphql-request 向 graphql api 代理多部分请求

[英]Proxy multipart request to graphql api using graphql-request

I have a nodejs express app that serves as a proxy between a client application and a graphql api.我有一个 nodejs express 应用程序,它充当客户端应用程序和 graphql api 之间的代理。 The graphql api implements the graphql-multipart-request-spec. graphql api 实现了 graphql-multipart-request-spec。 I am using the graphql-request package to query it.我正在使用 graphql-request package 来查询它。 The proxy application uses nestjs and multer for the upload.代理应用程序使用nestjs 和multer 进行上传。

According to graphql-request docs you can upload files like this根据 graphql-request 文档,您可以上传这样的文件


const UploadUserAvatar = gql`
  mutation uploadUserAvatar($userId: Int!, $file: Upload!) {
    updateUser(id: $userId, input: { avatar: $file })
  }
`

request('/api/graphql', UploadUserAvatar, {
  userId: 1,
  file: createReadStream('./avatar.img'),
})

But that implies that the uploaded file has been saved to the file system.但这意味着上传的文件已保存到文件系统中。 Is it possible to do the same thing using the buffer of the file?是否可以使用文件的缓冲区做同样的事情?

I tried to turn the buffer to a ReadableStream like this:我试图将缓冲区变成这样的 ReadableStream:

const readable = new Readable()
readable._read = () => {} // _read is required but you can noop it
readable.push(file.buffer)
readable.push(null)

await request('/api/graphql', UploadUserAvatar, {
  userId: 1,
  file: readable,
})

But the graphql api returns the following error:但是 graphql api 返回以下错误:

Unexpected end of multipart data多部分数据意外结束

I got into similar issue and I solved it by using form-data package.我遇到了类似的问题,我通过使用form-data package 解决了它。

The soultion that worked for me:对我有用的灵魂:

import FormData from "form-data";

function uploadUserAvatar(userId: string, readable) {
    const requestBody = new FormData();
    
    requestBody.append('operations', JSON.stringify({
        query: UploadUserAvatar,
        variables: { userId }
    }));
    
    requestBody.append('map', JSON.stringify({
        0: ['variables.file']
    }));

    requestBody.append('0', readable);
    
    return new Promise((resolve, reject) => {
        requestBody.submit('http://endpoint/api/graphql', (err, res) => {
            if (err) {
                reject(err);
            } else {
                let body = '';
                res.on('readable', () => {
                    body += res.read();
                });
                
                res.on('end', () => {
                    resolve(JSON.parse(body));
                });
            }
        });
    });
}

I hope it will solve your problem too.我希望它也能解决你的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM