All files / src/services session.ts

100% Statements 44/44
100% Branches 4/4
100% Functions 1/1
100% Lines 44/44

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 691x     1x     1x     1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x   1x 1x 1x 1x 1x           1x 6x   6x 6x 6x   3x 3x 3x 3x 3x   2x     2x 2x 2x 6x 4x       4x 4x 6x      
import { Effect, Schema } from 'effect';
 
// Utils
import { handleActionError } from '@/utils/errorHandlers';
 
// Constants
import { API_ROUTES } from '@/constants/routes';
 
// Types
import { HttpMethod } from '@shared/types';
import { UserProfile, UserStatus, UserRole } from '@/types/auth';
 
export const UserProfileSchema = Schema.Struct({
  token: Schema.NonEmptyString,
  id: Schema.NonEmptyString,
  email: Schema.NonEmptyString,
  username: Schema.NonEmptyString,
  status: Schema.optionalWith(Schema.Enums(UserStatus), { exact: true }),
  role: Schema.optionalWith(Schema.Enums(UserRole), { exact: true }),
  avatar: Schema.optionalWith(Schema.NonEmptyString, { exact: true }),
  groups: Schema.optionalWith(Schema.Array(Schema.String), {
    exact: true,
  }),
});
 
export const SessionRequestSchema = Schema.Struct({
  user: Schema.optional(UserProfileSchema),
});
 
export const SessionResponseSchema = Schema.Struct({
  ok: Schema.Boolean,
  action: Schema.NonEmptyString,
  user: Schema.optional(UserProfileSchema),
});
 
interface UpdateSessionOptions {
  user?: UserProfile;
}
 
const updateSession = async ({ user }: UpdateSessionOptions) => {
  try {
    // Validate request payload
    const validatedRequest = await Effect.runPromise(
      Schema.decodeUnknown(SessionRequestSchema)({ user }),
    );
 
    const response = await fetch(API_ROUTES.SESSION, {
      method: HttpMethod.POST,
      body: JSON.stringify(validatedRequest),
      credentials: 'include',
    });
 
    const json = await response.json();
 
    // Validate response
    return await Effect.runPromise(
      Schema.decodeUnknown(SessionResponseSchema)(json),
    );
  } catch (error) {
    return handleActionError<{
      ok: boolean;
      action: string;
      user?: UserProfile;
    }>(error);
  }
};
 
export { updateSession };