JWT refactoring
All checks were successful
Lint / lint (push) Successful in 12s
Test build / test-build (pull_request) Successful in 17s

This commit is contained in:
Julien Valverdé
2024-09-04 01:00:37 +02:00
parent b673acc2ec
commit 55f7d63cca

View File

@@ -1,12 +1,12 @@
import { Context, Effect, Layer } from "effect"
import jwt from "jsonwebtoken"
import type * as JWT from "jsonwebtoken"
export class JSONWebToken extends Context.Tag("JSONWebToken")<JSONWebToken, {
sign: (
payload: string | object | Buffer,
secretOrPrivateKey: jwt.Secret,
options: jwt.SignOptions,
secretOrPrivateKey: JWT.Secret,
options: JWT.SignOptions,
) => Effect.Effect<
string,
Error,
@@ -15,17 +15,23 @@ export class JSONWebToken extends Context.Tag("JSONWebToken")<JSONWebToken, {
verify: (
token: string,
secretOrPublicKey: jwt.Secret,
options: jwt.VerifyOptions,
secretOrPublicKey: JWT.Secret,
options: JWT.VerifyOptions,
) => Effect.Effect<
string | jwt.Jwt | jwt.JwtPayload,
jwt.VerifyErrors | Error,
string | JWT.Jwt | JWT.JwtPayload,
JWT.VerifyErrors | Error,
never
>,
}>() {}
export const JSONWebTokenLive = Layer.succeed(JSONWebToken, {
const importJWT = Effect.tryPromise({
try: () => import("jsonwebtoken"),
catch: cause => new Error("Could not import 'jsonwebtoken'. Make sure it is installed.", { cause }),
})
export const JSONWebTokenLive = Layer.effect(JSONWebToken, importJWT.pipe(
Effect.map(jwt => JSONWebToken.of({
sign: (payload, secretOrPrivateKey, options) => Effect.async(resume =>
jwt.sign(payload, secretOrPrivateKey, options, (err, token) => {
resume(token
@@ -43,4 +49,5 @@ export const JSONWebTokenLive = Layer.succeed(JSONWebToken, {
)
})
),
})
}))
))