all repos — caroster @ v8.0

[Octree] Group carpool to your event https://caroster.io

backend/src/graphql/event/administrators.ts (view raw)

  1import { errors } from "@strapi/utils";
  2
  3export default ({ nexus, strapi }) => ({
  4  types: [
  5    nexus.extendType({
  6      type: "Event",
  7      definition(t) {
  8        t.field("administrators", {
  9          type: nexus.list("String"),
 10        });
 11      },
 12    }),
 13    nexus.mutationField("addEventAdmin", {
 14      type: "EventEntityResponse",
 15      args: {
 16        eventId: nexus.nonNull("ID"),
 17        email: nexus.nonNull("String"),
 18      },
 19    }),
 20    nexus.mutationField("deleteEventAdmin", {
 21      type: "EventEntityResponse",
 22      args: {
 23        eventId: nexus.nonNull("ID"),
 24        email: nexus.nonNull("String"),
 25      },
 26    }),
 27  ],
 28  resolvers: {
 29    Event: {
 30      administrators: (event) =>
 31        event.administrators?.split(/, ?/).filter(Boolean) || [],
 32    },
 33    Mutation: {
 34      addEventAdmin: {
 35        async resolve(_root, args, context) {
 36          // Retrieve targeted event
 37          const event = await strapi.entityService.findOne(
 38            "api::event.event",
 39            args.eventId
 40          );
 41          if (!event) throw new errors.NotFoundError(`Event not found`);
 42
 43          const currentAdmins =
 44            event.administrators?.split(/, ?/).filter(Boolean) || [];
 45
 46          // Check if user is authorized to add event admin
 47          const user = context.state.user;
 48          if (user.email !== event.email && !currentAdmins.includes(user.email))
 49            throw new errors.ForbiddenError();
 50
 51          // Add email to event's administrators list
 52          const sanitizedEmail = args.email.replaceAll(",", "");
 53          const administrators = new Set([...currentAdmins, sanitizedEmail]);
 54          const updatedEvent = await strapi.entityService.update(
 55            "api::event.event",
 56            args.eventId,
 57            {
 58              data: {
 59                administrators: [...administrators].join(", "),
 60              },
 61            }
 62          );
 63
 64          // Create notification for targeted user
 65          const targetedUser = await strapi.db
 66            .query("plugin::users-permissions.user")
 67            .findOne({
 68              where: { email: args.email },
 69            });
 70          if (targetedUser) {
 71            strapi.entityService.create("api::notification.notification", {
 72              data: {
 73                type: "AddedAsAdmin",
 74                event: args.eventId,
 75                user: targetedUser.id,
 76              },
 77            });
 78          } else {
 79            strapi.log.warn(
 80              `No user with email '${args.email}'. Can't create notification AddedAsAdmin for event ${args.eventId}`
 81            );
 82            strapi
 83              .service("api::email.email")
 84              .sendEmailNotif(args.email, "AddedAsAdmin", event.lang, {
 85                event,
 86              });
 87          }
 88
 89          // Send formated response
 90          const { toEntityResponse } = strapi
 91            .plugin("graphql")
 92            .service("format").returnTypes;
 93          return toEntityResponse(updatedEvent, {
 94            args,
 95            resourceUID: "api::event.event",
 96          });
 97        },
 98      },
 99      deleteEventAdmin: {
100        async resolve(_root, args, context) {
101          // Retrieve targeted event
102          const event = await strapi.entityService.findOne(
103            "api::event.event",
104            args.eventId
105          );
106          if (!event) throw new errors.NotFoundError(`Event not found`);
107
108          const currentAdmins = event.administrators?.split(/, ?/) || [];
109
110          // Check if user is authorized to remove event admin
111          const user = context.state.user;
112          if (user.email !== event.email && !currentAdmins.includes(user.email))
113            throw new errors.ForbiddenError();
114
115          // Remove email from event's administrators list
116          const administratorsArray = currentAdmins.filter(
117            (email) => email !== args.email
118          );
119
120          const administrators = administratorsArray.join(", ");
121
122          const updatedEvent = await strapi.entityService.update(
123            "api::event.event",
124            args.eventId,
125            { data: { administrators } }
126          );
127
128          // Send formated response
129          const { toEntityResponse } = strapi
130            .plugin("graphql")
131            .service("format").returnTypes;
132          return toEntityResponse(updatedEvent, {
133            args,
134            resourceUID: "api::event.event",
135          });
136        },
137      },
138    },
139  },
140  resolversConfig: {
141    "Mutation.addEventAdmin": {
142      auth: true,
143    },
144    "Mutation.deleteEventAdmin": {
145      auth: true,
146    },
147  },
148});