@prefabs.tech/fastify-firebase 0.94.1 → 0.96.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.
- package/README.md +4 -5
- package/dist/prefabs-tech-fastify-firebase.cjs +11 -11
- package/dist/prefabs-tech-fastify-firebase.js +291 -372
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/types/index.d.ts +9 -2
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/lib/index.d.ts +1 -1
- package/dist/types/lib/index.d.ts.map +1 -1
- package/dist/types/lib/initializeFirebase.d.ts +1 -0
- package/dist/types/lib/initializeFirebase.d.ts.map +1 -1
- package/dist/types/middlewares/verifyFirebaseAppCheck.d.ts +4 -0
- package/dist/types/middlewares/verifyFirebaseAppCheck.d.ts.map +1 -0
- package/dist/types/model/notification/handlers/index.d.ts +1 -1
- package/dist/types/model/notification/handlers/sendNotification.d.ts +2 -3
- package/dist/types/model/notification/handlers/sendNotification.d.ts.map +1 -1
- package/dist/types/model/notification/schema.d.ts +1 -1
- package/dist/types/model/userDevice/handlers/addUserDevice.d.ts +2 -3
- package/dist/types/model/userDevice/handlers/addUserDevice.d.ts.map +1 -1
- package/dist/types/model/userDevice/handlers/index.d.ts +2 -2
- package/dist/types/model/userDevice/handlers/removeUserDevice.d.ts +2 -3
- package/dist/types/model/userDevice/handlers/removeUserDevice.d.ts.map +1 -1
- package/package.json +37 -41
- package/LICENSE +0 -21
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
|
|
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
|
|
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:
|
|
107
|
+
addUserDevice: (request: FastifyRequest, reply: FastifyReply) => Promise<void>
|
|
109
108
|
},
|
|
110
109
|
notification: {
|
|
111
|
-
sendNotification: (request:
|
|
110
|
+
sendNotification: (request: FastifyRequest, reply: FastifyReply) => Promise<void>
|
|
112
111
|
},
|
|
113
112
|
};
|
|
114
113
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
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
|
-
`,
|
|
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
|
-
`,
|
|
46
|
-
`),projectId:e.firebase.credentials?.projectId})})}catch(
|
|
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 ${
|
|
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 ${
|
|
57
|
+
CREATE INDEX IF NOT EXISTS idx_user_id_device_token ON ${d.sql.identifier([t])} (user_id, device_token);
|
|
58
58
|
END $$;
|
|
59
|
-
`},
|
|
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:
|
|
62
|
+
${this.getWhereFragment({filterFragment:d.sql.fragment`device_token = ${e}`})}
|
|
63
63
|
RETURNING *;
|
|
64
|
-
`}getFindByUserIdSql(
|
|
64
|
+
`}getFindByUserIdSql(e){return d.sql.type(this.validationSchema)`
|
|
65
65
|
SELECT *
|
|
66
66
|
FROM ${this.tableFragment}
|
|
67
|
-
${this.getWhereFragment({filterFragment:
|
|
68
|
-
`}}class
|
|
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;
|