shellphone.app/app/messages/api/queue/notify-incoming-message.ts

62 lines
2.0 KiB
TypeScript
Raw Normal View History

2021-08-01 16:28:47 +00:00
import { getConfig } from "blitz";
import { Queue } from "quirrel/blitz";
import type { MessageInstance } from "twilio/lib/rest/api/v2010/account/message";
import webpush, { PushSubscription, WebPushError } from "web-push";
import db from "../../../../db";
import appLogger from "../../../../integrations/logger";
import getTwilioClient from "../../../../integrations/twilio";
2021-08-01 16:28:47 +00:00
const { serverRuntimeConfig, publicRuntimeConfig } = getConfig();
const logger = appLogger.child({ queue: "notify-incoming-message" });
type Payload = {
2021-08-05 17:07:15 +00:00
organizationId: string;
phoneNumberId: string;
2021-08-01 16:28:47 +00:00
messageSid: MessageInstance["sid"];
};
const notifyIncomingMessageQueue = Queue<Payload>(
"api/queue/notify-incoming-message",
2021-08-05 17:07:15 +00:00
async ({ messageSid, organizationId, phoneNumberId }) => {
2021-08-01 16:28:47 +00:00
webpush.setVapidDetails(
"mailto:mokht@rmi.al",
publicRuntimeConfig.webPush.publicKey,
serverRuntimeConfig.webPush.privateKey,
);
2021-08-05 17:07:15 +00:00
const organization = await db.organization.findFirst({
where: { id: organizationId },
});
const twilioClient = getTwilioClient(organization);
const message = await twilioClient.messages.get(messageSid).fetch();
2021-08-01 16:28:47 +00:00
const notification = { message: `${message.from} - ${message.body}` };
const subscriptions = await db.notificationSubscription.findMany({
where: { organizationId, phoneNumberId },
});
2021-08-01 16:28:47 +00:00
await Promise.all(
subscriptions.map(async (subscription) => {
const webPushSubscription: PushSubscription = {
endpoint: subscription.endpoint,
keys: {
p256dh: subscription.keys_p256dh,
auth: subscription.keys_auth,
},
};
try {
await webpush.sendNotification(webPushSubscription, JSON.stringify(notification));
} catch (error) {
logger.error(error);
if (error instanceof WebPushError) {
// subscription most likely expired or has been revoked
2021-08-01 16:28:47 +00:00
await db.notificationSubscription.delete({ where: { id: subscription.id } });
}
}
}),
);
},
);
export default notifyIncomingMessageQueue;