我正在尝试使用 apollo-angular 将文件从 Angular 上传到 apollo 服务器,但文档令人困惑,而且我在属中找到的信息没有更新到最新版本的 apollo angular 和 apollo 服务器。
在前端我有:
突变
export const Save_UserMutation = gql`
mutation SaveUserMutation ($data: UsersInput!, $file: Upload) {
createUser(data: $data, file: $file) {
user
}
}
`
服务
save(_userData: User, emitMessage?: boolean) {
let file = _userData.profilePicture
_userData.profilePicture = (_userData.profilePicture as File).name
const saveUser$ = this.apollo.mutate({
mutation: Save_UserMutation,
variables: {
data: _dataUsuario,
file
},
context: {
useMultipart: true
}
}).subscribe()
}
在后端:
服务器
const server = new ApolloServer({
schema,
context: createContext,
uploads: false
})
上传设置为 false 就像文档说https://www.apollographql.com/docs/apollo-server/data/file-uploads/#gatsby-focus-wrapper
用 nexus 编写的突变
export const UsersMutation = extendType({
type: 'Mutation',
definition(t) {
t.nonNull.field('createUser', {
type: 'Users',
args: {
data: nonNull(arg({ type: 'UsersInput' })),
file: arg({
type: GraphQLUpload
})
},
async resolve(parent, args, ctx) {
if (args.file) {
const { createReadStream, filename, mimetype, encoding } = await args.file
const stream = createReadStream()
const pathName = path.join(__dirname, 'public', 'profilePictures') + `/${filename}`
await stream.pipe(fs.createWriteStream(pathName))
args.data.profilePicture == pathName
}
args.data.password = await bcrypt.hash(args.data.password, 10)
return ctx.prisma.users.create({
data: args.data
})
}
}),
})
当我尝试上传文件时,出现以下错误。
POST body missing. Did you forget use body-parser middleware?