Read vapid details from runtime config
Use the useRuntimeConfig interface to read vapid details on the server side. This is a more portale way to deal with loading data from the environment in Nuxt.js.
This commit is contained in:
parent
742be649eb
commit
c986d939ec
3 changed files with 27 additions and 8 deletions
|
@ -27,5 +27,5 @@ export default defineEventHandler(async (event) => {
|
|||
});
|
||||
await broadcastUpdate(schedule);
|
||||
await writeSchedule(schedule);
|
||||
await sendPush("New event", `${name} will start at ${start}`);
|
||||
await sendPush(event, "New event", `${name} will start at ${start}`);
|
||||
});
|
||||
|
|
|
@ -33,5 +33,5 @@ export default defineEventHandler(async (event) => {
|
|||
await broadcastUpdate(schedule);
|
||||
await writeSchedule(schedule);
|
||||
if (timeChanged)
|
||||
await sendPush(`New time for ${name}`, `${name} will now start at ${start}`);
|
||||
await sendPush(event, `New time for ${name}`, `${name} will now start at ${start}`);
|
||||
});
|
||||
|
|
|
@ -1,13 +1,31 @@
|
|||
import type { H3Event } from "h3";
|
||||
import webPush from "web-push";
|
||||
import { readSubscriptions, writeSubscriptions } from "~/server/database";
|
||||
|
||||
webPush.setVapidDetails(
|
||||
"mailto:webmaster@hornwitser.no",
|
||||
process.env.NUXT_PUBLIC_VAPID_PUBLIC_KEY!,
|
||||
process.env.NUXT_VAPID_PRIVATE_KEY!,
|
||||
)
|
||||
let cachedVapidDetails: {
|
||||
subject: string,
|
||||
publicKey: string,
|
||||
privateKey: string,
|
||||
} | undefined;
|
||||
|
||||
export async function sendPush(title: string, body: string) {
|
||||
function useVapidDetails(event: H3Event) {
|
||||
if (cachedVapidDetails) {
|
||||
return cachedVapidDetails;
|
||||
}
|
||||
|
||||
const runtimeConfig = useRuntimeConfig(event);
|
||||
if (!runtimeConfig.public.vapidPublicKey) throw new Error("NUXT_PUBLIC_VAPID_PUBLIC_KEY not set.")
|
||||
if (!runtimeConfig.vapidPrivateKey) throw new Error("NUXT_VAPID_PRIVATE_KEY not set.")
|
||||
|
||||
return cachedVapidDetails = {
|
||||
subject: "mailto:webmaster@hornwitser.no",
|
||||
publicKey: runtimeConfig.public.vapidPublicKey,
|
||||
privateKey: runtimeConfig.vapidPrivateKey,
|
||||
}
|
||||
}
|
||||
|
||||
export async function sendPush(event: H3Event, title: string, body: string) {
|
||||
const vapidDetails = useVapidDetails(event);
|
||||
const payload = JSON.stringify({ title, body });
|
||||
const subscriptions = await readSubscriptions();
|
||||
console.log(`Sending "${payload}" to ${subscriptions.length} subscribers`);
|
||||
|
@ -23,6 +41,7 @@ export async function sendPush(title: string, body: string) {
|
|||
{
|
||||
TTL: 3600,
|
||||
urgency: "high",
|
||||
vapidDetails,
|
||||
}
|
||||
)
|
||||
} catch (err: any) {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue