/
updateUser.js
39 lines (34 loc) · 1.33 KB
/
updateUser.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { WithFieldsError } from "@webiny/commodo";
import { ErrorResponse, Response, NotFoundResponse } from "@webiny/api";
import { InvalidFieldsError } from "@webiny/commodo-graphql";
export default userFetcher => async (root: any, args: Object, context: Object) => {
const { id, ...data } = args;
const User = userFetcher(context);
const user = await User.findById(id);
if (!user) {
return new NotFoundResponse(id ? `User "${id}" not found!` : "User not found!");
}
try {
await user.populate(data).save();
const authPlugin = context.plugins
.byType("security-authentication-provider")
.filter(pl => pl.hasOwnProperty("updateUser"))
.pop();
await authPlugin.updateUser({ data: args.data, user }, context);
} catch (e) {
if (e.code === WithFieldsError.VALIDATION_FAILED_INVALID_FIELDS) {
const attrError = InvalidFieldsError.from(e);
return new ErrorResponse({
code: attrError.code || WithFieldsError.VALIDATION_FAILED_INVALID_FIELDS,
message: attrError.message,
data: attrError.data
});
}
return new ErrorResponse({
code: e.code,
message: e.message,
data: e.data
});
}
return new Response(user);
};