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 { Context, Effect, Layer } from "effect"
import jwt from "jsonwebtoken" import type * as JWT from "jsonwebtoken"
export class JSONWebToken extends Context.Tag("JSONWebToken")<JSONWebToken, { export class JSONWebToken extends Context.Tag("JSONWebToken")<JSONWebToken, {
sign: ( sign: (
payload: string | object | Buffer, payload: string | object | Buffer,
secretOrPrivateKey: jwt.Secret, secretOrPrivateKey: JWT.Secret,
options: jwt.SignOptions, options: JWT.SignOptions,
) => Effect.Effect< ) => Effect.Effect<
string, string,
Error, Error,
@@ -15,17 +15,23 @@ export class JSONWebToken extends Context.Tag("JSONWebToken")<JSONWebToken, {
verify: ( verify: (
token: string, token: string,
secretOrPublicKey: jwt.Secret, secretOrPublicKey: JWT.Secret,
options: jwt.VerifyOptions, options: JWT.VerifyOptions,
) => Effect.Effect< ) => Effect.Effect<
string | jwt.Jwt | jwt.JwtPayload, string | JWT.Jwt | JWT.JwtPayload,
jwt.VerifyErrors | Error, JWT.VerifyErrors | Error,
never 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 => sign: (payload, secretOrPrivateKey, options) => Effect.async(resume =>
jwt.sign(payload, secretOrPrivateKey, options, (err, token) => { jwt.sign(payload, secretOrPrivateKey, options, (err, token) => {
resume(token resume(token
@@ -43,4 +49,5 @@ export const JSONWebTokenLive = Layer.succeed(JSONWebToken, {
) )
}) })
), ),
}) }))
))