From 4901e9d3efad113056f6b16a71b537a64125bf99 Mon Sep 17 00:00:00 2001 From: Pierre HUBERT Date: Mon, 30 Mar 2020 14:20:33 +0200 Subject: [PATCH] Create internal custom event manager --- src/helpers/AccountHelper.ts | 8 +++++ src/helpers/EventsHelper.ts | 69 ++++++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 src/helpers/EventsHelper.ts diff --git a/src/helpers/AccountHelper.ts b/src/helpers/AccountHelper.ts index 3c07ce0..06cd159 100644 --- a/src/helpers/AccountHelper.ts +++ b/src/helpers/AccountHelper.ts @@ -18,6 +18,7 @@ import { GroupsHelper } from "./GroupsHelper"; import { NotificationsHelper } from "./NotificationsHelper"; import { AccountImageHelper } from "./AccountImageHelper"; import { BackgroundImageHelper } from "./BackgroundImageHelper"; +import { EventsHelper } from "./EventsHelper"; /** * Account helper @@ -147,6 +148,13 @@ export class AccountHelper { * @param userID Target user ID */ public static async DestroyUserTokens(client: APIClient, userID: number) { + + // Push the event + EventsHelper.Emit("destroyed_login_tokens", { + client: client, + userID: userID + }); + return DatabaseHelper.DeleteRows(USERS_TOKENS_TABLE, { service_id: client.id, user_id: userID diff --git a/src/helpers/EventsHelper.ts b/src/helpers/EventsHelper.ts new file mode 100644 index 0000000..528ceb0 --- /dev/null +++ b/src/helpers/EventsHelper.ts @@ -0,0 +1,69 @@ +import { EventEmitter } from "events"; +import { APIClient } from "../entities/APIClient"; + +/** + * Events manager + * + * @author Pierre Hubert + */ + +// When a user sign out +export interface DestroyedLoginTokensEvent { + userID: number, + client: APIClient +} + +/** + * Global map of all possible events + */ +export interface EventsMap { + "destroyed_login_tokens": DestroyedLoginTokensEvent +} + +export class EventsHelper { + + /** + * The list of events + */ + private static EventsList: Map void | Promise>> = new Map() + + /** + * Listen to a new event + * + * @param name The name of the event to listen to + * @param listener Target listener + */ + public static Listen(name: K, listener: (ev: EventsMap[K]) => void | Promise) { + if(!this.EventsList[name]) + this.EventsList[(name)] = []; + + this.EventsList[(name)].push(listener); + + } + + /** + * Push a new event + * + * Note : It is not mandatory to listen to this method, as + * we will try / catch all the events + * + * @param name The name of the event + * @param args Argumens to pass to the event + */ + public static async Emit(name: K, args: EventsMap[K]) { + + if(!this.EventsList[name]) + return; + + for(const entry of this.EventsList[name]) { + try { + await entry(args); + } + catch(e) { + console.error("An error occured while propagating an event ("+name+")!", e, args); + } + } + } + + +} \ No newline at end of file