Last active
March 10, 2024 10:58
-
-
Save antonkalik/f78793066fe3bae1c6287f3c8529fb94 to your computer and use it in GitHub Desktop.
Token Service WIth Initialization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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