Skip to content

Instantly share code, notes, and snippets.

@antonkalik
Last active March 10, 2024 10:58
Show Gist options
  • Save antonkalik/f78793066fe3bae1c6287f3c8529fb94 to your computer and use it in GitHub Desktop.
Save antonkalik/f78793066fe3bae1c6287f3c8529fb94 to your computer and use it in GitHub Desktop.
Token Service WIth Initialization
require('dotenv').config();
import jsonwebtoken from 'jsonwebtoken';
export class TokenService {
private static jwt_secret: string = process.env.JWT_SECRET!;
static initialize = () => {
if (!this.jwt_secret) {
throw new Error('JWT secret not found in environment variables!');
}
this.jwt_secret = process.env.JWT_SECRET!;
};
public static verify = <Result>(token: string): Promise<Result> =>
new Promise((resolve, reject) => {
jsonwebtoken.verify(token, TokenService.jwt_secret, (error, decoded) => {
if (error) {
reject(error);
} else {
resolve(decoded as Result);
}
});
});
public static sign = (payload: string | object | Buffer): Promise<string> =>
new Promise((resolve, reject) => {
try {
resolve(jsonwebtoken.sign(payload, TokenService.jwt_secret));
} catch (error) {
reject(error);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment