1
0
mirror of https://gitlab.com/comunic/comunicapiv2 synced 2024-11-25 06:49:23 +00:00

Create internal custom event manager

This commit is contained in:
Pierre HUBERT 2020-03-30 14:20:33 +02:00
parent 4bfcb9b35b
commit 4901e9d3ef
2 changed files with 77 additions and 0 deletions

View File

@ -18,6 +18,7 @@ import { GroupsHelper } from "./GroupsHelper";
import { NotificationsHelper } from "./NotificationsHelper"; import { NotificationsHelper } from "./NotificationsHelper";
import { AccountImageHelper } from "./AccountImageHelper"; import { AccountImageHelper } from "./AccountImageHelper";
import { BackgroundImageHelper } from "./BackgroundImageHelper"; import { BackgroundImageHelper } from "./BackgroundImageHelper";
import { EventsHelper } from "./EventsHelper";
/** /**
* Account helper * Account helper
@ -147,6 +148,13 @@ export class AccountHelper {
* @param userID Target user ID * @param userID Target user ID
*/ */
public static async DestroyUserTokens(client: APIClient, userID: number) { 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, { return DatabaseHelper.DeleteRows(USERS_TOKENS_TABLE, {
service_id: client.id, service_id: client.id,
user_id: userID user_id: userID

View File

@ -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<keyof EventsMap, Array<(ev: any) => void | Promise<void>>> = new Map()
/**
* Listen to a new event
*
* @param name The name of the event to listen to
* @param listener Target listener
*/
public static Listen<K extends keyof EventsMap>(name: K, listener: (ev: EventsMap[K]) => void | Promise<void>) {
if(!this.EventsList[<any>name])
this.EventsList[<any>(name)] = [];
this.EventsList[<any>(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<K extends keyof EventsMap>(name: K, args: EventsMap[K]) {
if(!this.EventsList[<any>name])
return;
for(const entry of this.EventsList[<any>name]) {
try {
await entry(args);
}
catch(e) {
console.error("An error occured while propagating an event ("+name+")!", e, args);
}
}
}
}