How to provide middleware
How to provide middleware
- HttpApi endpoints
- HttpApi groups
PS: The README talks about the router https://github.com/Effect-TS/effect/blob/main/packages/platform/README.md#applying-middleware-in-your-application, not about Http Api.
HttpMiddleware.make()HttpMiddleware.make() to:- HttpApi endpoints
- HttpApi groups
PS: The README talks about the router https://github.com/Effect-TS/effect/blob/main/packages/platform/README.md#applying-middleware-in-your-application, not about Http Api.
Auth Middleware
export const withAuthMiddleware = HttpMiddleware.make(app =>
Effect.gen(function* () {
const request = yield* ServerRequest.HttpServerRequest
...
if (session) {
const userId = session?.getUserId()
return yield* app.pipe(
Effect.provideService(CurrentUser, { id: userId }),
)
}
return yield* new Unauthorized()
} catch (err) {
// Docs: https://github.com/supertokens/supertokens-node/blob/7e33a06f4283a150600a5eabda31615fc5827023/lib/ts/recipe/session/error.ts
if (SupertokensSession.Error.isErrorFromSuperTokens(err)) {
switch (err.type) {
case SupertokensSession.Error.TRY_REFRESH_TOKEN:
case SupertokensSession.Error.UNAUTHORISED:
return yield* new Unauthorized()
case SupertokensSession.Error.INVALID_CLAIMS:
return yield* new Forbidden()
...
default:
throw err
}
}
throw err
}
}),
)export const withAuthMiddleware = HttpMiddleware.make(app =>
Effect.gen(function* () {
const request = yield* ServerRequest.HttpServerRequest
...
if (session) {
const userId = session?.getUserId()
return yield* app.pipe(
Effect.provideService(CurrentUser, { id: userId }),
)
}
return yield* new Unauthorized()
} catch (err) {
// Docs: https://github.com/supertokens/supertokens-node/blob/7e33a06f4283a150600a5eabda31615fc5827023/lib/ts/recipe/session/error.ts
if (SupertokensSession.Error.isErrorFromSuperTokens(err)) {
switch (err.type) {
case SupertokensSession.Error.TRY_REFRESH_TOKEN:
case SupertokensSession.Error.UNAUTHORISED:
return yield* new Unauthorized()
case SupertokensSession.Error.INVALID_CLAIMS:
return yield* new Forbidden()
...
default:
throw err
}
}
throw err
}
}),
)