@prefabs.tech/fastify-firebase 0.89.1 → 0.90.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,18 +1,18 @@
1
- import N from "fastify-plugin";
2
- import { apps as k, initializeApp as R, credential as F, messaging as A } from "firebase-admin";
1
+ import w from "fastify-plugin";
2
+ import { apps as I, initializeApp as N, credential as R, messaging as k } from "firebase-admin";
3
3
  import { sql as l } from "slonik";
4
- import { DefaultSqlFactory as O, BaseService as _ } from "@prefabs.tech/fastify-slonik";
5
- import { mercurius as c } from "mercurius";
6
- import { gql as D, mergeTypeDefs as C, baseSchema as P } from "@prefabs.tech/fastify-graphql";
7
- const $ = (e, r) => {
8
- if (!(k.length > 0)) {
4
+ import { DefaultSqlFactory as F, BaseService as A } from "@prefabs.tech/fastify-slonik";
5
+ import { mercurius as a } from "mercurius";
6
+ import { gql as E, mergeTypeDefs as $, baseSchema as _ } from "@prefabs.tech/fastify-graphql";
7
+ const P = (e, r) => {
8
+ if (!(I.length > 0)) {
9
9
  if (e.firebase?.enabled !== !1 && !e.firebase.credentials) {
10
10
  r.log.error("Firebase credentials are missing");
11
11
  return;
12
12
  }
13
13
  try {
14
- R({
15
- credential: F.cert({
14
+ N({
15
+ credential: R.cert({
16
16
  projectId: e.firebase.credentials?.projectId,
17
17
  privateKey: e.firebase.credentials?.privateKey.replaceAll(
18
18
  String.raw`\n`,
@@ -26,10 +26,10 @@ const $ = (e, r) => {
26
26
  r.log.error("Failed to initialize firebase"), r.log.error(t);
27
27
  }
28
28
  }
29
- }, w = async (e) => {
30
- await A().sendEachForMulticast(e);
31
- }, M = "/send-notification", B = "/user-device", L = "/user-device", T = "user_devices", z = (e) => {
32
- const r = e.firebase.table?.userDevices?.name || T;
29
+ }, m = async (e) => {
30
+ await k().sendEachForMulticast(e);
31
+ }, O = "/send-notification", M = "/user-device", C = "/user-device", D = "user_devices", B = (e) => {
32
+ const r = e.firebase.table?.userDevices?.name || D;
33
33
  return l.unsafe`
34
34
  DO $$
35
35
  BEGIN
@@ -46,13 +46,13 @@ const $ = (e, r) => {
46
46
  ])} (user_id, device_token);
47
47
  END $$;
48
48
  `;
49
- }, W = async (e, r) => {
49
+ }, L = async (e, r) => {
50
50
  await e.connect(async (t) => {
51
- await t.query(z(r));
51
+ await t.query(B(r));
52
52
  });
53
53
  };
54
- class j extends O {
55
- static TABLE = T;
54
+ class W extends F {
55
+ static TABLE = D;
56
56
  getDeleteExistingTokenSql(r) {
57
57
  return l.type(this.validationSchema)`
58
58
  DELETE
@@ -72,7 +72,7 @@ class j extends O {
72
72
  return this.config.firebase.table?.userDevices?.name || super.table;
73
73
  }
74
74
  }
75
- class v extends _ {
75
+ class v extends A {
76
76
  async getByUserId(r) {
77
77
  const t = this.factory.getFindByUserIdSql(r);
78
78
  return await this.database.connect((i) => i.any(t));
@@ -85,36 +85,31 @@ class v extends _ {
85
85
  return super.factory;
86
86
  }
87
87
  get sqlFactoryClass() {
88
- return j;
88
+ return W;
89
89
  }
90
90
  async preCreate(r) {
91
91
  const { deviceToken: t } = r;
92
92
  return await this.removeByDeviceToken(t), r;
93
93
  }
94
94
  }
95
- const x = async (e, r) => {
95
+ const z = async (e, r) => {
96
96
  if (!e.user)
97
- return r.status(401).send({
98
- error: "Unauthorized",
99
- message: "unauthorized",
100
- statusCode: 401
101
- });
97
+ throw e.server.httpErrors.unauthorized("Unauthorised");
102
98
  const {
103
- body: s,
99
+ body: n,
104
100
  title: i,
105
101
  data: o,
106
102
  userId: d
107
- } = e.body;
108
- if (!d)
109
- throw e.log.error("receiver id is not defined"), new Error("Oops, Please provide a receiver id");
110
- const n = await new v(
103
+ } = e.body, s = await new v(
111
104
  e.config,
112
105
  e.slonik,
113
106
  e.dbSchema
114
107
  ).getByUserId(d);
115
- if (!n || n.length === 0)
116
- throw e.log.error("no device found for the receiver"), new Error("Unable to find device for the receiver");
117
- const u = n.map((g) => g.deviceToken), p = {
108
+ if (!s || s.length === 0)
109
+ throw e.server.httpErrors.unprocessableEntity(
110
+ "No devices found for the receiver"
111
+ );
112
+ const u = s.map((f) => f.deviceToken), p = {
118
113
  android: {
119
114
  priority: "high",
120
115
  notification: {
@@ -131,27 +126,18 @@ const x = async (e, r) => {
131
126
  tokens: u,
132
127
  notification: {
133
128
  title: i,
134
- body: s
129
+ body: n
135
130
  },
136
131
  data: {
137
132
  ...o,
138
133
  title: i,
139
- body: s
134
+ body: n
140
135
  }
141
136
  };
142
- await w(p), r.send({ message: "Notification sent successfully" });
143
- }, q = {
144
- sendNotification: x
145
- }, y = {
146
- type: "object",
147
- properties: {
148
- code: { type: "string" },
149
- error: { type: "object" },
150
- message: { type: "string" },
151
- statusCode: { type: "number" },
152
- status: { type: "string" }
153
- }
154
- }, V = {
137
+ await m(p), r.send({ message: "Notification sent successfully" });
138
+ }, x = {
139
+ sendNotification: z
140
+ }, j = {
155
141
  description: "Send a notification to a specific user",
156
142
  operationId: "sendNotification",
157
143
  body: {
@@ -173,71 +159,50 @@ const x = async (e, r) => {
173
159
  },
174
160
  401: {
175
161
  description: "Unauthorized",
176
- ...y
162
+ $ref: "ErrorResponse#"
177
163
  },
178
164
  500: {
179
- ...y
165
+ $ref: "ErrorResponse#"
180
166
  }
181
167
  },
182
168
  tags: ["notifications"]
183
- }, b = (e) => async () => {
169
+ }, g = (e) => async () => {
184
170
  if (e.config.firebase.enabled === !1)
185
- throw new Error("Firebase is not enabled");
186
- }, H = async (e) => {
171
+ throw e.httpErrors.notFound("Firebase is disabled");
172
+ }, V = async (e) => {
187
173
  const r = e.config.firebase.handlers?.userDevice, t = e.config.firebase.notification;
188
174
  t?.test?.enabled && e.post(
189
- t.test.path || M,
175
+ t.test.path || O,
190
176
  {
191
- preHandler: [e.verifySession(), b(e)],
192
- schema: V
177
+ preHandler: [e.verifySession(), g(e)],
178
+ schema: j
193
179
  },
194
- r?.addUserDevice || q.sendNotification
180
+ r?.addUserDevice || x.sendNotification
195
181
  );
196
- }, Y = async (e, r) => {
197
- const { body: t, config: s, dbSchema: i, log: o, slonik: d, user: a } = e;
198
- if (!a)
199
- return r.status(401).send({
200
- error: "Unauthorized",
201
- message: "unauthorized",
202
- statusCode: 401
203
- });
204
- const { deviceToken: n } = t;
205
- if (!n)
206
- throw o.error("device token is not defined"), new Error("Oops, Something went wrong");
207
- const u = new v(s, d, i);
208
- r.send(await u.create({ userId: a.id, deviceToken: n }));
209
- }, G = async (e, r) => {
182
+ }, q = async (e, r) => {
183
+ const { body: t, config: n, dbSchema: i, slonik: o, user: d } = e;
184
+ if (!d)
185
+ throw e.server.httpErrors.unauthorized("Unauthorised");
186
+ const { deviceToken: c } = t, s = new v(n, o, i);
187
+ r.send(await s.create({ userId: d.id, deviceToken: c }));
188
+ }, H = async (e, r) => {
210
189
  const t = e.user;
211
190
  if (!t)
212
- return r.status(401).send({
213
- error: "Unauthorized",
214
- message: "unauthorized",
215
- statusCode: 401
216
- });
217
- const { deviceToken: s } = e.body;
218
- if (!s)
219
- throw e.log.error("device token is not defined"), new Error("Oops, Something went wrong");
220
- const i = new v(e.config, e.slonik, e.dbSchema), o = await i.getByUserId(t.id);
191
+ throw e.server.httpErrors.unauthorized("Unauthorised");
192
+ const { deviceToken: n } = e.body, i = new v(e.config, e.slonik, e.dbSchema), o = await i.getByUserId(t.id);
221
193
  if (!o || o.length === 0)
222
- throw e.log.error("No devices found for user"), new Error("Oops, Something went wrong");
194
+ throw e.server.httpErrors.notFound("No devices found for the user");
223
195
  if (!o.find(
224
- (a) => a.deviceToken === s
196
+ (c) => c.deviceToken === n
225
197
  ))
226
- throw e.log.error("device requested to delete not owned by user"), new Error("Oops, Something went wrong");
227
- r.send(await i.removeByDeviceToken(s));
228
- }, E = {
229
- addUserDevice: Y,
230
- removeUserDevice: G
231
- }, f = {
232
- type: "object",
233
- properties: {
234
- code: { type: "string" },
235
- error: { type: "object" },
236
- message: { type: "string" },
237
- statusCode: { type: "number" },
238
- status: { type: "string" }
239
- }
240
- }, S = {
198
+ throw e.server.httpErrors.unprocessableEntity(
199
+ "Device requested to delete not owned by user"
200
+ );
201
+ r.send(await i.removeByDeviceToken(n));
202
+ }, y = {
203
+ addUserDevice: q,
204
+ removeUserDevice: H
205
+ }, T = {
241
206
  type: "object",
242
207
  properties: {
243
208
  userId: { type: "string" },
@@ -246,7 +211,7 @@ const x = async (e, r) => {
246
211
  updatedAt: { type: "number" }
247
212
  },
248
213
  required: ["userId", "deviceToken", "createdAt", "updatedAt"]
249
- }, K = {
214
+ }, Q = {
250
215
  description: "Delete a user device by device token",
251
216
  operationId: "deleteUserDevice",
252
217
  body: {
@@ -258,19 +223,19 @@ const x = async (e, r) => {
258
223
  },
259
224
  response: {
260
225
  200: {
261
- ...S,
226
+ ...T,
262
227
  nullable: !0
263
228
  },
264
229
  401: {
265
230
  description: "Unauthorized",
266
- ...f
231
+ $ref: "ErrorResponse#"
267
232
  },
268
233
  500: {
269
- ...f
234
+ $ref: "ErrorResponse#"
270
235
  }
271
236
  },
272
237
  tags: ["user-devices"]
273
- }, Q = {
238
+ }, Y = {
274
239
  description: "Register a new user device",
275
240
  operationId: "postUserDevice",
276
241
  body: {
@@ -282,93 +247,93 @@ const x = async (e, r) => {
282
247
  },
283
248
  response: {
284
249
  200: {
285
- ...S,
250
+ ...T,
286
251
  nullable: !0
287
252
  },
288
253
  401: {
289
254
  description: "Unauthorized",
290
- ...f
255
+ $ref: "ErrorResponse#"
291
256
  },
292
257
  500: {
293
- ...f
258
+ $ref: "ErrorResponse#"
294
259
  }
295
260
  },
296
261
  tags: ["user-devices"]
297
- }, X = async (e) => {
262
+ }, G = async (e) => {
298
263
  const r = e.config.firebase.handlers?.userDevice;
299
264
  e.post(
300
- B,
265
+ M,
301
266
  {
302
- preHandler: [e.verifySession(), b(e)],
303
- schema: Q
267
+ preHandler: [e.verifySession(), g(e)],
268
+ schema: Y
304
269
  },
305
- r?.addUserDevice || E.addUserDevice
270
+ r?.addUserDevice || y.addUserDevice
306
271
  ), e.delete(
307
- L,
272
+ C,
308
273
  {
309
- preHandler: [e.verifySession(), b(e)],
310
- schema: K
274
+ preHandler: [e.verifySession(), g(e)],
275
+ schema: Q
311
276
  },
312
- r?.removeUserDevice || E.removeUserDevice
277
+ r?.removeUserDevice || y.removeUserDevice
313
278
  );
314
- }, J = async (e) => {
315
- const { config: r, slonik: t, log: s } = e;
316
- r.firebase.enabled === !1 ? s.info("fastify-firebase plugin is not enabled") : (s.info("Registering fastify-firebase plugin"), await W(t, r), $(r, e));
279
+ }, K = async (e) => {
280
+ const { config: r, slonik: t, log: n } = e;
281
+ r.firebase.enabled === !1 ? n.info("fastify-firebase plugin is not enabled") : (n.info("Registering fastify-firebase plugin"), await L(t, r), P(r, e));
317
282
  const { routePrefix: i, routes: o } = r.firebase;
318
- o?.notifications?.disabled || await e.register(H, { prefix: i }), o?.userDevices?.disabled || await e.register(X, { prefix: i });
319
- }, le = N(J), Z = {
283
+ o?.notifications?.disabled || await e.register(V, { prefix: i }), o?.userDevices?.disabled || await e.register(G, { prefix: i });
284
+ }, ue = w(K), X = {
320
285
  sendNotification: async (e, r, t) => {
321
- const { app: s, config: i, dbSchema: o, database: d, user: a } = t;
322
- if (!a)
323
- return new c.ErrorWithProps("unauthorized", {}, 401);
286
+ const { app: n, config: i, dbSchema: o, database: d, user: c } = t;
287
+ if (!c)
288
+ return new a.ErrorWithProps("unauthorized", {}, 401);
324
289
  if (i.firebase.enabled === !1)
325
- return new c.ErrorWithProps("Firebase is not enabled", {}, 404);
290
+ return new a.ErrorWithProps("Firebase is not enabled", {}, 404);
326
291
  try {
327
- const { userId: n, title: u, body: p, data: g } = r.data;
328
- if (!n)
329
- return new c.ErrorWithProps("Receiver id is required", {}, 400);
292
+ const { userId: s, title: u, body: p, data: f } = r.data;
293
+ if (!s)
294
+ return new a.ErrorWithProps("Receiver id is required", {}, 400);
330
295
  const h = await new v(
331
296
  i,
332
297
  d,
333
298
  o
334
- ).getByUserId(n);
299
+ ).getByUserId(s);
335
300
  if (!h || h.length === 0)
336
- return new c.ErrorWithProps(
301
+ return new a.ErrorWithProps(
337
302
  "Receiver device not found",
338
303
  {},
339
304
  404
340
305
  );
341
- const U = {
306
+ const S = {
342
307
  tokens: h.map(
343
- (I) => I.deviceToken
308
+ (U) => U.deviceToken
344
309
  ),
345
310
  notification: {
346
311
  title: u,
347
312
  body: p
348
313
  },
349
- data: g
314
+ data: f
350
315
  };
351
- return await w(U), { message: "Notification sent successfully" };
352
- } catch (n) {
353
- return s.log.error(n), new c.ErrorWithProps(
316
+ return await m(S), { message: "Notification sent successfully" };
317
+ } catch (s) {
318
+ return n.log.error(s), new a.ErrorWithProps(
354
319
  "Oops, Something went wrong",
355
320
  {},
356
321
  500
357
322
  );
358
323
  }
359
324
  }
360
- }, ee = {}, ve = { Mutation: Z, Query: ee }, re = {
325
+ }, J = {}, pe = { Mutation: X, Query: J }, Z = {
361
326
  addUserDevice: async (e, r, t) => {
362
- const { app: s, config: i, dbSchema: o, database: d, user: a } = t;
327
+ const { app: n, config: i, dbSchema: o, database: d, user: c } = t;
363
328
  if (i.firebase.enabled === !1)
364
- return new c.ErrorWithProps("Firebase is not enabled", {}, 404);
365
- if (!a)
366
- return new c.ErrorWithProps("unauthorized", {}, 401);
329
+ return new a.ErrorWithProps("Firebase is not enabled", {}, 404);
330
+ if (!c)
331
+ return new a.ErrorWithProps("unauthorized", {}, 401);
367
332
  try {
368
- const { deviceToken: n } = r.data;
369
- return await new v(i, d, o).create({ userId: a.id, deviceToken: n });
370
- } catch (n) {
371
- return s.log.error(n), new c.ErrorWithProps(
333
+ const { deviceToken: s } = r.data;
334
+ return await new v(i, d, o).create({ userId: c.id, deviceToken: s });
335
+ } catch (s) {
336
+ return n.log.error(s), new a.ErrorWithProps(
372
337
  "Oops, Something went wrong",
373
338
  {},
374
339
  500
@@ -376,33 +341,33 @@ const x = async (e, r) => {
376
341
  }
377
342
  },
378
343
  removeUserDevice: async (e, r, t) => {
379
- const { app: s, config: i, dbSchema: o, database: d, user: a } = t;
344
+ const { app: n, config: i, dbSchema: o, database: d, user: c } = t;
380
345
  if (i.firebase.enabled === !1)
381
- return new c.ErrorWithProps("Firebase is not enabled", {}, 404);
382
- if (!a)
383
- return new c.ErrorWithProps("unauthorized", {}, 401);
346
+ return new a.ErrorWithProps("Firebase is not enabled", {}, 404);
347
+ if (!c)
348
+ return new a.ErrorWithProps("unauthorized", {}, 401);
384
349
  try {
385
- const { deviceToken: n } = r.data, u = new v(i, d, o), p = await u.getByUserId(a.id);
386
- return !p || p.length === 0 ? new c.ErrorWithProps(
350
+ const { deviceToken: s } = r.data, u = new v(i, d, o), p = await u.getByUserId(c.id);
351
+ return !p || p.length === 0 ? new a.ErrorWithProps(
387
352
  "No devices found for user",
388
353
  {},
389
354
  403
390
355
  ) : p.find(
391
- (m) => m.deviceToken === n
392
- ) ? await u.removeByDeviceToken(n) : new c.ErrorWithProps(
356
+ (b) => b.deviceToken === s
357
+ ) ? await u.removeByDeviceToken(s) : new a.ErrorWithProps(
393
358
  "Device requested to delete not owned by user",
394
359
  {},
395
360
  403
396
361
  );
397
- } catch (n) {
398
- return s.log.error(n), new c.ErrorWithProps(
362
+ } catch (s) {
363
+ return n.log.error(s), new a.ErrorWithProps(
399
364
  "Oops, Something went wrong",
400
365
  {},
401
366
  500
402
367
  );
403
368
  }
404
369
  }
405
- }, te = {}, ge = { Mutation: re, Query: te }, ie = D`
370
+ }, ee = {}, le = { Mutation: Z, Query: ee }, re = E`
406
371
  type SendNotificationResponse {
407
372
  message: String!
408
373
  }
@@ -417,7 +382,7 @@ const x = async (e, r) => {
417
382
  sendNotification(data: SendNotificationInput): SendNotificationResponse
418
383
  @auth
419
384
  }
420
- `, ne = D`
385
+ `, te = E`
421
386
  type UserDevice {
422
387
  id: Int!
423
388
  userId: String!
@@ -446,19 +411,24 @@ const x = async (e, r) => {
446
411
  addUserDevice(data: UserDeviceCreateInput): UserDevice @auth
447
412
  removeUserDevice(data: UserDeviceRemoveInput): UserDevice @auth
448
413
  }
449
- `, fe = C([
450
- P,
451
- ie,
452
- ne
414
+ `, ve = $([
415
+ _,
416
+ re,
417
+ te
453
418
  ]);
454
419
  export {
420
+ O as ROUTE_SEND_NOTIFICATION,
421
+ M as ROUTE_USER_DEVICE_ADD,
422
+ C as ROUTE_USER_DEVICE_REMOVE,
423
+ D as TABLE_USER_DEVICES,
455
424
  v as UserDeviceService,
456
- le as default,
457
- fe as firebaseSchema,
458
- $ as initializeFirebase,
459
- ve as notificationResolver,
460
- H as notificationRoutes,
461
- w as sendPushNotification,
462
- ge as userDeviceResolver,
463
- X as userDeviceRoutes
425
+ B as createUserDevicesTableQuery,
426
+ ue as default,
427
+ ve as firebaseSchema,
428
+ P as initializeFirebase,
429
+ pe as notificationResolver,
430
+ V as notificationRoutes,
431
+ m as sendPushNotification,
432
+ le as userDeviceResolver,
433
+ G as userDeviceRoutes
464
434
  };
@@ -1,8 +1,8 @@
1
- (function(n,g){typeof exports=="object"&&typeof module<"u"?g(exports,require("fastify-plugin"),require("firebase-admin"),require("slonik"),require("@prefabs.tech/fastify-slonik"),require("mercurius"),require("@prefabs.tech/fastify-graphql")):typeof define=="function"&&define.amd?define(["exports","fastify-plugin","firebase-admin","slonik","@prefabs.tech/fastify-slonik","mercurius","@prefabs.tech/fastify-graphql"],g):(n=typeof globalThis<"u"?globalThis:n||self,g(n.PrefabsTechFastifyFirebase={},n.FastifyPlugin,n.FirebaseAdmin,n.Slonik,n.PrefabsTechFastifySlonik,n.mercurius,n.PrefabsTechFastifyGraphql))})(this,function(n,g,h,p,S,c,y){"use strict";const w=(e,t)=>{if(!(h.apps.length>0)){if(e.firebase?.enabled!==!1&&!e.firebase.credentials){t.log.error("Firebase credentials are missing");return}try{h.initializeApp({credential:h.credential.cert({projectId:e.firebase.credentials?.projectId,privateKey:e.firebase.credentials?.privateKey.replaceAll(String.raw`\n`,`
2
- `),clientEmail:e.firebase.credentials?.clientEmail})})}catch(r){t.log.error("Failed to initialize firebase"),t.log.error(r)}}},T=async e=>{await h.messaging().sendEachForMulticast(e)},A="/send-notification",_="/user-device",O="/user-device",U="user_devices",C=e=>{const t=e.firebase.table?.userDevices?.name||U;return p.sql.unsafe`
1
+ (function(i,h){typeof exports=="object"&&typeof module<"u"?h(exports,require("fastify-plugin"),require("firebase-admin"),require("slonik"),require("@prefabs.tech/fastify-slonik"),require("mercurius"),require("@prefabs.tech/fastify-graphql")):typeof define=="function"&&define.amd?define(["exports","fastify-plugin","firebase-admin","slonik","@prefabs.tech/fastify-slonik","mercurius","@prefabs.tech/fastify-graphql"],h):(i=typeof globalThis<"u"?globalThis:i||self,h(i.PrefabsTechFastifyFirebase={},i.FastifyPlugin,i.FirebaseAdmin,i.Slonik,i.PrefabsTechFastifySlonik,i.mercurius,i.PrefabsTechFastifyGraphql))})(this,function(i,h,g,l,S,c,E){"use strict";const U=(e,r)=>{if(!(g.apps.length>0)){if(e.firebase?.enabled!==!1&&!e.firebase.credentials){r.log.error("Firebase credentials are missing");return}try{g.initializeApp({credential:g.credential.cert({projectId:e.firebase.credentials?.projectId,privateKey:e.firebase.credentials?.privateKey.replaceAll(String.raw`\n`,`
2
+ `),clientEmail:e.firebase.credentials?.clientEmail})})}catch(t){r.log.error("Failed to initialize firebase"),r.log.error(t)}}},y=async e=>{await g.messaging().sendEachForMulticast(e)},I="/send-notification",w="/user-device",R="/user-device",D="user_devices",N=e=>{const r=e.firebase.table?.userDevices?.name||D;return l.sql.unsafe`
3
3
  DO $$
4
4
  BEGIN
5
- CREATE TABLE IF NOT EXISTS ${p.sql.identifier([t])} (
5
+ CREATE TABLE IF NOT EXISTS ${l.sql.identifier([r])} (
6
6
  id INT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
7
7
  user_id VARCHAR(255) NOT NULL,
8
8
  device_token VARCHAR(255) NOT NULL,
@@ -10,18 +10,18 @@
10
10
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
11
11
  );
12
12
 
13
- CREATE INDEX IF NOT EXISTS idx_user_id_device_token ON ${p.sql.identifier([t])} (user_id, device_token);
13
+ CREATE INDEX IF NOT EXISTS idx_user_id_device_token ON ${l.sql.identifier([r])} (user_id, device_token);
14
14
  END $$;
15
- `},M=async(e,t)=>{await e.connect(async r=>{await r.query(C(t))})};class $ extends S.DefaultSqlFactory{static TABLE=U;getDeleteExistingTokenSql(t){return p.sql.type(this.validationSchema)`
15
+ `},$=async(e,r)=>{await e.connect(async t=>{await t.query(N(r))})};class O extends S.DefaultSqlFactory{static TABLE=D;getDeleteExistingTokenSql(r){return l.sql.type(this.validationSchema)`
16
16
  DELETE
17
17
  FROM ${this.tableFragment}
18
- ${this.getWhereFragment({filterFragment:p.sql.fragment`device_token = ${t}`})}
18
+ ${this.getWhereFragment({filterFragment:l.sql.fragment`device_token = ${r}`})}
19
19
  RETURNING *;
20
- `}getFindByUserIdSql(t){return p.sql.type(this.validationSchema)`
20
+ `}getFindByUserIdSql(r){return l.sql.type(this.validationSchema)`
21
21
  SELECT *
22
22
  FROM ${this.tableFragment}
23
- ${this.getWhereFragment({filterFragment:p.sql.fragment`user_id = ${t}`})};
24
- `}get table(){return this.config.firebase.table?.userDevices?.name||super.table}}class v extends S.BaseService{async getByUserId(t){const r=this.factory.getFindByUserIdSql(t);return await this.database.connect(i=>i.any(r))}async removeByDeviceToken(t){const r=this.factory.getDeleteExistingTokenSql(t);return await this.database.connect(i=>i.maybeOne(r))}get factory(){return super.factory}get sqlFactoryClass(){return $}async preCreate(t){const{deviceToken:r}=t;return await this.removeByDeviceToken(r),t}}const q={sendNotification:async(e,t)=>{if(!e.user)return t.status(401).send({error:"Unauthorized",message:"unauthorized",statusCode:401});const{body:o,title:i,data:a,userId:u}=e.body;if(!u)throw e.log.error("receiver id is not defined"),new Error("Oops, Please provide a receiver id");const s=await new v(e.config,e.slonik,e.dbSchema).getByUserId(u);if(!s||s.length===0)throw e.log.error("no device found for the receiver"),new Error("Unable to find device for the receiver");const l=s.map(m=>m.deviceToken),f={android:{priority:"high",notification:{sound:"default"}},apns:{payload:{aps:{sound:"default"}}},tokens:l,notification:{title:i,body:o},data:{...a,title:i,body:o}};await T(f),t.send({message:"Notification sent successfully"})}},I={type:"object",properties:{code:{type:"string"},error:{type:"object"},message:{type:"string"},statusCode:{type:"number"},status:{type:"string"}}},B={description:"Send a notification to a specific user",operationId:"sendNotification",body:{type:"object",properties:{title:{type:"string"},message:{type:"string"},userId:{type:"string"}},required:["title","message","userId"]},response:{200:{type:"object",properties:{success:{type:"boolean"},message:{type:"string"}}},401:{description:"Unauthorized",...I},500:{...I}},tags:["notifications"]},D=e=>async()=>{if(e.config.firebase.enabled===!1)throw new Error("Firebase is not enabled")},N=async e=>{const t=e.config.firebase.handlers?.userDevice,r=e.config.firebase.notification;r?.test?.enabled&&e.post(r.test.path||A,{preHandler:[e.verifySession(),D(e)],schema:B},t?.addUserDevice||q.sendNotification)},k={addUserDevice:async(e,t)=>{const{body:r,config:o,dbSchema:i,log:a,slonik:u,user:d}=e;if(!d)return t.status(401).send({error:"Unauthorized",message:"unauthorized",statusCode:401});const{deviceToken:s}=r;if(!s)throw a.error("device token is not defined"),new Error("Oops, Something went wrong");const l=new v(o,u,i);t.send(await l.create({userId:d.id,deviceToken:s}))},removeUserDevice:async(e,t)=>{const r=e.user;if(!r)return t.status(401).send({error:"Unauthorized",message:"unauthorized",statusCode:401});const{deviceToken:o}=e.body;if(!o)throw e.log.error("device token is not defined"),new Error("Oops, Something went wrong");const i=new v(e.config,e.slonik,e.dbSchema),a=await i.getByUserId(r.id);if(!a||a.length===0)throw e.log.error("No devices found for user"),new Error("Oops, Something went wrong");if(!a.find(d=>d.deviceToken===o))throw e.log.error("device requested to delete not owned by user"),new Error("Oops, Something went wrong");t.send(await i.removeByDeviceToken(o))}},b={type:"object",properties:{code:{type:"string"},error:{type:"object"},message:{type:"string"},statusCode:{type:"number"},status:{type:"string"}}},F={type:"object",properties:{userId:{type:"string"},deviceToken:{type:"string"},createdAt:{type:"number"},updatedAt:{type:"number"}},required:["userId","deviceToken","createdAt","updatedAt"]},z={description:"Delete a user device by device token",operationId:"deleteUserDevice",body:{type:"object",properties:{deviceToken:{type:"string"}},required:["deviceToken"]},response:{200:{...F,nullable:!0},401:{description:"Unauthorized",...b},500:{...b}},tags:["user-devices"]},L={description:"Register a new user device",operationId:"postUserDevice",body:{type:"object",properties:{deviceToken:{type:"string"}},required:["deviceToken"]},response:{200:{...F,nullable:!0},401:{description:"Unauthorized",...b},500:{...b}},tags:["user-devices"]},R=async e=>{const t=e.config.firebase.handlers?.userDevice;e.post(_,{preHandler:[e.verifySession(),D(e)],schema:L},t?.addUserDevice||k.addUserDevice),e.delete(O,{preHandler:[e.verifySession(),D(e)],schema:z},t?.removeUserDevice||k.removeUserDevice)},W=g(async e=>{const{config:t,slonik:r,log:o}=e;t.firebase.enabled===!1?o.info("fastify-firebase plugin is not enabled"):(o.info("Registering fastify-firebase plugin"),await M(r,t),w(t,e));const{routePrefix:i,routes:a}=t.firebase;a?.notifications?.disabled||await e.register(N,{prefix:i}),a?.userDevices?.disabled||await e.register(R,{prefix:i})}),j={Mutation:{sendNotification:async(e,t,r)=>{const{app:o,config:i,dbSchema:a,database:u,user:d}=r;if(!d)return new c.mercurius.ErrorWithProps("unauthorized",{},401);if(i.firebase.enabled===!1)return new c.mercurius.ErrorWithProps("Firebase is not enabled",{},404);try{const{userId:s,title:l,body:f,data:m}=t.data;if(!s)return new c.mercurius.ErrorWithProps("Receiver id is required",{},400);const E=await new v(i,u,a).getByUserId(s);if(!E||E.length===0)return new c.mercurius.ErrorWithProps("Receiver device not found",{},404);const K={tokens:E.map(X=>X.deviceToken),notification:{title:l,body:f},data:m};return await T(K),{message:"Notification sent successfully"}}catch(s){return o.log.error(s),new c.mercurius.ErrorWithProps("Oops, Something went wrong",{},500)}}},Query:{}},V={Mutation:{addUserDevice:async(e,t,r)=>{const{app:o,config:i,dbSchema:a,database:u,user:d}=r;if(i.firebase.enabled===!1)return new c.mercurius.ErrorWithProps("Firebase is not enabled",{},404);if(!d)return new c.mercurius.ErrorWithProps("unauthorized",{},401);try{const{deviceToken:s}=t.data;return await new v(i,u,a).create({userId:d.id,deviceToken:s})}catch(s){return o.log.error(s),new c.mercurius.ErrorWithProps("Oops, Something went wrong",{},500)}},removeUserDevice:async(e,t,r)=>{const{app:o,config:i,dbSchema:a,database:u,user:d}=r;if(i.firebase.enabled===!1)return new c.mercurius.ErrorWithProps("Firebase is not enabled",{},404);if(!d)return new c.mercurius.ErrorWithProps("unauthorized",{},401);try{const{deviceToken:s}=t.data,l=new v(i,u,a),f=await l.getByUserId(d.id);return!f||f.length===0?new c.mercurius.ErrorWithProps("No devices found for user",{},403):f.find(P=>P.deviceToken===s)?await l.removeByDeviceToken(s):new c.mercurius.ErrorWithProps("Device requested to delete not owned by user",{},403)}catch(s){return o.log.error(s),new c.mercurius.ErrorWithProps("Oops, Something went wrong",{},500)}}},Query:{}},H=y.gql`
23
+ ${this.getWhereFragment({filterFragment:l.sql.fragment`user_id = ${r}`})};
24
+ `}get table(){return this.config.firebase.table?.userDevices?.name||super.table}}class v extends S.BaseService{async getByUserId(r){const t=this.factory.getFindByUserIdSql(r);return await this.database.connect(n=>n.any(t))}async removeByDeviceToken(r){const t=this.factory.getDeleteExistingTokenSql(r);return await this.database.connect(n=>n.maybeOne(t))}get factory(){return super.factory}get sqlFactoryClass(){return O}async preCreate(r){const{deviceToken:t}=r;return await this.removeByDeviceToken(t),r}}const M={sendNotification:async(e,r)=>{if(!e.user)throw e.server.httpErrors.unauthorized("Unauthorised");const{body:o,title:n,data:a,userId:u}=e.body,s=await new v(e.config,e.slonik,e.dbSchema).getByUserId(u);if(!s||s.length===0)throw e.server.httpErrors.unprocessableEntity("No devices found for the receiver");const p=s.map(b=>b.deviceToken),f={android:{priority:"high",notification:{sound:"default"}},apns:{payload:{aps:{sound:"default"}}},tokens:p,notification:{title:n,body:o},data:{...a,title:n,body:o}};await y(f),r.send({message:"Notification sent successfully"})}},C={description:"Send a notification to a specific user",operationId:"sendNotification",body:{type:"object",properties:{title:{type:"string"},message:{type:"string"},userId:{type:"string"}},required:["title","message","userId"]},response:{200:{type:"object",properties:{success:{type:"boolean"},message:{type:"string"}}},401:{description:"Unauthorized",$ref:"ErrorResponse#"},500:{$ref:"ErrorResponse#"}},tags:["notifications"]},T=e=>async()=>{if(e.config.firebase.enabled===!1)throw e.httpErrors.notFound("Firebase is disabled")},F=async e=>{const r=e.config.firebase.handlers?.userDevice,t=e.config.firebase.notification;t?.test?.enabled&&e.post(t.test.path||I,{preHandler:[e.verifySession(),T(e)],schema:C},r?.addUserDevice||M.sendNotification)},_={addUserDevice:async(e,r)=>{const{body:t,config:o,dbSchema:n,slonik:a,user:u}=e;if(!u)throw e.server.httpErrors.unauthorized("Unauthorised");const{deviceToken:d}=t,s=new v(o,a,n);r.send(await s.create({userId:u.id,deviceToken:d}))},removeUserDevice:async(e,r)=>{const t=e.user;if(!t)throw e.server.httpErrors.unauthorized("Unauthorised");const{deviceToken:o}=e.body,n=new v(e.config,e.slonik,e.dbSchema),a=await n.getByUserId(t.id);if(!a||a.length===0)throw e.server.httpErrors.notFound("No devices found for the user");if(!a.find(d=>d.deviceToken===o))throw e.server.httpErrors.unprocessableEntity("Device requested to delete not owned by user");r.send(await n.removeByDeviceToken(o))}},k={type:"object",properties:{userId:{type:"string"},deviceToken:{type:"string"},createdAt:{type:"number"},updatedAt:{type:"number"}},required:["userId","deviceToken","createdAt","updatedAt"]},q={description:"Delete a user device by device token",operationId:"deleteUserDevice",body:{type:"object",properties:{deviceToken:{type:"string"}},required:["deviceToken"]},response:{200:{...k,nullable:!0},401:{description:"Unauthorized",$ref:"ErrorResponse#"},500:{$ref:"ErrorResponse#"}},tags:["user-devices"]},B={description:"Register a new user device",operationId:"postUserDevice",body:{type:"object",properties:{deviceToken:{type:"string"}},required:["deviceToken"]},response:{200:{...k,nullable:!0},401:{description:"Unauthorized",$ref:"ErrorResponse#"},500:{$ref:"ErrorResponse#"}},tags:["user-devices"]},A=async e=>{const r=e.config.firebase.handlers?.userDevice;e.post(w,{preHandler:[e.verifySession(),T(e)],schema:B},r?.addUserDevice||_.addUserDevice),e.delete(R,{preHandler:[e.verifySession(),T(e)],schema:q},r?.removeUserDevice||_.removeUserDevice)},L=h(async e=>{const{config:r,slonik:t,log:o}=e;r.firebase.enabled===!1?o.info("fastify-firebase plugin is not enabled"):(o.info("Registering fastify-firebase plugin"),await $(t,r),U(r,e));const{routePrefix:n,routes:a}=r.firebase;a?.notifications?.disabled||await e.register(F,{prefix:n}),a?.userDevices?.disabled||await e.register(A,{prefix:n})}),W={Mutation:{sendNotification:async(e,r,t)=>{const{app:o,config:n,dbSchema:a,database:u,user:d}=t;if(!d)return new c.mercurius.ErrorWithProps("unauthorized",{},401);if(n.firebase.enabled===!1)return new c.mercurius.ErrorWithProps("Firebase is not enabled",{},404);try{const{userId:s,title:p,body:f,data:b}=r.data;if(!s)return new c.mercurius.ErrorWithProps("Receiver id is required",{},400);const m=await new v(n,u,a).getByUserId(s);if(!m||m.length===0)return new c.mercurius.ErrorWithProps("Receiver device not found",{},404);const H={tokens:m.map(Y=>Y.deviceToken),notification:{title:p,body:f},data:b};return await y(H),{message:"Notification sent successfully"}}catch(s){return o.log.error(s),new c.mercurius.ErrorWithProps("Oops, Something went wrong",{},500)}}},Query:{}},z={Mutation:{addUserDevice:async(e,r,t)=>{const{app:o,config:n,dbSchema:a,database:u,user:d}=t;if(n.firebase.enabled===!1)return new c.mercurius.ErrorWithProps("Firebase is not enabled",{},404);if(!d)return new c.mercurius.ErrorWithProps("unauthorized",{},401);try{const{deviceToken:s}=r.data;return await new v(n,u,a).create({userId:d.id,deviceToken:s})}catch(s){return o.log.error(s),new c.mercurius.ErrorWithProps("Oops, Something went wrong",{},500)}},removeUserDevice:async(e,r,t)=>{const{app:o,config:n,dbSchema:a,database:u,user:d}=t;if(n.firebase.enabled===!1)return new c.mercurius.ErrorWithProps("Firebase is not enabled",{},404);if(!d)return new c.mercurius.ErrorWithProps("unauthorized",{},401);try{const{deviceToken:s}=r.data,p=new v(n,u,a),f=await p.getByUserId(d.id);return!f||f.length===0?new c.mercurius.ErrorWithProps("No devices found for user",{},403):f.find(P=>P.deviceToken===s)?await p.removeByDeviceToken(s):new c.mercurius.ErrorWithProps("Device requested to delete not owned by user",{},403)}catch(s){return o.log.error(s),new c.mercurius.ErrorWithProps("Oops, Something went wrong",{},500)}}},Query:{}},V=E.gql`
25
25
  type SendNotificationResponse {
26
26
  message: String!
27
27
  }
@@ -36,7 +36,7 @@
36
36
  sendNotification(data: SendNotificationInput): SendNotificationResponse
37
37
  @auth
38
38
  }
39
- `,Q=y.gql`
39
+ `,j=E.gql`
40
40
  type UserDevice {
41
41
  id: Int!
42
42
  userId: String!
@@ -65,4 +65,4 @@
65
65
  addUserDevice(data: UserDeviceCreateInput): UserDevice @auth
66
66
  removeUserDevice(data: UserDeviceRemoveInput): UserDevice @auth
67
67
  }
68
- `,Y=y.mergeTypeDefs([y.baseSchema,H,Q]);n.UserDeviceService=v,n.default=W,n.firebaseSchema=Y,n.initializeFirebase=w,n.notificationResolver=j,n.notificationRoutes=N,n.sendPushNotification=T,n.userDeviceResolver=V,n.userDeviceRoutes=R,Object.defineProperties(n,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
68
+ `,Q=E.mergeTypeDefs([E.baseSchema,V,j]);i.ROUTE_SEND_NOTIFICATION=I,i.ROUTE_USER_DEVICE_ADD=w,i.ROUTE_USER_DEVICE_REMOVE=R,i.TABLE_USER_DEVICES=D,i.UserDeviceService=v,i.createUserDevicesTableQuery=N,i.default=L,i.firebaseSchema=Q,i.initializeFirebase=U,i.notificationResolver=W,i.notificationRoutes=F,i.sendPushNotification=y,i.userDeviceResolver=z,i.userDeviceRoutes=A,Object.defineProperties(i,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});