shellphone.app/app/core/mutations/set-notification-subscription.ts

56 lines
1.4 KiB
TypeScript
Raw Normal View History

2021-08-01 16:28:47 +00:00
import { resolver } from "blitz";
import { z } from "zod";
import db from "../../../db";
import appLogger from "../../../integrations/logger";
2021-08-05 17:07:15 +00:00
import { enforceSuperAdminIfNotCurrentOrganization, setDefaultOrganizationId } from "../utils";
2021-08-01 16:28:47 +00:00
const logger = appLogger.child({ mutation: "set-notification-subscription" });
const Body = z.object({
2021-08-05 17:07:15 +00:00
organizationId: z.string().optional(),
phoneNumberId: z.string(),
2021-08-01 16:28:47 +00:00
subscription: z.object({
endpoint: z.string(),
expirationTime: z.number().nullable(),
keys: z.object({
p256dh: z.string(),
auth: z.string(),
}),
}),
});
2021-08-05 17:07:15 +00:00
export default resolver.pipe(
resolver.zod(Body),
resolver.authorize(),
setDefaultOrganizationId,
enforceSuperAdminIfNotCurrentOrganization,
async ({ organizationId, phoneNumberId, subscription }) => {
const phoneNumber = await db.phoneNumber.findFirst({
where: { id: phoneNumberId, organizationId },
include: { organization: true },
2021-08-01 16:28:47 +00:00
});
2021-08-05 17:07:15 +00:00
if (!phoneNumber) {
return;
2021-08-01 16:28:47 +00:00
}
2021-08-05 17:07:15 +00:00
try {
await db.notificationSubscription.create({
data: {
organizationId,
phoneNumberId,
endpoint: subscription.endpoint,
expirationTime: subscription.expirationTime,
keys_p256dh: subscription.keys.p256dh,
keys_auth: subscription.keys.auth,
},
});
} catch (error) {
if (error.code !== "P2002") {
logger.error(error);
// we might want to `throw error`;
}
}
},
);