@terreno/comms 56.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/biome.jsonc +17 -0
  3. package/bunfig.toml +5 -0
  4. package/dist/adapters/console.d.ts +30 -0
  5. package/dist/adapters/console.js +122 -0
  6. package/dist/commsApp.d.ts +14 -0
  7. package/dist/commsApp.js +37 -0
  8. package/dist/commsService.d.ts +20 -0
  9. package/dist/commsService.js +386 -0
  10. package/dist/index.d.ts +10 -0
  11. package/dist/index.js +19 -0
  12. package/dist/modelTypes.d.ts +53 -0
  13. package/dist/modelTypes.js +2 -0
  14. package/dist/models/commsMessage.d.ts +2 -0
  15. package/dist/models/commsMessage.js +119 -0
  16. package/dist/models/pushToken.d.ts +2 -0
  17. package/dist/models/pushToken.js +56 -0
  18. package/dist/routes/commsExplorer.d.ts +7 -0
  19. package/dist/routes/commsExplorer.js +147 -0
  20. package/dist/routes/pushTokens.d.ts +7 -0
  21. package/dist/routes/pushTokens.js +292 -0
  22. package/dist/templates.d.ts +10 -0
  23. package/dist/templates.js +32 -0
  24. package/dist/types.d.ts +78 -0
  25. package/dist/types.js +2 -0
  26. package/package.json +55 -0
  27. package/src/adapters/console.test.ts +227 -0
  28. package/src/adapters/console.ts +87 -0
  29. package/src/commsApp.test.ts +448 -0
  30. package/src/commsApp.ts +48 -0
  31. package/src/commsService.test.ts +570 -0
  32. package/src/commsService.ts +293 -0
  33. package/src/index.ts +45 -0
  34. package/src/modelTypes.ts +78 -0
  35. package/src/models/commsMessage.test.ts +53 -0
  36. package/src/models/commsMessage.ts +97 -0
  37. package/src/models/pushToken.test.ts +45 -0
  38. package/src/models/pushToken.ts +69 -0
  39. package/src/routes/commsExplorer.ts +114 -0
  40. package/src/routes/pushTokens.ts +265 -0
  41. package/src/templates.test.ts +37 -0
  42. package/src/templates.ts +31 -0
  43. package/src/tests/bunSetup.ts +14 -0
  44. package/src/types.ts +93 -0
  45. package/tsconfig.json +32 -0
@@ -0,0 +1,293 @@
1
+ import {APIError, logger} from "@terreno/api";
2
+
3
+ import {
4
+ ConsoleMailProvider,
5
+ ConsolePushProvider,
6
+ ConsoleSmsProvider,
7
+ ConsoleVerificationProvider,
8
+ } from "./adapters/console";
9
+ import {CommsMessage} from "./models/commsMessage";
10
+ import {PushToken} from "./models/pushToken";
11
+ import type {
12
+ CheckVerificationOptions,
13
+ CommsOptions,
14
+ MailMessage,
15
+ MailProvider,
16
+ PushMessage,
17
+ PushProvider,
18
+ SendPushToUserMessage,
19
+ SendResult,
20
+ SmsMessage,
21
+ SmsProvider,
22
+ StartVerificationOptions,
23
+ VerificationProvider,
24
+ VerificationResult,
25
+ } from "./types";
26
+
27
+ const CHANNEL_NOT_CONFIGURED_TITLE = "Comms channel not configured";
28
+ const REDACTED_RECIPIENT = "[redacted]";
29
+
30
+ const throwUnconfiguredChannel = (): never => {
31
+ throw new APIError({status: 501, title: CHANNEL_NOT_CONFIGURED_TITLE});
32
+ };
33
+
34
+ const isProduction = (): boolean => process.env.NODE_ENV === "production";
35
+
36
+ export class CommsService {
37
+ private readonly options: CommsOptions;
38
+ private readonly consoleMail = new ConsoleMailProvider();
39
+ private readonly consolePush = new ConsolePushProvider();
40
+ private readonly consoleSms = new ConsoleSmsProvider();
41
+ private readonly consoleVerification = new ConsoleVerificationProvider();
42
+
43
+ constructor(options?: CommsOptions) {
44
+ this.options = options ?? {};
45
+ }
46
+
47
+ private recipientForLog(recipient: string | string[]): string {
48
+ if (this.options.redactRecipients !== false) {
49
+ return REDACTED_RECIPIENT;
50
+ }
51
+ return Array.isArray(recipient) ? recipient.join(",") : recipient;
52
+ }
53
+
54
+ private async logResult({
55
+ channel,
56
+ metadata,
57
+ provider,
58
+ result,
59
+ subject,
60
+ to,
61
+ userId,
62
+ }: {
63
+ channel: "mail" | "push" | "sms" | "verification";
64
+ metadata?: Record<string, unknown>;
65
+ provider: string;
66
+ result: SendResult;
67
+ subject?: string;
68
+ to: string | string[];
69
+ userId?: string;
70
+ }): Promise<void> {
71
+ if (this.options.logMessages === false) {
72
+ return;
73
+ }
74
+
75
+ await CommsMessage.logSend({
76
+ channel,
77
+ error: result.error,
78
+ metadata,
79
+ provider,
80
+ providerMessageId: result.providerMessageId,
81
+ status: result.accepted ? "sent" : "failed",
82
+ subject,
83
+ to: this.recipientForLog(to),
84
+ userId,
85
+ });
86
+ }
87
+
88
+ private mailProvider(): MailProvider {
89
+ if (this.options.mail) {
90
+ return this.options.mail;
91
+ }
92
+ if (isProduction()) {
93
+ return throwUnconfiguredChannel();
94
+ }
95
+ logger.warn("[comms] Mail provider not configured; using console provider");
96
+ return this.consoleMail;
97
+ }
98
+
99
+ private smsProvider(): SmsProvider {
100
+ if (this.options.sms) {
101
+ return this.options.sms;
102
+ }
103
+ if (isProduction()) {
104
+ return throwUnconfiguredChannel();
105
+ }
106
+ logger.warn("[comms] SMS provider not configured; using console provider");
107
+ return this.consoleSms;
108
+ }
109
+
110
+ private pushProvider(): PushProvider {
111
+ if (this.options.push) {
112
+ return this.options.push;
113
+ }
114
+ if (isProduction()) {
115
+ return throwUnconfiguredChannel();
116
+ }
117
+ logger.warn("[comms] Push provider not configured; using console provider");
118
+ return this.consolePush;
119
+ }
120
+
121
+ private verificationProvider(): VerificationProvider {
122
+ if (this.options.verification) {
123
+ return this.options.verification;
124
+ }
125
+ if (isProduction()) {
126
+ return throwUnconfiguredChannel();
127
+ }
128
+ logger.warn("[comms] Verification provider not configured; using console provider");
129
+ return this.consoleVerification;
130
+ }
131
+
132
+ async sendMail(message: MailMessage): Promise<SendResult> {
133
+ const provider = this.mailProvider();
134
+ const resolvedMessage = {
135
+ ...message,
136
+ from: message.from ?? this.options.defaultFrom,
137
+ };
138
+
139
+ try {
140
+ const result = await provider.sendMail(resolvedMessage);
141
+ await this.logResult({
142
+ channel: "mail",
143
+ provider: provider.id,
144
+ result,
145
+ subject: message.subject,
146
+ to: message.to,
147
+ });
148
+ return result;
149
+ } catch (error: unknown) {
150
+ await this.logResult({
151
+ channel: "mail",
152
+ provider: provider.id,
153
+ result: {accepted: false, error: "Provider send failed"},
154
+ subject: message.subject,
155
+ to: message.to,
156
+ });
157
+ throw error;
158
+ }
159
+ }
160
+
161
+ async sendSms(message: SmsMessage): Promise<SendResult> {
162
+ const provider = this.smsProvider();
163
+
164
+ try {
165
+ const result = await provider.sendSms(message);
166
+ await this.logResult({
167
+ channel: "sms",
168
+ provider: provider.id,
169
+ result,
170
+ to: message.to,
171
+ });
172
+ return result;
173
+ } catch (error: unknown) {
174
+ await this.logResult({
175
+ channel: "sms",
176
+ provider: provider.id,
177
+ result: {accepted: false, error: "Provider send failed"},
178
+ to: message.to,
179
+ });
180
+ throw error;
181
+ }
182
+ }
183
+
184
+ async sendPushToUser(message: SendPushToUserMessage): Promise<SendResult[]> {
185
+ const provider = this.pushProvider();
186
+ const tokens = await PushToken.find({active: true, userId: message.userId});
187
+ if (tokens.length === 0) {
188
+ return [];
189
+ }
190
+
191
+ const providerMessage: PushMessage = {
192
+ badge: message.badge,
193
+ body: message.body,
194
+ data: message.data,
195
+ sound: message.sound,
196
+ title: message.title,
197
+ tokens: tokens.map((token) => token.token),
198
+ };
199
+ let results: SendResult[];
200
+ try {
201
+ results = await provider.sendPush(providerMessage);
202
+ } catch (error: unknown) {
203
+ await Promise.all(
204
+ tokens.map(
205
+ (token): Promise<void> =>
206
+ this.logResult({
207
+ channel: "push",
208
+ provider: provider.id,
209
+ result: {accepted: false, error: "Provider send failed"},
210
+ to: token.token,
211
+ userId: String(message.userId),
212
+ })
213
+ )
214
+ );
215
+ throw error;
216
+ }
217
+
218
+ const normalizedResults = tokens.map(
219
+ (_token, index): SendResult =>
220
+ results[index] ?? {
221
+ accepted: false,
222
+ error: "Provider returned no result for token",
223
+ }
224
+ );
225
+ await Promise.all(
226
+ tokens.map(async (token, index): Promise<void> => {
227
+ const result = normalizedResults[index] as SendResult;
228
+ await this.logResult({
229
+ channel: "push",
230
+ provider: provider.id,
231
+ result,
232
+ to: token.token,
233
+ userId: String(message.userId),
234
+ });
235
+ if (!result.accepted && result.isPermanentFailure) {
236
+ token.active = false;
237
+ await token.save();
238
+ }
239
+ })
240
+ );
241
+
242
+ return normalizedResults;
243
+ }
244
+
245
+ async startVerification(options: StartVerificationOptions): Promise<SendResult> {
246
+ const provider = this.verificationProvider();
247
+ try {
248
+ const result = await provider.startVerification(options);
249
+ await this.logResult({
250
+ channel: "verification",
251
+ metadata: {verificationChannel: options.channel},
252
+ provider: provider.id,
253
+ result,
254
+ to: options.to,
255
+ });
256
+ return result;
257
+ } catch (error: unknown) {
258
+ await this.logResult({
259
+ channel: "verification",
260
+ metadata: {verificationChannel: options.channel},
261
+ provider: provider.id,
262
+ result: {accepted: false, error: "Provider send failed"},
263
+ to: options.to,
264
+ });
265
+ throw error;
266
+ }
267
+ }
268
+
269
+ async checkVerification(options: CheckVerificationOptions): Promise<VerificationResult> {
270
+ const provider = this.verificationProvider();
271
+ try {
272
+ const result = await provider.checkVerification(options);
273
+ await this.logResult({
274
+ channel: "verification",
275
+ provider: provider.id,
276
+ result: {
277
+ accepted: result.valid,
278
+ ...(result.valid ? {} : {error: result.error ?? "Verification check failed"}),
279
+ },
280
+ to: options.to,
281
+ });
282
+ return result;
283
+ } catch (error: unknown) {
284
+ await this.logResult({
285
+ channel: "verification",
286
+ provider: provider.id,
287
+ result: {accepted: false, error: "Provider check failed"},
288
+ to: options.to,
289
+ });
290
+ throw error;
291
+ }
292
+ }
293
+ }
package/src/index.ts ADDED
@@ -0,0 +1,45 @@
1
+ export {
2
+ ConsoleMailProvider,
3
+ ConsolePushProvider,
4
+ ConsoleSmsProvider,
5
+ ConsoleVerificationProvider,
6
+ } from "./adapters/console";
7
+ export type {CommsAppOptions} from "./commsApp";
8
+ export {CommsApp, getCommsService} from "./commsApp";
9
+ export {CommsService} from "./commsService";
10
+ export {CommsMessage} from "./models/commsMessage";
11
+ export {PushToken} from "./models/pushToken";
12
+ export type {
13
+ CommsMessageDocument,
14
+ CommsMessageMethods,
15
+ CommsMessageModel,
16
+ CommsMessageSchema,
17
+ CommsMessageStatics,
18
+ LogSendParams,
19
+ PushTokenDocument,
20
+ PushTokenMethods,
21
+ PushTokenModel,
22
+ PushTokenPlatform,
23
+ PushTokenSchema,
24
+ PushTokenStatics,
25
+ } from "./modelTypes";
26
+ export type {MessageTemplate, RenderTemplateOptions} from "./templates";
27
+ export {renderTemplate} from "./templates";
28
+ export type {
29
+ CheckVerificationOptions,
30
+ CommsChannel,
31
+ CommsMessageStatus,
32
+ CommsOptions,
33
+ DeliveryEvent,
34
+ MailMessage,
35
+ MailProvider,
36
+ PushMessage,
37
+ PushProvider,
38
+ SendPushToUserMessage,
39
+ SendResult,
40
+ SmsMessage,
41
+ SmsProvider,
42
+ StartVerificationOptions,
43
+ VerificationProvider,
44
+ VerificationResult,
45
+ } from "./types";
@@ -0,0 +1,78 @@
1
+ import type {FindExactlyOnePlugin, FindOneOrNonePlugin, HasUpsert} from "@terreno/api";
2
+ import type mongoose from "mongoose";
3
+
4
+ import type {CommsChannel, CommsMessageStatus} from "./types";
5
+
6
+ export type CommsMessageMethods = Record<never, never>;
7
+
8
+ export interface CommsMessageDocument
9
+ extends mongoose.Document<mongoose.Types.ObjectId>,
10
+ CommsMessageMethods {
11
+ channel: CommsChannel;
12
+ created: Date;
13
+ deleted: boolean;
14
+ error?: string;
15
+ metadata?: Record<string, unknown>;
16
+ provider: string;
17
+ providerMessageId?: string;
18
+ status: CommsMessageStatus;
19
+ subject?: string;
20
+ to: string;
21
+ updated: Date;
22
+ userId?: mongoose.Types.ObjectId;
23
+ }
24
+
25
+ export interface LogSendParams {
26
+ channel: CommsChannel;
27
+ error?: string;
28
+ metadata?: Record<string, unknown>;
29
+ provider: string;
30
+ providerMessageId?: string;
31
+ status: CommsMessageStatus;
32
+ subject?: string;
33
+ to: string;
34
+ userId?: mongoose.Types.ObjectId | string;
35
+ }
36
+
37
+ export interface CommsMessageStatics
38
+ extends FindExactlyOnePlugin<CommsMessageDocument>,
39
+ FindOneOrNonePlugin<CommsMessageDocument> {
40
+ logSend(params: LogSendParams): Promise<CommsMessageDocument | null>;
41
+ }
42
+
43
+ export interface CommsMessageModel
44
+ extends mongoose.Model<CommsMessageDocument>,
45
+ CommsMessageStatics {}
46
+
47
+ export type CommsMessageSchema = mongoose.Schema<
48
+ CommsMessageDocument,
49
+ CommsMessageModel,
50
+ CommsMessageMethods
51
+ >;
52
+
53
+ export type PushTokenPlatform = "android" | "ios" | "web";
54
+
55
+ export type PushTokenMethods = Record<never, never>;
56
+
57
+ export interface PushTokenDocument
58
+ extends mongoose.Document<mongoose.Types.ObjectId>,
59
+ PushTokenMethods {
60
+ active: boolean;
61
+ created: Date;
62
+ deleted: boolean;
63
+ deviceId?: string;
64
+ lastSeenAt: Date;
65
+ platform: PushTokenPlatform;
66
+ token: string;
67
+ updated: Date;
68
+ userId: mongoose.Types.ObjectId;
69
+ }
70
+
71
+ export interface PushTokenStatics
72
+ extends FindExactlyOnePlugin<PushTokenDocument>,
73
+ FindOneOrNonePlugin<PushTokenDocument>,
74
+ HasUpsert<PushTokenDocument> {}
75
+
76
+ export interface PushTokenModel extends mongoose.Model<PushTokenDocument>, PushTokenStatics {}
77
+
78
+ export type PushTokenSchema = mongoose.Schema<PushTokenDocument, PushTokenModel, PushTokenMethods>;
@@ -0,0 +1,53 @@
1
+ import {beforeEach, describe, it} from "bun:test";
2
+ import {setupDb} from "@terreno/api/testing";
3
+ import {assert} from "chai";
4
+
5
+ import {CommsMessage} from "./commsMessage";
6
+
7
+ const COMMS_MESSAGE_FIELDS = [
8
+ "channel",
9
+ "error",
10
+ "metadata",
11
+ "provider",
12
+ "providerMessageId",
13
+ "status",
14
+ "subject",
15
+ "to",
16
+ "userId",
17
+ ] as const;
18
+
19
+ describe("CommsMessage", () => {
20
+ beforeEach(async (): Promise<void> => {
21
+ await setupDb();
22
+ await CommsMessage.deleteMany({});
23
+ });
24
+
25
+ it("records a communication send with documented schema fields", async (): Promise<void> => {
26
+ const message = await CommsMessage.logSend({
27
+ channel: "mail",
28
+ provider: "console",
29
+ status: "sent",
30
+ subject: "Welcome",
31
+ to: "person@example.com",
32
+ });
33
+
34
+ assert.isNotNull(message);
35
+ assert.equal(message?.channel, "mail");
36
+ assert.equal(await CommsMessage.countDocuments(), 1);
37
+ for (const field of COMMS_MESSAGE_FIELDS) {
38
+ assert.isString(CommsMessage.schema.path(field).options.description);
39
+ }
40
+ });
41
+
42
+ it("returns null instead of throwing when logging fails", async (): Promise<void> => {
43
+ const result = await CommsMessage.logSend({
44
+ channel: "mail",
45
+ provider: "",
46
+ status: "sent",
47
+ to: "person@example.com",
48
+ });
49
+
50
+ assert.isNull(result);
51
+ assert.equal(await CommsMessage.countDocuments(), 0);
52
+ });
53
+ });
@@ -0,0 +1,97 @@
1
+ import {
2
+ createdUpdatedPlugin,
3
+ findExactlyOne,
4
+ findOneOrNone,
5
+ isDeletedPlugin,
6
+ logger,
7
+ } from "@terreno/api";
8
+ import mongoose from "mongoose";
9
+
10
+ import type {
11
+ CommsMessageDocument,
12
+ CommsMessageModel,
13
+ CommsMessageSchema,
14
+ LogSendParams,
15
+ } from "../modelTypes";
16
+
17
+ const commsMessageSchema: CommsMessageSchema = new mongoose.Schema<
18
+ CommsMessageDocument,
19
+ CommsMessageModel
20
+ >(
21
+ {
22
+ channel: {
23
+ description: "Communication channel used for the send attempt",
24
+ enum: ["mail", "push", "sms", "verification"],
25
+ required: true,
26
+ type: String,
27
+ },
28
+ error: {
29
+ description: "Provider error returned for a failed send attempt",
30
+ type: String,
31
+ },
32
+ metadata: {
33
+ description: "Additional metadata associated with the send attempt",
34
+ type: mongoose.Schema.Types.Mixed,
35
+ },
36
+ provider: {
37
+ description: "Identifier of the provider handling the send attempt",
38
+ minlength: 1,
39
+ required: true,
40
+ type: String,
41
+ },
42
+ providerMessageId: {
43
+ description: "Provider-assigned identifier for delivery tracking",
44
+ index: true,
45
+ type: String,
46
+ },
47
+ status: {
48
+ description: "Current delivery status of the communication",
49
+ enum: ["bounced", "delivered", "failed", "sent"],
50
+ required: true,
51
+ type: String,
52
+ },
53
+ subject: {
54
+ description: "Mail subject when the communication channel is mail",
55
+ type: String,
56
+ },
57
+ to: {
58
+ description: "Recipient identifier for the communication",
59
+ required: true,
60
+ type: String,
61
+ },
62
+ userId: {
63
+ description: "User associated with the communication",
64
+ ref: "User",
65
+ type: mongoose.Schema.Types.ObjectId,
66
+ },
67
+ },
68
+ {strict: "throw", toJSON: {virtuals: true}, toObject: {virtuals: true}}
69
+ );
70
+
71
+ commsMessageSchema.statics = {
72
+ async logSend(
73
+ this: CommsMessageModel,
74
+ params: LogSendParams
75
+ ): Promise<CommsMessageDocument | null> {
76
+ try {
77
+ return await this.create(params);
78
+ } catch {
79
+ logger.warn("[comms] Failed to record communication send");
80
+ return null;
81
+ }
82
+ },
83
+ };
84
+
85
+ commsMessageSchema.plugin(createdUpdatedPlugin);
86
+ commsMessageSchema.plugin(isDeletedPlugin);
87
+ commsMessageSchema.plugin(findOneOrNone);
88
+ commsMessageSchema.plugin(findExactlyOne);
89
+
90
+ commsMessageSchema.index({channel: 1, created: -1});
91
+ commsMessageSchema.index({created: -1, status: 1});
92
+ commsMessageSchema.index({created: -1, userId: 1});
93
+
94
+ export const CommsMessage = mongoose.model<CommsMessageDocument, CommsMessageModel>(
95
+ "CommsMessage",
96
+ commsMessageSchema
97
+ );
@@ -0,0 +1,45 @@
1
+ import {beforeEach, describe, it} from "bun:test";
2
+ import {setupDb} from "@terreno/api/testing";
3
+ import {assert} from "chai";
4
+ import {DateTime} from "luxon";
5
+ import mongoose from "mongoose";
6
+
7
+ import {PushToken} from "./pushToken";
8
+
9
+ describe("PushToken", () => {
10
+ beforeEach(async (): Promise<void> => {
11
+ await setupDb();
12
+ await PushToken.deleteMany({});
13
+ });
14
+
15
+ it("updates an existing token instead of creating a duplicate", async (): Promise<void> => {
16
+ const firstUserId = new mongoose.Types.ObjectId();
17
+ const secondUserId = new mongoose.Types.ObjectId();
18
+ const firstSeenAt = DateTime.utc().minus({minutes: 1}).toJSDate();
19
+ const secondSeenAt = DateTime.utc().toJSDate();
20
+
21
+ await PushToken.upsert(
22
+ {token: "ExponentPushToken[test]"},
23
+ {
24
+ active: true,
25
+ lastSeenAt: firstSeenAt,
26
+ platform: "ios",
27
+ userId: firstUserId,
28
+ }
29
+ );
30
+ const updated = await PushToken.upsert(
31
+ {token: "ExponentPushToken[test]"},
32
+ {
33
+ active: true,
34
+ lastSeenAt: secondSeenAt,
35
+ platform: "android",
36
+ userId: secondUserId,
37
+ }
38
+ );
39
+
40
+ assert.equal(await PushToken.countDocuments(), 1);
41
+ assert.equal(updated.platform, "android");
42
+ assert.equal(updated.userId.toString(), secondUserId.toString());
43
+ assert.equal(updated.lastSeenAt.toISOString(), secondSeenAt.toISOString());
44
+ });
45
+ });
@@ -0,0 +1,69 @@
1
+ import {
2
+ createdUpdatedPlugin,
3
+ findExactlyOne,
4
+ findOneOrNone,
5
+ isDeletedPlugin,
6
+ upsertPlugin,
7
+ } from "@terreno/api";
8
+ import {DateTime} from "luxon";
9
+ import mongoose from "mongoose";
10
+
11
+ import type {PushTokenDocument, PushTokenModel, PushTokenSchema} from "../modelTypes";
12
+
13
+ const pushTokenSchema: PushTokenSchema = new mongoose.Schema<PushTokenDocument, PushTokenModel>(
14
+ {
15
+ active: {
16
+ default: true,
17
+ description: "Whether the device token is available for push delivery",
18
+ type: Boolean,
19
+ },
20
+ deviceId: {
21
+ description: "Application-provided identifier for the device",
22
+ type: String,
23
+ },
24
+ lastSeenAt: {
25
+ default: (): Date => DateTime.utc().toJSDate(),
26
+ description: "Most recent time the device token was registered",
27
+ required: true,
28
+ type: Date,
29
+ },
30
+ platform: {
31
+ description: "Platform associated with the device token",
32
+ enum: ["android", "ios", "web"],
33
+ required: true,
34
+ type: String,
35
+ },
36
+ token: {
37
+ description: "Push provider token identifying the device",
38
+ minlength: 1,
39
+ required: true,
40
+ type: String,
41
+ unique: true,
42
+ },
43
+ userId: {
44
+ description: "User who owns the device token",
45
+ index: true,
46
+ ref: "User",
47
+ required: true,
48
+ type: mongoose.Schema.Types.ObjectId,
49
+ },
50
+ },
51
+ {strict: "throw", toJSON: {virtuals: true}, toObject: {virtuals: true}}
52
+ );
53
+
54
+ pushTokenSchema.virtual("ownerId").get(function (this: PushTokenDocument): mongoose.Types.ObjectId {
55
+ return this.userId;
56
+ });
57
+
58
+ pushTokenSchema.plugin(createdUpdatedPlugin);
59
+ pushTokenSchema.plugin(isDeletedPlugin);
60
+ pushTokenSchema.plugin(findOneOrNone);
61
+ pushTokenSchema.plugin(findExactlyOne);
62
+ pushTokenSchema.plugin(upsertPlugin);
63
+
64
+ pushTokenSchema.index({active: 1, userId: 1});
65
+
66
+ export const PushToken = mongoose.model<PushTokenDocument, PushTokenModel>(
67
+ "PushToken",
68
+ pushTokenSchema
69
+ );