backend/src/graphql/notification/index.ts (view raw)
1import pMap from "p-map";
2
3export default [
4 ({ nexus, strapi }) => ({
5 types: [
6 nexus.mutationField("readNotifications", {
7 type: "NotificationEntityResponseCollection",
8 args: {
9 id: "ID",
10 },
11 }),
12 ],
13 resolvers: {
14 Query: {
15 notifications: {
16 async resolve(_root, args, context) {
17 const user = context.state.user;
18 const userNotifications = await strapi.entityService.findMany(
19 "api::notification.notification",
20 {
21 filters: {
22 user: { id: { $eq: user.id } },
23 event: { id: { $notNull: true } },
24 },
25 sort: { createdAt: "DESC" },
26 limit: args?.pagination?.limit || 20,
27 }
28 );
29 return {
30 nodes: userNotifications,
31 info: { args, resourceUID: "api::notification.notification" },
32 };
33 },
34 },
35 },
36 Mutation: {
37 readNotifications: {
38 async resolve(_root, args, context) {
39 const user = context.state.user;
40 const { id } = args;
41
42 const { toEntityResponseCollection } = strapi
43 .plugin("graphql")
44 .service("format").returnTypes;
45
46 let idFilter = {};
47 if (id) idFilter = { id };
48
49 const userNotifications = await strapi.entityService.findMany(
50 "api::notification.notification",
51 {
52 filters: {
53 user: { id: user.id },
54 read: false,
55 ...idFilter,
56 },
57 }
58 );
59 const updatedNotifications = await pMap(
60 userNotifications,
61 (notification: { id: "string" }) =>
62 strapi.entityService.update(
63 "api::notification.notification",
64 notification.id,
65 { data: { read: true } }
66 )
67 );
68 return toEntityResponseCollection(updatedNotifications, {
69 resourceUID: "api::notification.notification",
70 });
71 },
72 id: {
73 description:
74 "Notification ID to read. If no ID is provided, all user's notifications are set as read.",
75 },
76 },
77 },
78 },
79 resolversConfig: {
80 "Query.notifications": {
81 auth: true,
82 },
83 "Mutation.readNotifications": {
84 auth: true,
85 },
86 "Notification.event": {
87 auth: true,
88 },
89 },
90 }),
91];