backend/src/graphql/user/index.ts (view raw)
1export default [
2 ({ nexus, strapi }) => ({
3 types: [
4 nexus.extendType({
5 type: "UsersPermissionsMe",
6 definition(t) {
7 t.field("profile", {
8 type: "UsersPermissionsUser",
9 });
10 },
11 }),
12 nexus.extendInputType({
13 type: "UsersPermissionsUserInput",
14 definition(t) {
15 t.string("oldPassword");
16 },
17 }),
18 nexus.extendType({
19 type: "Mutation",
20 definition(t) {
21 t.field("updateMe", {
22 type: nexus.nonNull("UsersPermissionsUserEntityResponse"),
23 args: {
24 data: nexus.nonNull("UsersPermissionsUserInput"),
25 },
26 });
27 },
28 }),
29 ],
30 resolvers: {
31 Query: {
32 me: {
33 async resolve(_root, _args, context) {
34 const user = context.state?.user;
35 if (!user) throw new Error("Authentication requested");
36 return { id: user.id, username: user.username, profile: user };
37 },
38 },
39 },
40 Mutation: {
41 updateMe: {
42 async resolve(_root, args, context) {
43 const { data: userUpdate } = args;
44 const userId = context.state?.user?.id;
45
46 if (!userId) throw new Error("Authentication requested");
47
48 const user = await strapi
49 .plugin("users-permissions")
50 .services.user.fetch(userId, { populate: { events: true } });
51
52 if (userUpdate.password) {
53 const validPassword = await strapi
54 .plugin("users-permissions")
55 .services.user.validatePassword(
56 userUpdate.oldPassword || "",
57 user.password
58 );
59 if (!validPassword) throw new Error("Wrong password");
60 delete userUpdate.oldPassword;
61 }
62
63 const currentEvents = user.events || [];
64 const updatedEvents = userUpdate.events
65 ? [...currentEvents, ...userUpdate.events]
66 : user.events;
67
68 const updatedUser = await strapi.entityService.update(
69 "plugin::users-permissions.user",
70 user.id,
71 {
72 data: {
73 ...userUpdate,
74 events: updatedEvents,
75 },
76 }
77 );
78 const { toEntityResponse } = strapi
79 .plugin("graphql")
80 .service("format").returnTypes;
81
82 return toEntityResponse(updatedUser, {
83 args,
84 resourceUID: "plugin::users-permissions.user",
85 });
86 },
87 },
88 },
89 },
90 resolversConfig: {
91 "UsersPermissionsUser.notifications": {
92 auth: {
93 scope: ["plugin::users-permissions.user.me"],
94 },
95 },
96 },
97 }),
98];