Skip to content

Commit

Permalink
Merge pull request #164 from dvishal485/main
Browse files Browse the repository at this point in the history
update notif worker
  • Loading branch information
dvishal485 authored Aug 26, 2024
2 parents 968a546 + 324ca15 commit 8bb8f54
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 68 deletions.
40 changes: 37 additions & 3 deletions public/notification-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ function urlB64ToUint8Array(base64String) {
service_worker.addEventListener("activate", async () => {
console.log("Hello from service worker");
try {
/** @type {PushSubscriptionOptionsInit} */
/** @type {PushSubscriptionOptions} */
const options = {
applicationServerKey:
"BCOsRaxpJeR0KyIPIg1rHx3pUtWVsGDGOxH65dDkqyU5ycF-CjPJxuqiXF4M0LpUMG_rk_YxSZX34uHbrV5umJQ",
Expand All @@ -30,9 +30,43 @@ service_worker.addEventListener("activate", async () => {
const subscription =
await service_worker.registration.pushManager.subscribe(options);

console.log("Subscription", subscription);
console.log(JSON.stringify(subscription));
let subscribe_json = subscription.toJSON();
console.log("Subscription", subscribe_json);

const body = JSON.stringify(subscribe_json);

await fetch("https://team-dev.dtutimes.com/api/v1/notification/subscribe", {
method: "POST",
body,
headers: {
"Content-Type": "application/json",
},
})
.then((res) => res.text())
.then(console.log)
.catch(console.error);
} catch (err) {
console.log("Error", err);
}
});

service_worker.addEventListener("push", function (event) {
if (event.data) {
console.log(event.data.text());
pushNotification("Hi", event.data.text(), service_worker.registration);
} else {
console.log("No data!");
}
});

/**
* @param title {string}
* @param body {string}
* @param swRegistration {ServiceWorkerRegistration}
*/
const pushNotification = (title, body, swRegistration) => {
const options = {
body,
};
swRegistration.showNotification(title, options);
};
48 changes: 19 additions & 29 deletions src/pages/Notification/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@ import { ErrorContext } from "@/contexts/error";
import API from "@/services/API";
import { INotification } from "@/types/notification";
import React, { useEffect, useState } from "react";
import { Notification, BgService } from "./notification-engine";
import {
setup_notification,
disable_notification,
setup_present,
} from "./notification-engine";

interface NotificationCardProps {
notif: INotification;
Expand Down Expand Up @@ -57,8 +61,11 @@ export default function NotificationPage() {
const { setError } = React.useContext(ErrorContext);

const [notifications, setNotifs] = useState<INotification[]>(null);
const [status, setStatus] = useState<boolean>(false);

useEffect(() => {
setup_present().then(setStatus);

const notifications = "/notification";
API.get(notifications)
.then((response) => {
Expand All @@ -80,34 +87,17 @@ export default function NotificationPage() {
return (
<div className="max-w-4xl mx-auto py-12">
<h1>Latest Updates</h1>
<button onClick={Notification.requestPermission}>
Get alerts on Notification!
</button>
<button
onClick={async () => {
console.log("Registering service!");
const x = await BgService.registerServiceWorker(
"https://team-dev.dtutimes.com/notification-service.js",
);
console.log("Service worker registered", x);
}}
>
Register service worker
</button>
<button
onClick={async () => {
console.log("services: ", await BgService.getRegistration());
}}
>
Console log bg services
</button>
<button
onClick={async () => {
console.log("services: ", await BgService.unregisterServiceWorker());
}}
>
Console log bg services
</button>
<div>
{status ? (
<button className="ml-2" onClick={disable_notification}>
Disable Notifications
</button>
) : (
<button className="mr-2" onClick={setup_notification}>
Get alerts on Notification!
</button>
)}
</div>
{notifications.map((notif) => {
return <NotificationCard key={notif._id} notif={notif} />;
})}
Expand Down
56 changes: 25 additions & 31 deletions src/pages/Notification/notification-engine.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,6 @@
export class Notification {
class Notification {
static notify = window.Notification;

public static isPermissionGranted() {
if (!Notification.isSupported()) {
throw new Error("Notification API is not supported");
}
return Notification.notify.permission === "granted";
}

public static async requestPermission() {
if (!Notification.isSupported()) {
throw new Error("Notification API is not supported");
Expand All @@ -17,31 +10,12 @@ export class Notification {
return permission;
}

public static constructNotification(
title: string,
options: NotificationOptions,
) {
return new Notification.notify(title, options);
}

public static isSupported() {
return Notification.notify !== undefined;
}

public static async displayNotification(
title: string,
options: NotificationOptions,
) {
const permission = await Notification.requestPermission();
if (permission === "granted") {
Notification.constructNotification(title, options);
} else {
console.error("Permission denied");
}
}
}

export class BgService {
class BgService {
static bg = window.navigator;

public static isSupported() {
Expand All @@ -55,13 +29,33 @@ export class BgService {
}

public static async unregisterServiceWorker() {
const registrations = await BgService.bg.serviceWorker.getRegistrations();
const registrations = await BgService.getRegistrations();
registrations.forEach((registration) => registration.unregister());
return registrations;
}

public static async getRegistration() {
const registration = await BgService.bg.serviceWorker.getRegistration();
public static async getRegistrations() {
const registration = await BgService.bg.serviceWorker.getRegistrations();
console.log("Service worker registered", registration);
return registration;
}
}

export async function setup_notification() {
Notification.requestPermission();

const worker = await BgService.registerServiceWorker(
"https://team-dev.dtutimes.com/notification-service.js",
);

console.log("Service worker registered", worker);
}

export async function disable_notification() {
await BgService.unregisterServiceWorker();
}

export async function setup_present() {
const services = await BgService.getRegistrations();
return services.length > 0;
}
10 changes: 5 additions & 5 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ export default defineConfig({
},
},
esbuild: {
// drop:
// process.env.NODE_ENV == "production"
// ? ["console", "debugger"]
// : undefined,
// pure: ["console.error"],
drop:
process.env.NODE_ENV == "production"
? ["console", "debugger"]
: undefined,
pure: ["console.error"],
},
build: {
rollupOptions: {
Expand Down

0 comments on commit 8bb8f54

Please sign in to comment.