@prefabs.tech/fastify-firebase 0.94.0 → 0.95.1

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/README.md CHANGED
@@ -23,20 +23,19 @@ Peer dependencies (install compatible versions — see [package.json](./package.
23
23
  - [`fastify-plugin`](https://www.npmjs.com/package/fastify-plugin)
24
24
  - [`mercurius`](https://www.npmjs.com/package/mercurius)
25
25
  - [`slonik`](https://www.npmjs.com/package/slonik)
26
- - [`supertokens-node`](https://www.npmjs.com/package/supertokens-node)
27
26
 
28
27
  ## Installation
29
28
 
30
29
  Install with npm:
31
30
 
32
31
  ```bash
33
- npm install @prefabs.tech/fastify-config @prefabs.tech/fastify-error-handler @prefabs.tech/fastify-graphql @prefabs.tech/fastify-slonik @prefabs.tech/fastify-firebase fastify fastify-plugin mercurius slonik supertokens-node
32
+ npm install @prefabs.tech/fastify-config @prefabs.tech/fastify-error-handler @prefabs.tech/fastify-graphql @prefabs.tech/fastify-slonik @prefabs.tech/fastify-firebase fastify fastify-plugin mercurius slonik
34
33
  ```
35
34
 
36
35
  Install with pnpm:
37
36
 
38
37
  ```bash
39
- pnpm add --filter "@scope/project" @prefabs.tech/fastify-config @prefabs.tech/fastify-error-handler @prefabs.tech/fastify-graphql @prefabs.tech/fastify-slonik @prefabs.tech/fastify-firebase fastify fastify-plugin mercurius slonik supertokens-node
38
+ pnpm add --filter "@scope/project" @prefabs.tech/fastify-config @prefabs.tech/fastify-error-handler @prefabs.tech/fastify-graphql @prefabs.tech/fastify-slonik @prefabs.tech/fastify-firebase fastify fastify-plugin mercurius slonik
40
39
  ```
41
40
 
42
41
  ## Usage
@@ -105,10 +104,10 @@ const config: ApiConfig = {
105
104
  };
106
105
  handlers: {
107
106
  userDevice?: {
108
- addUserDevice: (request: SessionRequest, reply: FastifyReply) => Promise<void>
107
+ addUserDevice: (request: FastifyRequest, reply: FastifyReply) => Promise<void>
109
108
  },
110
109
  notification: {
111
- sendNotification: (request: SessionRequest, reply: FastifyReply) => Promise<void>
110
+ sendNotification: (request: FastifyRequest, reply: FastifyReply) => Promise<void>
112
111
  },
113
112
  };
114
113
  }
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const h=require("@prefabs.tech/fastify-graphql"),g=require("firebase-admin"),p=require("slonik"),S=require("@prefabs.tech/fastify-slonik"),a=require("mercurius"),$=require("fastify-plugin"),U="/send-notification",I="/user-device",w="/user-device",y="user_devices",P=h.gql`
1
+ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require("@prefabs.tech/fastify-graphql"),l=require("firebase-admin");l=s(l,1);let u=require("firebase-admin/app-check"),d=require("slonik"),f=require("@prefabs.tech/fastify-slonik"),p=require("mercurius"),m=require("fastify-plugin");m=s(m,1);var h=`/send-notification`,g=`/user-device`,_=`/user-device`,v=`user_devices`,y=c.gql`
2
2
  type SendNotificationResponse {
3
3
  message: String!
4
4
  }
@@ -13,7 +13,7 @@
13
13
  sendNotification(data: SendNotificationInput): SendNotificationResponse
14
14
  @auth
15
15
  }
16
- `,C=h.gql`
16
+ `,b=c.gql`
17
17
  type UserDevice {
18
18
  id: Int!
19
19
  userId: String!
@@ -42,11 +42,11 @@
42
42
  addUserDevice(data: UserDeviceCreateInput): UserDevice @auth
43
43
  removeUserDevice(data: UserDeviceRemoveInput): UserDevice @auth
44
44
  }
45
- `,M=h.mergeTypeDefs([h.baseSchema,P,C]),R=(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({clientEmail:e.firebase.credentials?.clientEmail,privateKey:e.firebase.credentials?.privateKey.replaceAll(String.raw`\n`,`
46
- `),projectId:e.firebase.credentials?.projectId})})}catch(t){r.log.error("Failed to initialize firebase"),r.log.error(t)}}},m=async e=>{await g.messaging().sendEachForMulticast(e)},N=e=>{const r=e.firebase.table?.userDevices?.name||y;return p.sql.unsafe`
45
+ `,x=(0,c.mergeTypeDefs)([c.baseSchema,y,b]),S=(e,t)=>{if(!(l.default.apps.length>0)){if(e.firebase?.enabled!==!1&&!e.firebase.credentials){t.log.error(`Firebase credentials are missing`);return}try{l.default.initializeApp({credential:l.default.credential.cert({clientEmail:e.firebase.credentials?.clientEmail,privateKey:e.firebase.credentials?.privateKey.replaceAll(String.raw`\n`,`
46
+ `),projectId:e.firebase.credentials?.projectId})})}catch(e){t.log.error(`Failed to initialize firebase`),t.log.error(e)}}},C=async e=>{await l.default.messaging().sendEachForMulticast(e)},w=async(e,t)=>{if(!e.config.firebase.appCheck?.enabled)return;let n=new Set(e.config.firebase.appCheck?.routes);try{if(!n.has(e.url.split(`?`,1)[0]))return;let r=e.headers[`x-firebase-appcheck`];if(!r||Array.isArray(r))return t.status(403).send({code:`FORBIDDEN`,message:`You aren't authorized to access this resource`});await(0,u.getAppCheck)().verifyToken(r)}catch(n){return e.log.error(`Error verifying Firebase App Check token: ${n}`),t.status(403).send({code:`FORBIDDEN`,message:`You aren't authorized to access this resource`})}},T=e=>{let t=e.firebase.table?.userDevices?.name||`user_devices`;return d.sql.unsafe`
47
47
  DO $$
48
48
  BEGIN
49
- CREATE TABLE IF NOT EXISTS ${p.sql.identifier([r])} (
49
+ CREATE TABLE IF NOT EXISTS ${d.sql.identifier([t])} (
50
50
  id INT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
51
51
  user_id VARCHAR(255) NOT NULL,
52
52
  device_token VARCHAR(255) NOT NULL,
@@ -54,15 +54,15 @@
54
54
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
55
55
  );
56
56
 
57
- CREATE INDEX IF NOT EXISTS idx_user_id_device_token ON ${p.sql.identifier([r])} (user_id, device_token);
57
+ CREATE INDEX IF NOT EXISTS idx_user_id_device_token ON ${d.sql.identifier([t])} (user_id, device_token);
58
58
  END $$;
59
- `},b=e=>async()=>{if(e.config.firebase.enabled===!1)throw e.httpErrors.notFound("Firebase is disabled")};class q extends S.DefaultSqlFactory{static TABLE=y;get table(){return this.config.firebase.table?.userDevices?.name||super.table}getDeleteExistingTokenSql(r){return p.sql.type(this.validationSchema)`
59
+ `},E=e=>async()=>{if(e.config.firebase.enabled===!1)throw e.httpErrors.notFound(`Firebase is disabled`)},D=class extends f.DefaultSqlFactory{static TABLE=v;get table(){return this.config.firebase.table?.userDevices?.name||super.table}getDeleteExistingTokenSql(e){return d.sql.type(this.validationSchema)`
60
60
  DELETE
61
61
  FROM ${this.tableFragment}
62
- ${this.getWhereFragment({filterFragment:p.sql.fragment`device_token = ${r}`})}
62
+ ${this.getWhereFragment({filterFragment:d.sql.fragment`device_token = ${e}`})}
63
63
  RETURNING *;
64
- `}getFindByUserIdSql(r){return p.sql.type(this.validationSchema)`
64
+ `}getFindByUserIdSql(e){return d.sql.type(this.validationSchema)`
65
65
  SELECT *
66
66
  FROM ${this.tableFragment}
67
- ${this.getWhereFragment({filterFragment:p.sql.fragment`user_id = ${r}`})};
68
- `}}class v extends S.BaseService{get factory(){return super.factory}get sqlFactoryClass(){return q}async getByUserId(r){const t=this.factory.getFindByUserIdSql(r);return await this.database.connect(i=>i.any(t))}async removeByDeviceToken(r){const t=this.factory.getDeleteExistingTokenSql(r);return await this.database.connect(i=>i.maybeOne(t))}async preCreate(r){const{deviceToken:t}=r;return await this.removeByDeviceToken(t),r}}const B=async(e,r)=>{if(!e.user)throw e.server.httpErrors.unauthorized("Unauthorised");const{body:n,data:i,title:o,userId:d}=e.body,s=await new v(e.config,e.slonik,e.dbSchema).getByUserId(d);if(!s||s.length===0)throw e.server.httpErrors.unprocessableEntity("No devices found for the receiver");const u=s.map(f=>f.deviceToken),l={android:{notification:{sound:"default"},priority:"high"},apns:{payload:{aps:{sound:"default"}}},data:{...i,body:n,title:o},notification:{body:n,title:o},tokens:u};await m(l),r.send({message:"Notification sent successfully"})},L={sendNotification:B},W={body:{properties:{message:{type:"string"},title:{type:"string"},userId:{type:"string"}},required:["title","message","userId"],type:"object"},description:"Send a notification to a specific user",operationId:"sendNotification",response:{200:{properties:{message:{type:"string"},success:{type:"boolean"}},type:"object"},401:{$ref:"ErrorResponse#",description:"Unauthorized"},500:{$ref:"ErrorResponse#"}},tags:["notifications"]},k=async e=>{const r=e.config.firebase.handlers?.notification,t=e.config.firebase.notification;t?.test?.enabled&&e.post(t.test.path||U,{preHandler:[e.verifySession(),b(e)],schema:W},r?.sendNotification||L.sendNotification)},z={sendNotification:async(e,r,t)=>{const{app:n,config:i,database:o,dbSchema:d,user:c}=t;if(!c)return new a.mercurius.ErrorWithProps("unauthorized",{},401);if(i.firebase.enabled===!1)return new a.mercurius.ErrorWithProps("Firebase is not enabled",{},404);try{const{body:s,data:u,title:l,userId:f}=r.data;if(!f)return new a.mercurius.ErrorWithProps("Receiver id is required",{},400);const E=await new v(i,o,d).getByUserId(f);if(!E||E.length===0)return new a.mercurius.ErrorWithProps("Receiver device not found",{},404);const A=E.map(O=>O.deviceToken);return await m({data:u,notification:{body:s,title:l},tokens:A}),{message:"Notification sent successfully"}}catch(s){return n.log.error(s),new a.mercurius.ErrorWithProps("Oops, Something went wrong",{},500)}}},V={},j={Mutation:z,Query:V},x=async(e,r)=>{const{body:t,config:n,dbSchema:i,slonik:o,user:d}=e;if(!d)throw e.server.httpErrors.unauthorized("Unauthorised");const{deviceToken:c}=t,s=new v(n,o,i);r.send(await s.create({deviceToken:c,userId:d.id}))},H=async(e,r)=>{const t=e.user;if(!t)throw e.server.httpErrors.unauthorized("Unauthorised");const{deviceToken:n}=e.body,i=new v(e.config,e.slonik,e.dbSchema),o=await i.getByUserId(t.id);if(!o||o.length===0)throw e.server.httpErrors.notFound("No devices found for the user");if(!o.find(c=>c.deviceToken===n))throw e.server.httpErrors.unprocessableEntity("Device requested to delete not owned by user");r.send(await i.removeByDeviceToken(n))},T={addUserDevice:x,removeUserDevice:H},_={properties:{createdAt:{type:"number"},deviceToken:{type:"string"},updatedAt:{type:"number"},userId:{type:"string"}},required:["userId","deviceToken","createdAt","updatedAt"],type:"object"},Q={body:{properties:{deviceToken:{type:"string"}},required:["deviceToken"],type:"object"},description:"Delete a user device by device token",operationId:"deleteUserDevice",response:{200:{..._,nullable:!0},401:{$ref:"ErrorResponse#",description:"Unauthorized"},500:{$ref:"ErrorResponse#"}},tags:["user-devices"]},G={body:{properties:{deviceToken:{type:"string"}},required:["deviceToken"],type:"object"},description:"Register a new user device",operationId:"postUserDevice",response:{200:{..._,nullable:!0},401:{$ref:"ErrorResponse#",description:"Unauthorized"},500:{$ref:"ErrorResponse#"}},tags:["user-devices"]},F=async e=>{const r=e.config.firebase.handlers?.userDevice;e.post(I,{preHandler:[e.verifySession(),b(e)],schema:G},r?.addUserDevice||T.addUserDevice),e.delete(w,{preHandler:[e.verifySession(),b(e)],schema:Q},r?.removeUserDevice||T.removeUserDevice)},Y={addUserDevice:async(e,r,t)=>{const{app:n,config:i,database:o,dbSchema:d,user:c}=t;if(i.firebase.enabled===!1)return new a.mercurius.ErrorWithProps("Firebase is not enabled",{},404);if(!c)return new a.mercurius.ErrorWithProps("unauthorized",{},401);try{const{deviceToken:s}=r.data;return await new v(i,o,d).create({deviceToken:s,userId:c.id})}catch(s){return n.log.error(s),new a.mercurius.ErrorWithProps("Oops, Something went wrong",{},500)}},removeUserDevice:async(e,r,t)=>{const{app:n,config:i,database:o,dbSchema:d,user:c}=t;if(i.firebase.enabled===!1)return new a.mercurius.ErrorWithProps("Firebase is not enabled",{},404);if(!c)return new a.mercurius.ErrorWithProps("unauthorized",{},401);try{const{deviceToken:s}=r.data,u=new v(i,o,d),l=await u.getByUserId(c.id);return!l||l.length===0?new a.mercurius.ErrorWithProps("No devices found for user",{},403):l.find(D=>D.deviceToken===s)?await u.removeByDeviceToken(s):new a.mercurius.ErrorWithProps("Device requested to delete not owned by user",{},403)}catch(s){return n.log.error(s),new a.mercurius.ErrorWithProps("Oops, Something went wrong",{},500)}}},K={},X={Mutation:Y,Query:K},J=async(e,r)=>{await e.connect(async t=>{await t.query(N(r))})},Z=async e=>{const{config:r,log:t,slonik:n}=e;r.firebase.enabled===!1?t.info("fastify-firebase plugin is not enabled"):(t.info("Registering fastify-firebase plugin"),await J(n,r),R(r,e));const{routePrefix:i,routes:o}=r.firebase;o?.notifications?.disabled||await e.register(k,{prefix:i}),o?.userDevices?.disabled||await e.register(F,{prefix:i})},ee=$(Z);exports.ROUTE_SEND_NOTIFICATION=U;exports.ROUTE_USER_DEVICE_ADD=I;exports.ROUTE_USER_DEVICE_REMOVE=w;exports.TABLE_USER_DEVICES=y;exports.UserDeviceService=v;exports.createUserDevicesTableQuery=N;exports.default=ee;exports.firebaseSchema=M;exports.initializeFirebase=R;exports.notificationResolver=j;exports.notificationRoutes=k;exports.sendPushNotification=m;exports.userDeviceResolver=X;exports.userDeviceRoutes=F;
67
+ ${this.getWhereFragment({filterFragment:d.sql.fragment`user_id = ${e}`})};
68
+ `}},O=class extends f.BaseService{get factory(){return super.factory}get sqlFactoryClass(){return D}async getByUserId(e){let t=this.factory.getFindByUserIdSql(e);return await this.database.connect(e=>e.any(t))}async removeByDeviceToken(e){let t=this.factory.getDeleteExistingTokenSql(e);return await this.database.connect(e=>e.maybeOne(t))}async preCreate(e){let{deviceToken:t}=e;return await this.removeByDeviceToken(t),e}},k={sendNotification:async(e,t)=>{if(!e.user)throw e.server.httpErrors.unauthorized(`Unauthorised`);let{body:n,data:r,title:i,userId:a}=e.body,o=await new O(e.config,e.slonik,e.dbSchema).getByUserId(a);if(!o||o.length===0)throw e.server.httpErrors.unprocessableEntity(`No devices found for the receiver`);let s=o.map(e=>e.deviceToken);await C({android:{notification:{sound:`default`},priority:`high`},apns:{payload:{aps:{sound:`default`}}},data:{...r,body:n,title:i},notification:{body:n,title:i},tokens:s}),t.send({message:`Notification sent successfully`})}},A={body:{properties:{body:{type:`string`},title:{type:`string`},userId:{type:`string`}},required:[`title`,`body`,`userId`],type:`object`},description:`Send a notification to a specific user`,operationId:`sendNotification`,response:{200:{properties:{message:{type:`string`},success:{type:`boolean`}},type:`object`},401:{$ref:`ErrorResponse#`,description:`Unauthorized`},500:{$ref:`ErrorResponse#`}},tags:[`notifications`]},j=async e=>{let t=e.config.firebase.handlers?.notification,n=e.config.firebase.notification;n?.test?.enabled&&e.post(n.test.path||`/send-notification`,{preHandler:[e.verifySession(),E(e)],schema:A},t?.sendNotification||k.sendNotification)},M={Mutation:{sendNotification:async(e,t,n)=>{let{app:r,config:i,database:a,dbSchema:o,user:s}=n;if(!s)return new p.mercurius.ErrorWithProps(`unauthorized`,{},401);if(i.firebase.enabled===!1)return new p.mercurius.ErrorWithProps(`Firebase is not enabled`,{},404);try{let{body:e,data:n,title:r,userId:s}=t.data;if(!s)return new p.mercurius.ErrorWithProps(`Receiver id is required`,{},400);let c=await new O(i,a,o).getByUserId(s);if(!c||c.length===0)return new p.mercurius.ErrorWithProps(`Receiver device not found`,{},404);let l=c.map(e=>e.deviceToken);return await C({data:n,notification:{body:e,title:r},tokens:l}),{message:`Notification sent successfully`}}catch(e){return r.log.error(e),new p.mercurius.ErrorWithProps(`Oops, Something went wrong`,{},500)}}},Query:{}},N={addUserDevice:async(e,t)=>{let{body:n,config:r,dbSchema:i,slonik:a,user:o}=e;if(!o)throw e.server.httpErrors.unauthorized(`Unauthorised`);let{deviceToken:s}=n,c=new O(r,a,i);t.send(await c.create({deviceToken:s,userId:o.id}))},removeUserDevice:async(e,t)=>{let n=e.user;if(!n)throw e.server.httpErrors.unauthorized(`Unauthorised`);let{deviceToken:r}=e.body,i=new O(e.config,e.slonik,e.dbSchema),a=await i.getByUserId(n.id);if(!a||a.length===0)throw e.server.httpErrors.notFound(`No devices found for the user`);if(!a.find(e=>e.deviceToken===r))throw e.server.httpErrors.unprocessableEntity(`Device requested to delete not owned by user`);t.send(await i.removeByDeviceToken(r))}},P={properties:{createdAt:{type:`number`},deviceToken:{type:`string`},updatedAt:{type:`number`},userId:{type:`string`}},required:[`userId`,`deviceToken`,`createdAt`,`updatedAt`],type:`object`},F={body:{properties:{deviceToken:{type:`string`}},required:[`deviceToken`],type:`object`},description:`Delete a user device by device token`,operationId:`deleteUserDevice`,response:{200:{...P,nullable:!0},401:{$ref:`ErrorResponse#`,description:`Unauthorized`},500:{$ref:`ErrorResponse#`}},tags:[`user-devices`]},I={body:{properties:{deviceToken:{type:`string`}},required:[`deviceToken`],type:`object`},description:`Register a new user device`,operationId:`postUserDevice`,response:{200:{...P,nullable:!0},401:{$ref:`ErrorResponse#`,description:`Unauthorized`},500:{$ref:`ErrorResponse#`}},tags:[`user-devices`]},L=async e=>{let t=e.config.firebase.handlers?.userDevice;e.post(g,{preHandler:[e.verifySession(),E(e)],schema:I},t?.addUserDevice||N.addUserDevice),e.delete(_,{preHandler:[e.verifySession(),E(e)],schema:F},t?.removeUserDevice||N.removeUserDevice)},R={Mutation:{addUserDevice:async(e,t,n)=>{let{app:r,config:i,database:a,dbSchema:o,user:s}=n;if(i.firebase.enabled===!1)return new p.mercurius.ErrorWithProps(`Firebase is not enabled`,{},404);if(!s)return new p.mercurius.ErrorWithProps(`unauthorized`,{},401);try{let{deviceToken:e}=t.data;return await new O(i,a,o).create({deviceToken:e,userId:s.id})}catch(e){return r.log.error(e),new p.mercurius.ErrorWithProps(`Oops, Something went wrong`,{},500)}},removeUserDevice:async(e,t,n)=>{let{app:r,config:i,database:a,dbSchema:o,user:s}=n;if(i.firebase.enabled===!1)return new p.mercurius.ErrorWithProps(`Firebase is not enabled`,{},404);if(!s)return new p.mercurius.ErrorWithProps(`unauthorized`,{},401);try{let{deviceToken:e}=t.data,n=new O(i,a,o),r=await n.getByUserId(s.id);return!r||r.length===0?new p.mercurius.ErrorWithProps(`No devices found for user`,{},403):r.find(t=>t.deviceToken===e)?await n.removeByDeviceToken(e):new p.mercurius.ErrorWithProps(`Device requested to delete not owned by user`,{},403)}catch(e){return r.log.error(e),new p.mercurius.ErrorWithProps(`Oops, Something went wrong`,{},500)}}},Query:{}},z=async(e,t)=>{await e.connect(async e=>{await e.query(T(t))})},B=(0,m.default)(async e=>{let{config:t,log:n,slonik:r}=e;t.firebase.enabled===!1?n.info(`fastify-firebase plugin is not enabled`):(n.info(`Registering fastify-firebase plugin`),await z(r,t),S(t,e));let{routePrefix:i,routes:a}=t.firebase;a?.notifications?.disabled||await e.register(j,{prefix:i}),a?.userDevices?.disabled||await e.register(L,{prefix:i})});exports.ROUTE_SEND_NOTIFICATION=h,exports.ROUTE_USER_DEVICE_ADD=g,exports.ROUTE_USER_DEVICE_REMOVE=_,exports.TABLE_USER_DEVICES=v,exports.UserDeviceService=O,exports.createUserDevicesTableQuery=T,exports.default=B,Object.defineProperty(exports,"firebaseAdmin",{enumerable:!0,get:function(){return l.default}}),exports.firebaseSchema=x,Object.defineProperty(exports,"getAppCheck",{enumerable:!0,get:function(){return u.getAppCheck}}),exports.initializeFirebase=S,exports.notificationResolver=M,exports.notificationRoutes=j,exports.sendPushNotification=C,exports.userDeviceResolver=R,exports.userDeviceRoutes=L,exports.verifyFirebaseAppCheck=w;