Skip to content

Instantly share code, notes, and snippets.

@Teebo
Last active November 5, 2022 16:16
Show Gist options
  • Save Teebo/0ed4cec8386962662a1c557f411efcd6 to your computer and use it in GitHub Desktop.
Save Teebo/0ed4cec8386962662a1c557f411efcd6 to your computer and use it in GitHub Desktop.
Singleton pattern
export interface ISession {
username: string;
token: string;
}
/**
* Session class
*/
export class Session implements ISession {
private static instance: Session;
public username: string;
public _token: string;
private constructor(session: ISession) {
this.username = session.username;
this._token = session.token;
}
set token(token: string) {
this._token = token;
}
get token(): string {
return this._token;
}
/**
*
* @param session An object of type ISession
* @returns A session instance
*/
static createSession(session: ISession): Session {
if(this.instance) {
console.error(`You tried to create another session instance...returning the existing one..\n`);
return this.instance;
}
this.instance = new Session(session);
return this.instance;
}
}
// Create a session instance
const session = Session.createSession({token: 'jwt', username: 'User1'});
// Create another session instance
const session2 = Session.createSession({token: 'jwt2', username: 'User2'}); // Cannot instantiate another session.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment