@prefabs.tech/fastify-firebase 0.89.0 → 0.89.2
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.
- package/dist/prefabs-tech-fastify-firebase.js +13 -8
- package/dist/prefabs-tech-fastify-firebase.umd.cjs +11 -11
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/types/index.d.ts +2 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/migrations/queries.d.ts +6 -0
- package/dist/types/migrations/queries.d.ts.map +1 -0
- package/package.json +7 -7
- package/dist/types/migrations/queryToCreateTable.d.ts +0 -6
- package/dist/types/migrations/queryToCreateTable.d.ts.map +0 -1
|
@@ -193,7 +193,7 @@ const x = async (e, r) => {
|
|
|
193
193
|
},
|
|
194
194
|
r?.addUserDevice || q.sendNotification
|
|
195
195
|
);
|
|
196
|
-
},
|
|
196
|
+
}, Q = async (e, r) => {
|
|
197
197
|
const { body: t, config: s, dbSchema: i, log: o, slonik: d, user: a } = e;
|
|
198
198
|
if (!a)
|
|
199
199
|
return r.status(401).send({
|
|
@@ -206,7 +206,7 @@ const x = async (e, r) => {
|
|
|
206
206
|
throw o.error("device token is not defined"), new Error("Oops, Something went wrong");
|
|
207
207
|
const u = new v(s, d, i);
|
|
208
208
|
r.send(await u.create({ userId: a.id, deviceToken: n }));
|
|
209
|
-
},
|
|
209
|
+
}, Y = async (e, r) => {
|
|
210
210
|
const t = e.user;
|
|
211
211
|
if (!t)
|
|
212
212
|
return r.status(401).send({
|
|
@@ -226,8 +226,8 @@ const x = async (e, r) => {
|
|
|
226
226
|
throw e.log.error("device requested to delete not owned by user"), new Error("Oops, Something went wrong");
|
|
227
227
|
r.send(await i.removeByDeviceToken(s));
|
|
228
228
|
}, E = {
|
|
229
|
-
addUserDevice:
|
|
230
|
-
removeUserDevice:
|
|
229
|
+
addUserDevice: Q,
|
|
230
|
+
removeUserDevice: Y
|
|
231
231
|
}, f = {
|
|
232
232
|
type: "object",
|
|
233
233
|
properties: {
|
|
@@ -246,7 +246,7 @@ const x = async (e, r) => {
|
|
|
246
246
|
updatedAt: { type: "number" }
|
|
247
247
|
},
|
|
248
248
|
required: ["userId", "deviceToken", "createdAt", "updatedAt"]
|
|
249
|
-
},
|
|
249
|
+
}, G = {
|
|
250
250
|
description: "Delete a user device by device token",
|
|
251
251
|
operationId: "deleteUserDevice",
|
|
252
252
|
body: {
|
|
@@ -270,7 +270,7 @@ const x = async (e, r) => {
|
|
|
270
270
|
}
|
|
271
271
|
},
|
|
272
272
|
tags: ["user-devices"]
|
|
273
|
-
},
|
|
273
|
+
}, K = {
|
|
274
274
|
description: "Register a new user device",
|
|
275
275
|
operationId: "postUserDevice",
|
|
276
276
|
body: {
|
|
@@ -300,14 +300,14 @@ const x = async (e, r) => {
|
|
|
300
300
|
B,
|
|
301
301
|
{
|
|
302
302
|
preHandler: [e.verifySession(), b(e)],
|
|
303
|
-
schema:
|
|
303
|
+
schema: K
|
|
304
304
|
},
|
|
305
305
|
r?.addUserDevice || E.addUserDevice
|
|
306
306
|
), e.delete(
|
|
307
307
|
L,
|
|
308
308
|
{
|
|
309
309
|
preHandler: [e.verifySession(), b(e)],
|
|
310
|
-
schema:
|
|
310
|
+
schema: G
|
|
311
311
|
},
|
|
312
312
|
r?.removeUserDevice || E.removeUserDevice
|
|
313
313
|
);
|
|
@@ -452,7 +452,12 @@ const x = async (e, r) => {
|
|
|
452
452
|
ne
|
|
453
453
|
]);
|
|
454
454
|
export {
|
|
455
|
+
M as ROUTE_SEND_NOTIFICATION,
|
|
456
|
+
B as ROUTE_USER_DEVICE_ADD,
|
|
457
|
+
L as ROUTE_USER_DEVICE_REMOVE,
|
|
458
|
+
T as TABLE_USER_DEVICES,
|
|
455
459
|
v as UserDeviceService,
|
|
460
|
+
z as createUserDevicesTableQuery,
|
|
456
461
|
le as default,
|
|
457
462
|
fe as firebaseSchema,
|
|
458
463
|
$ as initializeFirebase,
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
(function(
|
|
2
|
-
`),clientEmail:e.firebase.credentials?.clientEmail})})}catch(
|
|
1
|
+
(function(i,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):(i=typeof globalThis<"u"?globalThis:i||self,g(i.PrefabsTechFastifyFirebase={},i.FastifyPlugin,i.FirebaseAdmin,i.Slonik,i.PrefabsTechFastifySlonik,i.mercurius,i.PrefabsTechFastifyGraphql))})(this,function(i,g,h,p,w,c,y){"use strict";const U=(e,r)=>{if(!(h.apps.length>0)){if(e.firebase?.enabled!==!1&&!e.firebase.credentials){r.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(t){r.log.error("Failed to initialize firebase"),r.log.error(t)}}},m=async e=>{await h.messaging().sendEachForMulticast(e)},I="/send-notification",N="/user-device",R="/user-device",D="user_devices",k=e=>{const r=e.firebase.table?.userDevices?.name||D;return p.sql.unsafe`
|
|
3
3
|
DO $$
|
|
4
4
|
BEGIN
|
|
5
|
-
CREATE TABLE IF NOT EXISTS ${p.sql.identifier([
|
|
5
|
+
CREATE TABLE IF NOT EXISTS ${p.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([
|
|
13
|
+
CREATE INDEX IF NOT EXISTS idx_user_id_device_token ON ${p.sql.identifier([r])} (user_id, device_token);
|
|
14
14
|
END $$;
|
|
15
|
-
`},M=async(e,
|
|
15
|
+
`},M=async(e,r)=>{await e.connect(async t=>{await t.query(k(r))})};class $ extends w.DefaultSqlFactory{static TABLE=D;getDeleteExistingTokenSql(r){return p.sql.type(this.validationSchema)`
|
|
16
16
|
DELETE
|
|
17
17
|
FROM ${this.tableFragment}
|
|
18
|
-
${this.getWhereFragment({filterFragment:p.sql.fragment`device_token = ${
|
|
18
|
+
${this.getWhereFragment({filterFragment:p.sql.fragment`device_token = ${r}`})}
|
|
19
19
|
RETURNING *;
|
|
20
|
-
`}getFindByUserIdSql(
|
|
20
|
+
`}getFindByUserIdSql(r){return p.sql.type(this.validationSchema)`
|
|
21
21
|
SELECT *
|
|
22
22
|
FROM ${this.tableFragment}
|
|
23
|
-
${this.getWhereFragment({filterFragment:p.sql.fragment`user_id = ${
|
|
24
|
-
`}get table(){return this.config.firebase.table?.userDevices?.name||super.table}}class v extends
|
|
23
|
+
${this.getWhereFragment({filterFragment:p.sql.fragment`user_id = ${r}`})};
|
|
24
|
+
`}get table(){return this.config.firebase.table?.userDevices?.name||super.table}}class v extends w.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 $}async preCreate(r){const{deviceToken:t}=r;return await this.removeByDeviceToken(t),r}}const q={sendNotification:async(e,r)=>{if(!e.user)return r.status(401).send({error:"Unauthorized",message:"unauthorized",statusCode:401});const{body:o,title:n,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(E=>E.deviceToken),f={android:{priority:"high",notification:{sound:"default"}},apns:{payload:{aps:{sound:"default"}}},tokens:l,notification:{title:n,body:o},data:{...a,title:n,body:o}};await m(f),r.send({message:"Notification sent successfully"})}},F={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",...F},500:{...F}},tags:["notifications"]},T=e=>async()=>{if(e.config.firebase.enabled===!1)throw new Error("Firebase is not enabled")},_=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:B},r?.addUserDevice||q.sendNotification)},O={addUserDevice:async(e,r)=>{const{body:t,config:o,dbSchema:n,log:a,slonik:u,user:d}=e;if(!d)return r.status(401).send({error:"Unauthorized",message:"unauthorized",statusCode:401});const{deviceToken:s}=t;if(!s)throw a.error("device token is not defined"),new Error("Oops, Something went wrong");const l=new v(o,u,n);r.send(await l.create({userId:d.id,deviceToken:s}))},removeUserDevice:async(e,r)=>{const t=e.user;if(!t)return r.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 n=new v(e.config,e.slonik,e.dbSchema),a=await n.getByUserId(t.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");r.send(await n.removeByDeviceToken(o))}},b={type:"object",properties:{code:{type:"string"},error:{type:"object"},message:{type:"string"},statusCode:{type:"number"},status:{type:"string"}}},A={type:"object",properties:{userId:{type:"string"},deviceToken:{type:"string"},createdAt:{type:"number"},updatedAt:{type:"number"}},required:["userId","deviceToken","createdAt","updatedAt"]},L={description:"Delete a user device by device token",operationId:"deleteUserDevice",body:{type:"object",properties:{deviceToken:{type:"string"}},required:["deviceToken"]},response:{200:{...A,nullable:!0},401:{description:"Unauthorized",...b},500:{...b}},tags:["user-devices"]},z={description:"Register a new user device",operationId:"postUserDevice",body:{type:"object",properties:{deviceToken:{type:"string"}},required:["deviceToken"]},response:{200:{...A,nullable:!0},401:{description:"Unauthorized",...b},500:{...b}},tags:["user-devices"]},P=async e=>{const r=e.config.firebase.handlers?.userDevice;e.post(N,{preHandler:[e.verifySession(),T(e)],schema:z},r?.addUserDevice||O.addUserDevice),e.delete(R,{preHandler:[e.verifySession(),T(e)],schema:L},r?.removeUserDevice||O.removeUserDevice)},W=g(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 M(t,r),U(r,e));const{routePrefix:n,routes:a}=r.firebase;a?.notifications?.disabled||await e.register(_,{prefix:n}),a?.userDevices?.disabled||await e.register(P,{prefix:n})}),j={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:l,body:f,data:E}=r.data;if(!s)return new c.mercurius.ErrorWithProps("Receiver id is required",{},400);const S=await new v(n,u,a).getByUserId(s);if(!S||S.length===0)return new c.mercurius.ErrorWithProps("Receiver device not found",{},404);const K={tokens:S.map(X=>X.deviceToken),notification:{title:l,body:f},data:E};return await m(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,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,l=new v(n,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(C=>C.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:{}},Q=y.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
|
-
`,
|
|
39
|
+
`,H=y.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
|
|
68
|
+
`,Y=y.mergeTypeDefs([y.baseSchema,Q,H]);i.ROUTE_SEND_NOTIFICATION=I,i.ROUTE_USER_DEVICE_ADD=N,i.ROUTE_USER_DEVICE_REMOVE=R,i.TABLE_USER_DEVICES=D,i.UserDeviceService=v,i.createUserDevicesTableQuery=k,i.default=W,i.firebaseSchema=Y,i.initializeFirebase=U,i.notificationResolver=j,i.notificationRoutes=_,i.sendPushNotification=m,i.userDeviceResolver=V,i.userDeviceRoutes=P,Object.defineProperties(i,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|