@prefabs.tech/fastify-firebase 0.88.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/LICENSE +21 -0
- package/README.md +144 -0
- package/dist/prefabs-tech-fastify-firebase.js +464 -0
- package/dist/prefabs-tech-fastify-firebase.umd.cjs +68 -0
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/dist/types/constants.d.ts +6 -0
- package/dist/types/constants.d.ts.map +1 -0
- package/dist/types/graphql/schema.d.ts +3 -0
- package/dist/types/graphql/schema.d.ts.map +1 -0
- package/dist/types/index.d.ts +67 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/lib/index.d.ts +3 -0
- package/dist/types/lib/index.d.ts.map +1 -0
- package/dist/types/lib/initializeFirebase.d.ts +5 -0
- package/dist/types/lib/initializeFirebase.d.ts.map +1 -0
- package/dist/types/lib/sendPushNotification.d.ts +4 -0
- package/dist/types/lib/sendPushNotification.d.ts.map +1 -0
- package/dist/types/middlewares/isFirebaseEnabled.d.ts +4 -0
- package/dist/types/middlewares/isFirebaseEnabled.d.ts.map +1 -0
- package/dist/types/migrations/queryToCreateTable.d.ts +6 -0
- package/dist/types/migrations/queryToCreateTable.d.ts.map +1 -0
- package/dist/types/migrations/runMigrations.d.ts +5 -0
- package/dist/types/migrations/runMigrations.d.ts.map +1 -0
- package/dist/types/model/notification/controller.d.ts +4 -0
- package/dist/types/model/notification/controller.d.ts.map +1 -0
- package/dist/types/model/notification/graphql/resolver.d.ts +20 -0
- package/dist/types/model/notification/graphql/resolver.d.ts.map +1 -0
- package/dist/types/model/notification/graphql/schema.d.ts +3 -0
- package/dist/types/model/notification/graphql/schema.d.ts.map +1 -0
- package/dist/types/model/notification/handlers/index.d.ts +5 -0
- package/dist/types/model/notification/handlers/index.d.ts.map +1 -0
- package/dist/types/model/notification/handlers/sendNotification.d.ts +5 -0
- package/dist/types/model/notification/handlers/sendNotification.d.ts.map +1 -0
- package/dist/types/model/notification/schema.d.ts +75 -0
- package/dist/types/model/notification/schema.d.ts.map +1 -0
- package/dist/types/model/userDevice/controller.d.ts +4 -0
- package/dist/types/model/userDevice/controller.d.ts.map +1 -0
- package/dist/types/model/userDevice/graphql/resolver.d.ts +18 -0
- package/dist/types/model/userDevice/graphql/resolver.d.ts.map +1 -0
- package/dist/types/model/userDevice/graphql/schema.d.ts +3 -0
- package/dist/types/model/userDevice/graphql/schema.d.ts.map +1 -0
- package/dist/types/model/userDevice/handlers/addUserDevice.d.ts +5 -0
- package/dist/types/model/userDevice/handlers/addUserDevice.d.ts.map +1 -0
- package/dist/types/model/userDevice/handlers/index.d.ts +6 -0
- package/dist/types/model/userDevice/handlers/index.d.ts.map +1 -0
- package/dist/types/model/userDevice/handlers/removeUserDevice.d.ts +5 -0
- package/dist/types/model/userDevice/handlers/removeUserDevice.d.ts.map +1 -0
- package/dist/types/model/userDevice/schema.d.ts +153 -0
- package/dist/types/model/userDevice/schema.d.ts.map +1 -0
- package/dist/types/model/userDevice/service.d.ts +12 -0
- package/dist/types/model/userDevice/service.d.ts.map +1 -0
- package/dist/types/model/userDevice/sqlFactory.d.ts +10 -0
- package/dist/types/model/userDevice/sqlFactory.d.ts.map +1 -0
- package/dist/types/plugin.d.ts +4 -0
- package/dist/types/plugin.d.ts.map +1 -0
- package/dist/types/types.d.ts +21 -0
- package/dist/types/types.d.ts.map +1 -0
- package/package.json +80 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2017 Olivier Pichon
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
# @prefabs.tech/fastify-firebase
|
|
2
|
+
|
|
3
|
+
A [Fastify](https://github.com/fastify/fastify) plugin that provides an easy integration of Firebase Admin in a fastify API.
|
|
4
|
+
|
|
5
|
+
## Requirements
|
|
6
|
+
|
|
7
|
+
* [@prefabs.tech/fastify-config](../config/)
|
|
8
|
+
* [@prefabs.tech/fastify-slonik](../slonik/)
|
|
9
|
+
|
|
10
|
+
## Installation
|
|
11
|
+
|
|
12
|
+
Install with npm:
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npm install @prefabs.tech/fastify-config @prefabs.tech/fastify-slonik @prefabs.tech/fastify-firebase
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Install with pnpm:
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
pnpm add --filter "@scope/project" @prefabs.tech/fastify-config @prefabs.tech/fastify-slonik @prefabs.tech/fastify-firebase
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Usage
|
|
25
|
+
|
|
26
|
+
### Register Plugin
|
|
27
|
+
|
|
28
|
+
Register the fastify-firebase plugin with your Fastify instance:
|
|
29
|
+
|
|
30
|
+
```typescript
|
|
31
|
+
import firebasePlugin from "@prefabs.tech/fastify-firebase";
|
|
32
|
+
import configPlugin from "@prefabs.tech/fastify-config";
|
|
33
|
+
import Fastify from "fastify";
|
|
34
|
+
|
|
35
|
+
import config from "./config";
|
|
36
|
+
|
|
37
|
+
import type { ApiConfig } from "@prefabs.tech/fastify-config";
|
|
38
|
+
import type { FastifyInstance } from "fastify";
|
|
39
|
+
|
|
40
|
+
const start = async () => {
|
|
41
|
+
// Create fastify instance
|
|
42
|
+
const fastify = Fastify({
|
|
43
|
+
logger: config.logger,
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
// Register fastify-config plugin
|
|
47
|
+
await fastify.register(configPlugin, { config });
|
|
48
|
+
|
|
49
|
+
// Register fastify-firebase plugin
|
|
50
|
+
await fastify.register(firebasePlugin);
|
|
51
|
+
|
|
52
|
+
await fastify.listen({
|
|
53
|
+
port: config.port,
|
|
54
|
+
host: "0.0.0.0",
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
start();
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Configuration
|
|
62
|
+
|
|
63
|
+
Add firebase configuration
|
|
64
|
+
|
|
65
|
+
```typescript
|
|
66
|
+
const config: ApiConfig = {
|
|
67
|
+
// ...
|
|
68
|
+
firebase: {
|
|
69
|
+
credentials: {
|
|
70
|
+
clientEmail: "...",
|
|
71
|
+
privateKey: "...",
|
|
72
|
+
projectId: "...",
|
|
73
|
+
}
|
|
74
|
+
table: {
|
|
75
|
+
userDevices: {
|
|
76
|
+
name: "user-devices";
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
notification: {
|
|
80
|
+
test: {
|
|
81
|
+
enabled: true,
|
|
82
|
+
path: '/send-notification'
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
handlers: {
|
|
86
|
+
userDevice?: {
|
|
87
|
+
addUserDevice: (request: SessionRequest, reply: FastifyReply) => Promise<void>
|
|
88
|
+
},
|
|
89
|
+
notification: {
|
|
90
|
+
sendNotification: (request: SessionRequest, reply: FastifyReply) => Promise<void>
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## Using GraphQL
|
|
98
|
+
|
|
99
|
+
This package supports integration with [@prefabs.tech/fastify-graphql](../graphql/).
|
|
100
|
+
|
|
101
|
+
### Schema Integration
|
|
102
|
+
|
|
103
|
+
The GraphQL schema provided by this package is located at [src/graphql/schema.ts](./src/graphql/schema.ts) and is exported as `firebaseSchema`.
|
|
104
|
+
|
|
105
|
+
To load and merge this schema with your application's custom schemas, update your schema file as follows:
|
|
106
|
+
|
|
107
|
+
```typescript
|
|
108
|
+
import { firebaseSchema } from "@prefabs.tech/fastify-firebase";
|
|
109
|
+
import { loadFilesSync } from "@graphql-tools/load-files";
|
|
110
|
+
import { mergeTypeDefs } from "";
|
|
111
|
+
import { makeExecutableSchema } from "@graphql-tools/schema";
|
|
112
|
+
|
|
113
|
+
const schemas: string[] = loadFilesSync("./src/**/*.gql");
|
|
114
|
+
|
|
115
|
+
const typeDefs = mergeTypeDefs([firebaseSchema, ...schemas]);
|
|
116
|
+
const schema = makeExecutableSchema({ typeDefs });
|
|
117
|
+
|
|
118
|
+
export default schema;
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
### Resolver Integration
|
|
122
|
+
|
|
123
|
+
To integrate the resolvers provided by this package, import them and merge with your application's resolvers:
|
|
124
|
+
|
|
125
|
+
```typescript
|
|
126
|
+
import { notificationResolver, userDeviceResolver } from "@prefabs.tech/fastify-firebase";
|
|
127
|
+
|
|
128
|
+
import type { IResolvers } from "mercurius";
|
|
129
|
+
|
|
130
|
+
const resolvers: IResolvers = {
|
|
131
|
+
Mutation: {
|
|
132
|
+
// ...other mutations ...
|
|
133
|
+
...userDeviceResolver.Mutation,
|
|
134
|
+
...notificationResolver.Mutation,
|
|
135
|
+
},
|
|
136
|
+
Query: {
|
|
137
|
+
// ...other queries ...
|
|
138
|
+
...userDeviceResolver.Query,
|
|
139
|
+
...notificationResolver.Query,
|
|
140
|
+
},
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
export default resolvers;
|
|
144
|
+
```
|
|
@@ -0,0 +1,464 @@
|
|
|
1
|
+
import N from "fastify-plugin";
|
|
2
|
+
import { apps as k, initializeApp as R, credential as F, messaging as A } from "firebase-admin";
|
|
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)) {
|
|
9
|
+
if (e.firebase?.enabled !== !1 && !e.firebase.credentials) {
|
|
10
|
+
r.log.error("Firebase credentials are missing");
|
|
11
|
+
return;
|
|
12
|
+
}
|
|
13
|
+
try {
|
|
14
|
+
R({
|
|
15
|
+
credential: F.cert({
|
|
16
|
+
projectId: e.firebase.credentials?.projectId,
|
|
17
|
+
privateKey: e.firebase.credentials?.privateKey.replaceAll(
|
|
18
|
+
String.raw`\n`,
|
|
19
|
+
`
|
|
20
|
+
`
|
|
21
|
+
),
|
|
22
|
+
clientEmail: e.firebase.credentials?.clientEmail
|
|
23
|
+
})
|
|
24
|
+
});
|
|
25
|
+
} catch (t) {
|
|
26
|
+
r.log.error("Failed to initialize firebase"), r.log.error(t);
|
|
27
|
+
}
|
|
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;
|
|
33
|
+
return l.unsafe`
|
|
34
|
+
DO $$
|
|
35
|
+
BEGIN
|
|
36
|
+
CREATE TABLE IF NOT EXISTS ${l.identifier([r])} (
|
|
37
|
+
id INT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
|
38
|
+
user_id VARCHAR(255) NOT NULL,
|
|
39
|
+
device_token VARCHAR(255) NOT NULL,
|
|
40
|
+
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
41
|
+
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
|
42
|
+
);
|
|
43
|
+
|
|
44
|
+
CREATE INDEX IF NOT EXISTS idx_user_id_device_token ON ${l.identifier([
|
|
45
|
+
r
|
|
46
|
+
])} (user_id, device_token);
|
|
47
|
+
END $$;
|
|
48
|
+
`;
|
|
49
|
+
}, W = async (e, r) => {
|
|
50
|
+
await e.connect(async (t) => {
|
|
51
|
+
await t.query(z(r));
|
|
52
|
+
});
|
|
53
|
+
};
|
|
54
|
+
class j extends O {
|
|
55
|
+
static TABLE = T;
|
|
56
|
+
getDeleteExistingTokenSql(r) {
|
|
57
|
+
return l.type(this.validationSchema)`
|
|
58
|
+
DELETE
|
|
59
|
+
FROM ${this.tableFragment}
|
|
60
|
+
${this.getWhereFragment({ filterFragment: l.fragment`device_token = ${r}` })}
|
|
61
|
+
RETURNING *;
|
|
62
|
+
`;
|
|
63
|
+
}
|
|
64
|
+
getFindByUserIdSql(r) {
|
|
65
|
+
return l.type(this.validationSchema)`
|
|
66
|
+
SELECT *
|
|
67
|
+
FROM ${this.tableFragment}
|
|
68
|
+
${this.getWhereFragment({ filterFragment: l.fragment`user_id = ${r}` })};
|
|
69
|
+
`;
|
|
70
|
+
}
|
|
71
|
+
get table() {
|
|
72
|
+
return this.config.firebase.table?.userDevices?.name || super.table;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
class v extends _ {
|
|
76
|
+
async getByUserId(r) {
|
|
77
|
+
const t = this.factory.getFindByUserIdSql(r);
|
|
78
|
+
return await this.database.connect((i) => i.any(t));
|
|
79
|
+
}
|
|
80
|
+
async removeByDeviceToken(r) {
|
|
81
|
+
const t = this.factory.getDeleteExistingTokenSql(r);
|
|
82
|
+
return await this.database.connect((i) => i.maybeOne(t));
|
|
83
|
+
}
|
|
84
|
+
get factory() {
|
|
85
|
+
return super.factory;
|
|
86
|
+
}
|
|
87
|
+
get sqlFactoryClass() {
|
|
88
|
+
return j;
|
|
89
|
+
}
|
|
90
|
+
async preCreate(r) {
|
|
91
|
+
const { deviceToken: t } = r;
|
|
92
|
+
return await this.removeByDeviceToken(t), r;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const x = async (e, r) => {
|
|
96
|
+
if (!e.user)
|
|
97
|
+
return r.status(401).send({
|
|
98
|
+
error: "Unauthorized",
|
|
99
|
+
message: "unauthorized",
|
|
100
|
+
statusCode: 401
|
|
101
|
+
});
|
|
102
|
+
const {
|
|
103
|
+
body: s,
|
|
104
|
+
title: i,
|
|
105
|
+
data: o,
|
|
106
|
+
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(
|
|
111
|
+
e.config,
|
|
112
|
+
e.slonik,
|
|
113
|
+
e.dbSchema
|
|
114
|
+
).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 = {
|
|
118
|
+
android: {
|
|
119
|
+
priority: "high",
|
|
120
|
+
notification: {
|
|
121
|
+
sound: "default"
|
|
122
|
+
}
|
|
123
|
+
},
|
|
124
|
+
apns: {
|
|
125
|
+
payload: {
|
|
126
|
+
aps: {
|
|
127
|
+
sound: "default"
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
},
|
|
131
|
+
tokens: u,
|
|
132
|
+
notification: {
|
|
133
|
+
title: i,
|
|
134
|
+
body: s
|
|
135
|
+
},
|
|
136
|
+
data: {
|
|
137
|
+
...o,
|
|
138
|
+
title: i,
|
|
139
|
+
body: s
|
|
140
|
+
}
|
|
141
|
+
};
|
|
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 = {
|
|
155
|
+
description: "Send a notification to a specific user",
|
|
156
|
+
operationId: "sendNotification",
|
|
157
|
+
body: {
|
|
158
|
+
type: "object",
|
|
159
|
+
properties: {
|
|
160
|
+
title: { type: "string" },
|
|
161
|
+
message: { type: "string" },
|
|
162
|
+
userId: { type: "string" }
|
|
163
|
+
},
|
|
164
|
+
required: ["title", "message", "userId"]
|
|
165
|
+
},
|
|
166
|
+
response: {
|
|
167
|
+
200: {
|
|
168
|
+
type: "object",
|
|
169
|
+
properties: {
|
|
170
|
+
success: { type: "boolean" },
|
|
171
|
+
message: { type: "string" }
|
|
172
|
+
}
|
|
173
|
+
},
|
|
174
|
+
401: {
|
|
175
|
+
description: "Unauthorized",
|
|
176
|
+
...y
|
|
177
|
+
},
|
|
178
|
+
500: {
|
|
179
|
+
...y
|
|
180
|
+
}
|
|
181
|
+
},
|
|
182
|
+
tags: ["notifications"]
|
|
183
|
+
}, b = (e) => async () => {
|
|
184
|
+
if (e.config.firebase.enabled === !1)
|
|
185
|
+
throw new Error("Firebase is not enabled");
|
|
186
|
+
}, H = async (e) => {
|
|
187
|
+
const r = e.config.firebase.handlers?.userDevice, t = e.config.firebase.notification;
|
|
188
|
+
t?.test?.enabled && e.post(
|
|
189
|
+
t.test.path || M,
|
|
190
|
+
{
|
|
191
|
+
preHandler: [e.verifySession(), b(e)],
|
|
192
|
+
schema: V
|
|
193
|
+
},
|
|
194
|
+
r?.addUserDevice || q.sendNotification
|
|
195
|
+
);
|
|
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) => {
|
|
210
|
+
const t = e.user;
|
|
211
|
+
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);
|
|
221
|
+
if (!o || o.length === 0)
|
|
222
|
+
throw e.log.error("No devices found for user"), new Error("Oops, Something went wrong");
|
|
223
|
+
if (!o.find(
|
|
224
|
+
(a) => a.deviceToken === s
|
|
225
|
+
))
|
|
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 = {
|
|
241
|
+
type: "object",
|
|
242
|
+
properties: {
|
|
243
|
+
userId: { type: "string" },
|
|
244
|
+
deviceToken: { type: "string" },
|
|
245
|
+
createdAt: { type: "number" },
|
|
246
|
+
updatedAt: { type: "number" }
|
|
247
|
+
},
|
|
248
|
+
required: ["userId", "deviceToken", "createdAt", "updatedAt"]
|
|
249
|
+
}, K = {
|
|
250
|
+
description: "Delete a user device by device token",
|
|
251
|
+
operationId: "deleteUserDevice",
|
|
252
|
+
body: {
|
|
253
|
+
type: "object",
|
|
254
|
+
properties: {
|
|
255
|
+
deviceToken: { type: "string" }
|
|
256
|
+
},
|
|
257
|
+
required: ["deviceToken"]
|
|
258
|
+
},
|
|
259
|
+
response: {
|
|
260
|
+
200: {
|
|
261
|
+
...S,
|
|
262
|
+
nullable: !0
|
|
263
|
+
},
|
|
264
|
+
401: {
|
|
265
|
+
description: "Unauthorized",
|
|
266
|
+
...f
|
|
267
|
+
},
|
|
268
|
+
500: {
|
|
269
|
+
...f
|
|
270
|
+
}
|
|
271
|
+
},
|
|
272
|
+
tags: ["user-devices"]
|
|
273
|
+
}, Q = {
|
|
274
|
+
description: "Register a new user device",
|
|
275
|
+
operationId: "postUserDevice",
|
|
276
|
+
body: {
|
|
277
|
+
type: "object",
|
|
278
|
+
properties: {
|
|
279
|
+
deviceToken: { type: "string" }
|
|
280
|
+
},
|
|
281
|
+
required: ["deviceToken"]
|
|
282
|
+
},
|
|
283
|
+
response: {
|
|
284
|
+
200: {
|
|
285
|
+
...S,
|
|
286
|
+
nullable: !0
|
|
287
|
+
},
|
|
288
|
+
401: {
|
|
289
|
+
description: "Unauthorized",
|
|
290
|
+
...f
|
|
291
|
+
},
|
|
292
|
+
500: {
|
|
293
|
+
...f
|
|
294
|
+
}
|
|
295
|
+
},
|
|
296
|
+
tags: ["user-devices"]
|
|
297
|
+
}, X = async (e) => {
|
|
298
|
+
const r = e.config.firebase.handlers?.userDevice;
|
|
299
|
+
e.post(
|
|
300
|
+
B,
|
|
301
|
+
{
|
|
302
|
+
preHandler: [e.verifySession(), b(e)],
|
|
303
|
+
schema: Q
|
|
304
|
+
},
|
|
305
|
+
r?.addUserDevice || E.addUserDevice
|
|
306
|
+
), e.delete(
|
|
307
|
+
L,
|
|
308
|
+
{
|
|
309
|
+
preHandler: [e.verifySession(), b(e)],
|
|
310
|
+
schema: K
|
|
311
|
+
},
|
|
312
|
+
r?.removeUserDevice || E.removeUserDevice
|
|
313
|
+
);
|
|
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));
|
|
317
|
+
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 = {
|
|
320
|
+
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);
|
|
324
|
+
if (i.firebase.enabled === !1)
|
|
325
|
+
return new c.ErrorWithProps("Firebase is not enabled", {}, 404);
|
|
326
|
+
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);
|
|
330
|
+
const h = await new v(
|
|
331
|
+
i,
|
|
332
|
+
d,
|
|
333
|
+
o
|
|
334
|
+
).getByUserId(n);
|
|
335
|
+
if (!h || h.length === 0)
|
|
336
|
+
return new c.ErrorWithProps(
|
|
337
|
+
"Receiver device not found",
|
|
338
|
+
{},
|
|
339
|
+
404
|
|
340
|
+
);
|
|
341
|
+
const U = {
|
|
342
|
+
tokens: h.map(
|
|
343
|
+
(I) => I.deviceToken
|
|
344
|
+
),
|
|
345
|
+
notification: {
|
|
346
|
+
title: u,
|
|
347
|
+
body: p
|
|
348
|
+
},
|
|
349
|
+
data: g
|
|
350
|
+
};
|
|
351
|
+
return await w(U), { message: "Notification sent successfully" };
|
|
352
|
+
} catch (n) {
|
|
353
|
+
return s.log.error(n), new c.ErrorWithProps(
|
|
354
|
+
"Oops, Something went wrong",
|
|
355
|
+
{},
|
|
356
|
+
500
|
|
357
|
+
);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
}, ee = {}, ve = { Mutation: Z, Query: ee }, re = {
|
|
361
|
+
addUserDevice: async (e, r, t) => {
|
|
362
|
+
const { app: s, config: i, dbSchema: o, database: d, user: a } = t;
|
|
363
|
+
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);
|
|
367
|
+
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(
|
|
372
|
+
"Oops, Something went wrong",
|
|
373
|
+
{},
|
|
374
|
+
500
|
|
375
|
+
);
|
|
376
|
+
}
|
|
377
|
+
},
|
|
378
|
+
removeUserDevice: async (e, r, t) => {
|
|
379
|
+
const { app: s, config: i, dbSchema: o, database: d, user: a } = t;
|
|
380
|
+
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);
|
|
384
|
+
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(
|
|
387
|
+
"No devices found for user",
|
|
388
|
+
{},
|
|
389
|
+
403
|
|
390
|
+
) : p.find(
|
|
391
|
+
(m) => m.deviceToken === n
|
|
392
|
+
) ? await u.removeByDeviceToken(n) : new c.ErrorWithProps(
|
|
393
|
+
"Device requested to delete not owned by user",
|
|
394
|
+
{},
|
|
395
|
+
403
|
|
396
|
+
);
|
|
397
|
+
} catch (n) {
|
|
398
|
+
return s.log.error(n), new c.ErrorWithProps(
|
|
399
|
+
"Oops, Something went wrong",
|
|
400
|
+
{},
|
|
401
|
+
500
|
|
402
|
+
);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
}, te = {}, ge = { Mutation: re, Query: te }, ie = D`
|
|
406
|
+
type SendNotificationResponse {
|
|
407
|
+
message: String!
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
input SendNotificationInput {
|
|
411
|
+
userId: String!
|
|
412
|
+
title: String!
|
|
413
|
+
body: String!
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
type Mutation {
|
|
417
|
+
sendNotification(data: SendNotificationInput): SendNotificationResponse
|
|
418
|
+
@auth
|
|
419
|
+
}
|
|
420
|
+
`, ne = D`
|
|
421
|
+
type UserDevice {
|
|
422
|
+
id: Int!
|
|
423
|
+
userId: String!
|
|
424
|
+
deviceToken: String!
|
|
425
|
+
createdAt: Float!
|
|
426
|
+
updatedAt: Float!
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
type UserDevices {
|
|
430
|
+
data: [UserDevice]!
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
input UserDeviceCreateInput {
|
|
434
|
+
deviceToken: String!
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
input UserDeviceUpdateInput {
|
|
438
|
+
deviceToken: String!
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
input UserDeviceRemoveInput {
|
|
442
|
+
deviceToken: String!
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
type Mutation {
|
|
446
|
+
addUserDevice(data: UserDeviceCreateInput): UserDevice @auth
|
|
447
|
+
removeUserDevice(data: UserDeviceRemoveInput): UserDevice @auth
|
|
448
|
+
}
|
|
449
|
+
`, fe = C([
|
|
450
|
+
P,
|
|
451
|
+
ie,
|
|
452
|
+
ne
|
|
453
|
+
]);
|
|
454
|
+
export {
|
|
455
|
+
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
|
|
464
|
+
};
|
|
@@ -0,0 +1,68 @@
|
|
|
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`
|
|
3
|
+
DO $$
|
|
4
|
+
BEGIN
|
|
5
|
+
CREATE TABLE IF NOT EXISTS ${p.sql.identifier([t])} (
|
|
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([t])} (user_id, device_token);
|
|
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)`
|
|
16
|
+
DELETE
|
|
17
|
+
FROM ${this.tableFragment}
|
|
18
|
+
${this.getWhereFragment({filterFragment:p.sql.fragment`device_token = ${t}`})}
|
|
19
|
+
RETURNING *;
|
|
20
|
+
`}getFindByUserIdSql(t){return p.sql.type(this.validationSchema)`
|
|
21
|
+
SELECT *
|
|
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`
|
|
25
|
+
type SendNotificationResponse {
|
|
26
|
+
message: String!
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
input SendNotificationInput {
|
|
30
|
+
userId: String!
|
|
31
|
+
title: String!
|
|
32
|
+
body: String!
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
type Mutation {
|
|
36
|
+
sendNotification(data: SendNotificationInput): SendNotificationResponse
|
|
37
|
+
@auth
|
|
38
|
+
}
|
|
39
|
+
`,Q=y.gql`
|
|
40
|
+
type UserDevice {
|
|
41
|
+
id: Int!
|
|
42
|
+
userId: String!
|
|
43
|
+
deviceToken: String!
|
|
44
|
+
createdAt: Float!
|
|
45
|
+
updatedAt: Float!
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
type UserDevices {
|
|
49
|
+
data: [UserDevice]!
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
input UserDeviceCreateInput {
|
|
53
|
+
deviceToken: String!
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
input UserDeviceUpdateInput {
|
|
57
|
+
deviceToken: String!
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
input UserDeviceRemoveInput {
|
|
61
|
+
deviceToken: String!
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
type Mutation {
|
|
65
|
+
addUserDevice(data: UserDeviceCreateInput): UserDevice @auth
|
|
66
|
+
removeUserDevice(data: UserDeviceRemoveInput): UserDevice @auth
|
|
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"}})});
|