Skip to content

Instantly share code, notes, and snippets.

@alii
Created January 19, 2021 13:31
Show Gist options
  • Save alii/575b9c30961cf1aab15a33d8e38d9803 to your computer and use it in GitHub Desktop.
Save alii/575b9c30961cf1aab15a33d8e38d9803 to your computer and use it in GitHub Desktop.
Notification permissions system with Permer
import { Permer } from "permer";
const permer = new Permer(["web", "email"]);
type NotificationSettings = {
user_id: number;
review_comment: number;
user_likes_review: number;
user_comment_review: number;
user_like_list: number;
user_follow: number;
};
type EventName = keyof Omit<NotificationSettings, "user_id">;
type User = {
id: number;
username: string;
email: string;
password: string;
};
const users: User[] = [
{
id: 1,
email: "alistair@edge.gg",
username: "alistair",
password: "pwd1234secure",
},
{
id: 2,
email: "benja@edge.gg",
username: "benja",
password: "1234568re8ysdfh",
},
];
const table: NotificationSettings[] = [
{
user_id: users[0].id,
review_comment: permer.toPermissionsInteger(["email", "web"]),
user_likes_review: permer.toPermissionsInteger(["web"]),
user_comment_review: permer.toPermissionsInteger(["email", "web"]),
user_like_list: permer.toPermissionsInteger([]),
user_follow: permer.toPermissionsInteger(["email"]),
},
{
user_id: users[1].id,
review_comment: permer.toPermissionsInteger(["web"]),
user_likes_review: permer.toPermissionsInteger(["email"]),
user_comment_review: permer.toPermissionsInteger(["email"]),
user_like_list: permer.toPermissionsInteger(["web", "email"]),
user_follow: permer.toPermissionsInteger(["web"]),
},
];
export const notificationManager = new (class NotificationEmitter {
sendWebNotification(user: User) {
console.log("Sending a web notif to", user.email);
}
sendEmailNotification(user: User) {
console.log("Sending an email to", user.email);
}
sendEvent(event_name: EventName) {
for (const user of users) {
const settings = table.find((row) => {
return row.user_id === user.id;
});
const transports = permer.toPermissionList(settings[event_name]);
for (const transport of transports) {
switch (transport) {
case "web":
this.sendWebNotification(user);
break;
case "email":
this.sendEmailNotification(user);
break;
}
}
}
}
})();
notificationManager.sendEvent("user_follow");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment