@prefabs.tech/fastify-firebase 0.93.5 → 0.94.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 +38 -14
- package/dist/prefabs-tech-fastify-firebase.cjs +26 -26
- package/dist/prefabs-tech-fastify-firebase.js +205 -205
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/types/index.d.ts +26 -26
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/lib/initializeFirebase.d.ts.map +1 -1
- package/dist/types/lib/sendPushNotification.d.ts.map +1 -1
- package/dist/types/migrations/queries.d.ts.map +1 -1
- package/dist/types/migrations/runMigrations.d.ts.map +1 -1
- package/dist/types/model/notification/controller.d.ts +4 -0
- package/dist/types/model/notification/controller.d.ts.map +1 -1
- package/dist/types/model/notification/graphql/resolver.d.ts +2 -2
- package/dist/types/model/notification/graphql/resolver.d.ts.map +1 -1
- package/dist/types/model/notification/handlers/sendNotification.d.ts.map +1 -1
- package/dist/types/model/notification/schema.d.ts +9 -9
- package/dist/types/model/userDevice/controller.d.ts.map +1 -1
- package/dist/types/model/userDevice/handlers/addUserDevice.d.ts.map +1 -1
- package/dist/types/model/userDevice/handlers/removeUserDevice.d.ts.map +1 -1
- package/dist/types/model/userDevice/schema.d.ts +16 -16
- package/dist/types/model/userDevice/service.d.ts +3 -3
- package/dist/types/model/userDevice/service.d.ts.map +1 -1
- package/dist/types/model/userDevice/sqlFactory.d.ts +1 -1
- package/dist/types/model/userDevice/sqlFactory.d.ts.map +1 -1
- package/dist/types/plugin.d.ts.map +1 -1
- package/dist/types/types.d.ts +11 -11
- package/dist/types/types.d.ts.map +1 -1
- package/package.json +22 -21
package/README.md
CHANGED
|
@@ -2,23 +2,41 @@
|
|
|
2
2
|
|
|
3
3
|
A [Fastify](https://github.com/fastify/fastify) plugin that provides an easy integration of Firebase Admin in a fastify API.
|
|
4
4
|
|
|
5
|
+
## Why this plugin?
|
|
6
|
+
|
|
7
|
+
Integrating Firebase Admin into a Node.js API typically involves much more than just calling `initializeApp()`. To support features like push notifications securely, you must manage user device tokens in a database, expose REST routes or GraphQL mutations to clients to register those devices, and define secure dispatch handlers. We created this plugin to:
|
|
8
|
+
|
|
9
|
+
- **Provide a Complete Feature Slice**: Rather than just wrapping the SDK, this plugin provides a fully functioning User Device and Notification management system out-of-the-box, automatically taking advantage of your `@prefabs.tech/fastify-slonik` database setup.
|
|
10
|
+
- **Bootstrap APIs Instantly**: It automatically provides and wires up both REST routes and GraphQL resolvers/schemas (`userDevice`, `notification`) so you don't have to manually write the boilerplate to add, remove, and manage FCM tokens across your applications.
|
|
11
|
+
- **Centralize Configuration**: By extending our `@prefabs.tech/fastify-config` interface, we ensure that your Firebase credentials, database table preferences, and route configurations are strictly typed and managed in one central place alongside the rest of your app.
|
|
12
|
+
- **Allow Clean Overrides**: While we provide default controllers and services for handling devices and notifications, the plugin architecture allows you to easily override them via the config (`config.firebase.handlers`) whenever your business logic requires custom behavior.
|
|
13
|
+
|
|
5
14
|
## Requirements
|
|
6
15
|
|
|
7
|
-
|
|
8
|
-
|
|
16
|
+
Peer dependencies (install compatible versions — see [package.json](./package.json)):
|
|
17
|
+
|
|
18
|
+
- [@prefabs.tech/fastify-config](../config/)
|
|
19
|
+
- [@prefabs.tech/fastify-error-handler](../error-handler/)
|
|
20
|
+
- [@prefabs.tech/fastify-graphql](../graphql/)
|
|
21
|
+
- [@prefabs.tech/fastify-slonik](../slonik/)
|
|
22
|
+
- [`fastify`](https://www.npmjs.com/package/fastify)
|
|
23
|
+
- [`fastify-plugin`](https://www.npmjs.com/package/fastify-plugin)
|
|
24
|
+
- [`mercurius`](https://www.npmjs.com/package/mercurius)
|
|
25
|
+
- [`slonik`](https://www.npmjs.com/package/slonik)
|
|
26
|
+
- [`supertokens-node`](https://www.npmjs.com/package/supertokens-node)
|
|
9
27
|
|
|
10
28
|
## Installation
|
|
11
29
|
|
|
12
30
|
Install with npm:
|
|
13
31
|
|
|
14
32
|
```bash
|
|
15
|
-
npm install @prefabs.tech/fastify-config @prefabs.tech/fastify-slonik @prefabs.tech/fastify-firebase
|
|
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
|
|
16
34
|
```
|
|
17
35
|
|
|
18
36
|
Install with pnpm:
|
|
19
37
|
|
|
20
38
|
```bash
|
|
21
|
-
pnpm add --filter "@scope/project" @prefabs.tech/fastify-config @prefabs.tech/fastify-slonik @prefabs.tech/fastify-firebase
|
|
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
|
|
22
40
|
```
|
|
23
41
|
|
|
24
42
|
## Usage
|
|
@@ -28,32 +46,35 @@ pnpm add --filter "@scope/project" @prefabs.tech/fastify-config @prefabs.tech/fa
|
|
|
28
46
|
Register the fastify-firebase plugin with your Fastify instance:
|
|
29
47
|
|
|
30
48
|
```typescript
|
|
31
|
-
import firebasePlugin from "@prefabs.tech/fastify-firebase";
|
|
32
49
|
import configPlugin from "@prefabs.tech/fastify-config";
|
|
50
|
+
import errorHandlerPlugin from "@prefabs.tech/fastify-error-handler";
|
|
51
|
+
import firebasePlugin from "@prefabs.tech/fastify-firebase";
|
|
52
|
+
import graphqlPlugin from "@prefabs.tech/fastify-graphql";
|
|
53
|
+
import slonikPlugin from "@prefabs.tech/fastify-slonik";
|
|
33
54
|
import Fastify from "fastify";
|
|
34
55
|
|
|
35
56
|
import config from "./config";
|
|
36
57
|
|
|
37
58
|
import type { ApiConfig } from "@prefabs.tech/fastify-config";
|
|
38
|
-
import type { FastifyInstance } from "fastify";
|
|
39
59
|
|
|
40
60
|
const start = async () => {
|
|
41
|
-
// Create fastify instance
|
|
42
61
|
const fastify = Fastify({
|
|
43
62
|
logger: config.logger,
|
|
44
63
|
});
|
|
45
64
|
|
|
46
|
-
// Register fastify-config plugin
|
|
47
65
|
await fastify.register(configPlugin, { config });
|
|
48
|
-
|
|
49
|
-
|
|
66
|
+
await fastify.register(errorHandlerPlugin, {
|
|
67
|
+
stackTrace: process.env.NODE_ENV === "development",
|
|
68
|
+
});
|
|
69
|
+
await fastify.register(slonikPlugin, config.slonik);
|
|
70
|
+
await fastify.register(graphqlPlugin, config.graphql);
|
|
50
71
|
await fastify.register(firebasePlugin);
|
|
51
72
|
|
|
52
73
|
await fastify.listen({
|
|
53
|
-
port: config.port,
|
|
54
74
|
host: "0.0.0.0",
|
|
75
|
+
port: config.port,
|
|
55
76
|
});
|
|
56
|
-
}
|
|
77
|
+
};
|
|
57
78
|
|
|
58
79
|
start();
|
|
59
80
|
```
|
|
@@ -107,7 +128,7 @@ To load and merge this schema with your application's custom schemas, update you
|
|
|
107
128
|
```typescript
|
|
108
129
|
import { firebaseSchema } from "@prefabs.tech/fastify-firebase";
|
|
109
130
|
import { loadFilesSync } from "@graphql-tools/load-files";
|
|
110
|
-
import { mergeTypeDefs } from "";
|
|
131
|
+
import { mergeTypeDefs } from "@graphql-tools/merge";
|
|
111
132
|
import { makeExecutableSchema } from "@graphql-tools/schema";
|
|
112
133
|
|
|
113
134
|
const schemas: string[] = loadFilesSync("./src/**/*.gql");
|
|
@@ -123,7 +144,10 @@ export default schema;
|
|
|
123
144
|
To integrate the resolvers provided by this package, import them and merge with your application's resolvers:
|
|
124
145
|
|
|
125
146
|
```typescript
|
|
126
|
-
import {
|
|
147
|
+
import {
|
|
148
|
+
notificationResolver,
|
|
149
|
+
userDeviceResolver,
|
|
150
|
+
} from "@prefabs.tech/fastify-firebase";
|
|
127
151
|
|
|
128
152
|
import type { IResolvers } from "mercurius";
|
|
129
153
|
|
|
@@ -1,27 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const
|
|
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 p.sql.unsafe`
|
|
3
|
-
DO $$
|
|
4
|
-
BEGIN
|
|
5
|
-
CREATE TABLE IF NOT EXISTS ${p.sql.identifier([r])} (
|
|
6
|
-
id INT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
|
7
|
-
user_id VARCHAR(255) NOT NULL,
|
|
8
|
-
device_token VARCHAR(255) NOT NULL,
|
|
9
|
-
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
10
|
-
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
|
11
|
-
);
|
|
12
|
-
|
|
13
|
-
CREATE INDEX IF NOT EXISTS idx_user_id_device_token ON ${p.sql.identifier([r])} (user_id, device_token);
|
|
14
|
-
END $$;
|
|
15
|
-
`},P=async(e,r)=>{await e.connect(async t=>{await t.query(N(r))})};class C extends S.DefaultSqlFactory{static TABLE=D;getDeleteExistingTokenSql(r){return p.sql.type(this.validationSchema)`
|
|
16
|
-
DELETE
|
|
17
|
-
FROM ${this.tableFragment}
|
|
18
|
-
${this.getWhereFragment({filterFragment:p.sql.fragment`device_token = ${r}`})}
|
|
19
|
-
RETURNING *;
|
|
20
|
-
`}getFindByUserIdSql(r){return p.sql.type(this.validationSchema)`
|
|
21
|
-
SELECT *
|
|
22
|
-
FROM ${this.tableFragment}
|
|
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 S.BaseService{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))}get factory(){return super.factory}get sqlFactoryClass(){return C}async preCreate(r){const{deviceToken:t}=r;return await this.removeByDeviceToken(t),r}}const M=async(e,r)=>{if(!e.user)throw e.server.httpErrors.unauthorized("Unauthorised");const{body:n,title:i,data: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:{priority:"high",notification:{sound:"default"}},apns:{payload:{aps:{sound:"default"}}},tokens:u,notification:{title:i,body:n},data:{...o,title:i,body:n}};await y(l),r.send({message:"Notification sent successfully"})},q={sendNotification:M},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",$ref:"ErrorResponse#"},500:{$ref:"ErrorResponse#"}},tags:["notifications"]},b=e=>async()=>{if(e.config.firebase.enabled===!1)throw e.httpErrors.notFound("Firebase is disabled")},k=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(),b(e)],schema:B},r?.addUserDevice||q.sendNotification)},L=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({userId:d.id,deviceToken:c}))},W=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:L,removeUserDevice:W},_={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:{..._,nullable:!0},401:{description:"Unauthorized",$ref:"ErrorResponse#"},500:{$ref:"ErrorResponse#"}},tags:["user-devices"]},V={description:"Register a new user device",operationId:"postUserDevice",body:{type:"object",properties:{deviceToken:{type:"string"}},required:["deviceToken"]},response:{200:{..._,nullable:!0},401:{description:"Unauthorized",$ref:"ErrorResponse#"},500:{$ref:"ErrorResponse#"}},tags:["user-devices"]},F=async e=>{const r=e.config.firebase.handlers?.userDevice;e.post(w,{preHandler:[e.verifySession(),b(e)],schema:V},r?.addUserDevice||T.addUserDevice),e.delete(R,{preHandler:[e.verifySession(),b(e)],schema:z},r?.removeUserDevice||T.removeUserDevice)},j=async e=>{const{config:r,slonik:t,log:n}=e;r.firebase.enabled===!1?n.info("fastify-firebase plugin is not enabled"):(n.info("Registering fastify-firebase plugin"),await P(t,r),U(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})},x=$(j),H={sendNotification:async(e,r,t)=>{const{app:n,config:i,dbSchema:o,database: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{userId:s,title:u,body:l,data:f}=r.data;if(!s)return new a.mercurius.ErrorWithProps("Receiver id is required",{},400);const E=await new v(i,d,o).getByUserId(s);if(!E||E.length===0)return new a.mercurius.ErrorWithProps("Receiver device not found",{},404);const A={tokens:E.map(O=>O.deviceToken),notification:{title:u,body:l},data:f};return await y(A),{message:"Notification sent successfully"}}catch(s){return n.log.error(s),new a.mercurius.ErrorWithProps("Oops, Something went wrong",{},500)}}},Q={},G={Mutation:H,Query:Q},Y={addUserDevice:async(e,r,t)=>{const{app:n,config:i,dbSchema:o,database: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,d,o).create({userId:c.id,deviceToken:s})}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,dbSchema:o,database: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,d,o),l=await u.getByUserId(c.id);return!l||l.length===0?new a.mercurius.ErrorWithProps("No devices found for user",{},403):l.find(m=>m.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=h.gql`
|
|
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`
|
|
25
2
|
type SendNotificationResponse {
|
|
26
3
|
message: String!
|
|
27
4
|
}
|
|
@@ -36,7 +13,7 @@
|
|
|
36
13
|
sendNotification(data: SendNotificationInput): SendNotificationResponse
|
|
37
14
|
@auth
|
|
38
15
|
}
|
|
39
|
-
`,
|
|
16
|
+
`,C=h.gql`
|
|
40
17
|
type UserDevice {
|
|
41
18
|
id: Int!
|
|
42
19
|
userId: String!
|
|
@@ -65,4 +42,27 @@
|
|
|
65
42
|
addUserDevice(data: UserDeviceCreateInput): UserDevice @auth
|
|
66
43
|
removeUserDevice(data: UserDeviceRemoveInput): UserDevice @auth
|
|
67
44
|
}
|
|
68
|
-
`,
|
|
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`
|
|
47
|
+
DO $$
|
|
48
|
+
BEGIN
|
|
49
|
+
CREATE TABLE IF NOT EXISTS ${p.sql.identifier([r])} (
|
|
50
|
+
id INT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
|
51
|
+
user_id VARCHAR(255) NOT NULL,
|
|
52
|
+
device_token VARCHAR(255) NOT NULL,
|
|
53
|
+
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
54
|
+
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
|
55
|
+
);
|
|
56
|
+
|
|
57
|
+
CREATE INDEX IF NOT EXISTS idx_user_id_device_token ON ${p.sql.identifier([r])} (user_id, device_token);
|
|
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)`
|
|
60
|
+
DELETE
|
|
61
|
+
FROM ${this.tableFragment}
|
|
62
|
+
${this.getWhereFragment({filterFragment:p.sql.fragment`device_token = ${r}`})}
|
|
63
|
+
RETURNING *;
|
|
64
|
+
`}getFindByUserIdSql(r){return p.sql.type(this.validationSchema)`
|
|
65
|
+
SELECT *
|
|
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;
|