以下是示例代码:
服务器端配置:
const upload = require('multer')({ dest: 'uploads/' })
app.post('/upload', upload.single('file'), (req, res) => { console.log(req.file) res.send('File uploaded successfully') })
客户端Mutation:
const UPLOAD_FILE_MUTATION = gql mutation UploadFileMutation($file: Upload!) { uploadFile(file: $file) { url } }
请求头文件设置:
const httpLink = createHttpLink({
uri: process.env.API_ENDPOINT,
headers: {
'Content-Type': 'application/json',
Authorization: Bearer ${process.env.TOKEN}
,
},
})
文件大小限制:
const uploadLink = new ApolloLink((operation, forward) => {
if (operation.operationName === 'UploadFileMutation') {
const files = Array.from(operation.variables.file || [])
const size = files.reduce((acc, file) => acc + file.size, 0)
if (size > MAX_FILE_SIZE) {
throw new Error(Files must be ${MAX_FILE_SIZE} bytes or less
)
}
}
return forward(operation)
}).concat(httpLink)
上一篇:Apollo未正确缓存数据
下一篇:Apollo写缓存失败