Compare commits

...

3 Commits

8 changed files with 242 additions and 38 deletions

View File

@@ -0,0 +1,2 @@
export * from "./selectFormValid/selectFormValid";
export * from "./selectAuthData/selectAuthData";

View File

@@ -0,0 +1,14 @@
import { useAuthStore } from "../../stores/authStore/authStore";
import { selectAuthData } from "./selectAuthData";
import { MOCK_EMAIL, MOCK_PASSWORD } from "../../../api/calls/mocks";
describe("selectAuthData", () => {
it("should return the correct auth data", () => {
useAuthStore.getState().setEmail(MOCK_EMAIL);
useAuthStore.getState().setPassword(MOCK_PASSWORD);
expect(selectAuthData(useAuthStore.getState())).toEqual({
email: MOCK_EMAIL,
password: MOCK_PASSWORD,
});
});
});

View File

@@ -0,0 +1,7 @@
import type { AuthData } from "../../types/service";
import type { AuthStore } from "../../types/store";
export const selectAuthData = (state: AuthStore): AuthData => ({
email: state.formData.email.value,
password: state.formData.password.value,
});

View File

@@ -0,0 +1,25 @@
import { MOCK_EMAIL, MOCK_PASSWORD } from "../../../api/calls/mocks";
import { useAuthStore } from "../../stores/authStore/authStore";
import { selectFormValid } from "./selectFormValid";
describe("selectFormValid", () => {
afterEach(() => {
useAuthStore.getState().reset();
});
it("should be false when email is invalid", () => {
useAuthStore.getState().setEmail("");
expect(selectFormValid(useAuthStore.getState())).toBe(false);
});
it("should be false when password is invalid", () => {
useAuthStore.getState().setPassword("");
expect(selectFormValid(useAuthStore.getState())).toBe(false);
});
it("should be true when email and password are valid", () => {
useAuthStore.getState().setEmail(MOCK_EMAIL);
useAuthStore.getState().setPassword(MOCK_PASSWORD);
expect(selectFormValid(useAuthStore.getState())).toBe(true);
});
});

View File

@@ -0,0 +1,4 @@
import type { AuthStore } from "../../types/store";
export const selectFormValid = (state: AuthStore) =>
Object.values(state.formData).every((field) => field.valid);

View File

@@ -1,10 +1,5 @@
import { setupServer } from "msw/node";
import {
loginMock,
registerMock,
logoutMock,
refreshMock,
} from "../../../api/calls";
import * as apiCalls from "../../../api/calls";
import { defaultStoreState, useAuthStore } from "./authStore";
import {
MOCK_EMAIL,
@@ -12,7 +7,16 @@ import {
MOCK_PASSWORD,
} from "../../../api/calls/mocks";
const server = setupServer(loginMock, registerMock, logoutMock, refreshMock);
const server = setupServer(
apiCalls.loginMock,
apiCalls.registerMock,
apiCalls.logoutMock,
apiCalls.refreshMock,
);
const loginSpy = vi.spyOn(apiCalls, "login");
const registerSpy = vi.spyOn(apiCalls, "register");
const logoutSpy = vi.spyOn(apiCalls, "logout");
describe("authStore", () => {
beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
@@ -22,6 +26,24 @@ describe("authStore", () => {
});
afterAll(() => server.close());
describe("setEmail", () => {
it("should set the email in formData", () => {
useAuthStore.getState().setEmail(MOCK_NEW_EMAIL);
expect(useAuthStore.getState().formData.email).toMatchObject({
value: MOCK_NEW_EMAIL,
});
});
});
describe("setPassword", () => {
it("should set the password in formData", () => {
useAuthStore.getState().setPassword(MOCK_PASSWORD);
expect(useAuthStore.getState().formData.password).toMatchObject({
value: MOCK_PASSWORD,
});
});
});
describe("reset", () => {
it("should reset the store to default state", () => {
useAuthStore.getState().reset();
@@ -30,10 +52,33 @@ describe("authStore", () => {
});
describe("login", () => {
it("should not do api call if status is loading", async () => {
useAuthStore.getState().setEmail(MOCK_EMAIL);
useAuthStore.getState().setPassword(MOCK_PASSWORD);
useAuthStore.setState({ status: "loading" });
await useAuthStore.getState().login();
expect(loginSpy).not.toHaveBeenCalled();
});
it("should not do api call if form is invalid", async () => {
useAuthStore.getState().setEmail("");
useAuthStore.getState().setPassword("");
await useAuthStore.getState().login();
const { status } = useAuthStore.getState();
expect(loginSpy).not.toHaveBeenCalled();
expect(status).toBe("idle");
});
it("should set access token, user data, and update status after successful login", async () => {
await useAuthStore
.getState()
.login({ email: MOCK_EMAIL, password: MOCK_PASSWORD });
useAuthStore.getState().setEmail(MOCK_EMAIL);
useAuthStore.getState().setPassword(MOCK_PASSWORD);
await useAuthStore.getState().login();
const { user, status, error } = useAuthStore.getState();
@@ -43,9 +88,10 @@ describe("authStore", () => {
});
it("should set error and update status if login fails", async () => {
await useAuthStore
.getState()
.login({ email: "wrong@test.com", password: "wrongPassword" });
useAuthStore.getState().setEmail("wrong@test.com");
useAuthStore.getState().setPassword("wrongPassword");
await useAuthStore.getState().login();
const { status, error } = useAuthStore.getState();
@@ -55,10 +101,33 @@ describe("authStore", () => {
});
describe("register", () => {
it("should not do api call if status is loading", async () => {
useAuthStore.getState().setEmail(MOCK_EMAIL);
useAuthStore.getState().setPassword(MOCK_PASSWORD);
useAuthStore.setState({ status: "loading" });
await useAuthStore.getState().register();
expect(registerSpy).not.toHaveBeenCalled();
});
it("should not do api call if form is invalid", async () => {
useAuthStore.getState().setEmail("");
useAuthStore.getState().setPassword("");
await useAuthStore.getState().register();
const { status } = useAuthStore.getState();
expect(registerSpy).not.toHaveBeenCalled();
expect(status).toBe("idle");
});
it("should set access token, user data, and update status after successful registration", async () => {
await useAuthStore
.getState()
.register({ email: MOCK_NEW_EMAIL, password: MOCK_PASSWORD });
useAuthStore.getState().setEmail(MOCK_NEW_EMAIL);
useAuthStore.getState().setPassword(MOCK_PASSWORD);
await useAuthStore.getState().register();
const { user, status, error } = useAuthStore.getState();
@@ -68,9 +137,10 @@ describe("authStore", () => {
});
it("should set error and update status if registration fails", async () => {
await useAuthStore
.getState()
.register({ email: MOCK_EMAIL, password: MOCK_PASSWORD });
useAuthStore.getState().setEmail(MOCK_EMAIL);
useAuthStore.getState().setPassword(MOCK_PASSWORD);
await useAuthStore.getState().register();
const { status, error } = useAuthStore.getState();
@@ -80,6 +150,14 @@ describe("authStore", () => {
});
describe("logout", () => {
it("should not do api call if status is loading", async () => {
useAuthStore.setState({ status: "loading" });
await useAuthStore.getState().logout();
expect(logoutSpy).not.toHaveBeenCalled();
});
it("should clear access token, user data, and update status after logout", async () => {
await useAuthStore.getState().logout();

View File

@@ -3,19 +3,66 @@ import type { AuthStore, AuthStoreState } from "../../types/store";
import { login, logout, register } from "../../../api";
import { callApi } from "shared/utils";
import { UNEXPECTED_ERROR_MESSAGE } from "shared/api";
import { selectAuthData, selectFormValid } from "../../selectors";
export const defaultStoreState: Readonly<AuthStoreState> = {
formData: {
email: { value: "", valid: false },
password: { value: "", valid: false },
},
user: undefined,
status: "idle",
error: null,
};
export const useAuthStore = create<AuthStore>()((set) => ({
function validateEmail(email: string): boolean {
return Boolean(email);
}
function validatePassword(password: string): boolean {
return Boolean(password);
}
export const useAuthStore = create<AuthStore>()((set, get) => ({
...defaultStoreState,
reset: () => set(defaultStoreState),
login: async (loginData) => {
setEmail: (email: string) => {
const isValid = validateEmail(email);
set((state) => ({
formData: { ...state.formData, email: { value: email, valid: isValid } },
}));
},
setPassword: (password: string) => {
const isValid = validatePassword(password);
set((state) => ({
formData: {
...state.formData,
password: { value: password, valid: isValid },
},
}));
},
reset: () => {
set(defaultStoreState);
},
login: async () => {
const { status } = get();
if (status === "loading") {
return;
}
set({ status: "loading" });
const formValid = selectFormValid(get());
if (!formValid) {
set({ status: "idle" });
return;
}
try {
const loginData = selectAuthData(get());
const [responseData, loginError] = await callApi(() => login(loginData));
if (loginError) {
@@ -28,8 +75,6 @@ export const useAuthStore = create<AuthStore>()((set) => ({
user: responseData?.user,
error: null,
});
// useTokenStore.setState({ accessToken: responseData?.accessToken });
} catch (err) {
console.error(err);
set({
@@ -38,8 +83,24 @@ export const useAuthStore = create<AuthStore>()((set) => ({
});
}
},
register: async (registerData) => {
register: async () => {
const { status } = get();
if (status === "loading") {
return;
}
set({ status: "loading" });
const formValid = selectFormValid(get());
if (!formValid) {
set({ status: "idle" });
return;
}
try {
const registerData = selectAuthData(get());
const [responseData, registerError] = await callApi(() =>
register(registerData),
);
@@ -54,8 +115,6 @@ export const useAuthStore = create<AuthStore>()((set) => ({
user: responseData?.user,
error: null,
});
// useTokenStore.setState({ accessToken: responseData?.accessToken });
} catch (err) {
console.error(err);
set({
@@ -65,12 +124,18 @@ export const useAuthStore = create<AuthStore>()((set) => ({
}
},
logout: async () => {
const prevStatus = get().status;
if (prevStatus === "loading") {
return;
}
set({ status: "loading" });
try {
const [, logoutError] = await callApi(() => logout());
if (logoutError) {
set({ error: logoutError });
set({ error: logoutError, status: prevStatus });
return;
}

View File

@@ -2,9 +2,20 @@ import type { User } from "entities/User";
import type { AuthData, AuthStatus } from "./service";
import type { ApiError } from "shared/utils";
export type AuthFormData = {
[K in keyof AuthData]: {
value: AuthData[K];
valid: boolean;
};
};
export interface AuthStoreState {
/**
* User's credentials
* Form data for login/register forms
*/
formData: AuthFormData;
/**
* Current user
*/
user?: User;
/**
@@ -17,16 +28,14 @@ export interface AuthStoreState {
error: ApiError | Error | null;
}
export type ResetAction = () => void;
export type LoginAction = (data: AuthData) => Promise<void>;
export type RegisterAction = (data: AuthData) => Promise<void>;
export type LogoutAction = () => Promise<void>;
export interface AuthStoreActions {
reset: ResetAction;
login: LoginAction;
register: RegisterAction;
logout: LogoutAction;
setEmail: (email: string) => void;
setPassword: (password: string) => void;
reset: () => void;
login: () => Promise<void>;
register: () => Promise<void>;
logout: () => Promise<void>;
}
export type AuthStore = AuthStoreState & AuthStoreActions;