|
| 1 | +import { isDefined } from "@lite-app/shared/is-defined"; |
1 | 2 | import { createAuthClient } from "better-auth/client"; |
2 | 3 | import { adminClient, organizationClient } from "better-auth/client/plugins"; |
3 | 4 |
|
| 5 | +import { AuthClientFetchError, AuthError } from "~/lib/auth/error"; |
| 6 | + |
4 | 7 | export const authClient = createAuthClient({ |
5 | 8 | plugins: [adminClient(), organizationClient()], |
6 | 9 | }); |
7 | | -export const { organization } = authClient; |
| 10 | + |
| 11 | +async function unwrapAuthClientResult<T>({ |
| 12 | + operation, |
| 13 | + promise, |
| 14 | +}: { |
| 15 | + operation: string; |
| 16 | + promise: Promise<{ data: T; error: unknown }>; |
| 17 | +}) { |
| 18 | + const result = await promise.catch( |
| 19 | + (error) => |
| 20 | + new AuthClientFetchError({ |
| 21 | + operation, |
| 22 | + cause: error, |
| 23 | + }) |
| 24 | + ); |
| 25 | + if (result instanceof Error) { |
| 26 | + return result; |
| 27 | + } |
| 28 | + const { data, error } = result; |
| 29 | + const success = isDefined(data) && !isDefined(error); |
| 30 | + if (!success) { |
| 31 | + return new AuthError({ |
| 32 | + operation, |
| 33 | + cause: error, |
| 34 | + }); |
| 35 | + } |
| 36 | + return data; |
| 37 | +} |
| 38 | + |
| 39 | +export function getSession( |
| 40 | + ...params: Parameters<typeof authClient.getSession> |
| 41 | +) { |
| 42 | + return unwrapAuthClientResult({ |
| 43 | + operation: "get session", |
| 44 | + promise: authClient.getSession(...params), |
| 45 | + }); |
| 46 | +} |
| 47 | + |
| 48 | +export function signUpEmail( |
| 49 | + ...params: Parameters<typeof authClient.signUp.email> |
| 50 | +) { |
| 51 | + return unwrapAuthClientResult({ |
| 52 | + operation: "sign up", |
| 53 | + promise: authClient.signUp.email(...params), |
| 54 | + }); |
| 55 | +} |
| 56 | + |
| 57 | +export function signInEmail( |
| 58 | + ...params: Parameters<typeof authClient.signIn.email> |
| 59 | +) { |
| 60 | + return unwrapAuthClientResult({ |
| 61 | + operation: "sign in", |
| 62 | + promise: authClient.signIn.email(...params), |
| 63 | + }); |
| 64 | +} |
| 65 | + |
| 66 | +export function requestPasswordReset( |
| 67 | + ...params: Parameters<typeof authClient.requestPasswordReset> |
| 68 | +) { |
| 69 | + return unwrapAuthClientResult({ |
| 70 | + operation: "request password reset", |
| 71 | + promise: authClient.requestPasswordReset(...params), |
| 72 | + }); |
| 73 | +} |
| 74 | + |
| 75 | +export function resetPassword( |
| 76 | + ...params: Parameters<typeof authClient.resetPassword> |
| 77 | +) { |
| 78 | + return unwrapAuthClientResult({ |
| 79 | + operation: "reset password", |
| 80 | + promise: authClient.resetPassword(...params), |
| 81 | + }); |
| 82 | +} |
0 commit comments