Geo*_*ios 5 error-handling upload file-upload graphql express-graphql
我有一个带有接受单个文件的解析器的快速 GraphQL 端点。解析器包括对正在接收的文件的简单验证。
问题在于,当验证失败时,没有办法立即将错误返回给前端,因为抛出错误并不会强制中断上传请求。
一个过于简单的例子:
fileUpload: async (parent, { file, otherdata }) => {
const isValid = (some logic here)
if(!isValid)
throw new ApolloError('upload parameters not valid')
//No need to get this far,
//we could have rejected the request already by examining otherdata,
//or the stream could be already created for max time utilization
const { createReadStream, filename, mimetype, encoding } = await file;
const readStream = await createReadStream()
...
}
Run Code Online (Sandbox Code Playgroud)
预期行为:解析器返回通常的 {errors:[], data:null} 对象 - 或错误本身 - 取决于错误策略选项。
实际行为:错误在后端抛出,但请求在前端仍处于待处理状态。
我已经尝试过以下方法但未成功:
一些澄清:
我知道使用 GraphQL 上传文件是边缘支持的功能,但在本例中我们讨论的是一个相当基本的操作。
我将不胜感激任何建议!
事实证明,这是默认的 Express 行为,与 GraphQL 接口完全无关。可以在此处找到该解决方案的纯快速版本。
请求和响应对象应传递到解析器上下文:
const apollo = new ApolloServer({
typeDefs,
resolvers,
context: ({ req, res }) => {
return {
req,
res
};
}
});
Run Code Online (Sandbox Code Playgroud)
然后在解析器中,根据示例:
fileUpload: async (parent, { file, otherdata }, {req, res}) => {
const isValid = (some logic here)
if(!isValid){
res.send(403).send("Some message")
// Throwing ApolloError could also work,
// in which case response object would not be required, but not tested.
// throw new ApolloError('upload parameters not valid')
return req.destroy()
}
//No need to get this far,
//we could have rejected the request already by examining otherdata,
//or the stream could be already created for max time utilization
const { createReadStream, filename, mimetype, encoding } = await file;
const readStream = await createReadStream()
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
855 次 |
| 最近记录: |