Merge pull request 'feature/state-and-data-fetching' (#1) from feature/state-and-data-fetching into main
Reviewed-on: #1
This commit was merged in pull request #1.
This commit is contained in:
24
package.json
24
package.json
@@ -7,26 +7,44 @@
|
|||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "tsc -b && vite build",
|
"build": "tsc -b && vite build",
|
||||||
"lint": "eslint .",
|
"lint": "eslint .",
|
||||||
"preview": "vite preview"
|
"preview": "vite preview",
|
||||||
|
"test:unit": "vitest",
|
||||||
|
"test:run": "vitest run",
|
||||||
|
"test:coverage": "vitest run --coverage"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"ky": "^1.14.3",
|
||||||
"react": "^19.2.0",
|
"react": "^19.2.0",
|
||||||
"react-dom": "^19.2.0"
|
"react-dom": "^19.2.0",
|
||||||
|
"zustand": "^5.0.12"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.39.1",
|
"@eslint/js": "^9.39.1",
|
||||||
"@module-federation/vite": "^1.12.3",
|
"@module-federation/vite": "^1.12.3",
|
||||||
|
"@testing-library/dom": "^10.4.1",
|
||||||
|
"@testing-library/jest-dom": "^6.9.1",
|
||||||
|
"@testing-library/react": "^16.3.2",
|
||||||
|
"@testing-library/user-event": "^14.6.1",
|
||||||
"@types/node": "^24.10.1",
|
"@types/node": "^24.10.1",
|
||||||
"@types/react": "^19.2.7",
|
"@types/react": "^19.2.7",
|
||||||
"@types/react-dom": "^19.2.3",
|
"@types/react-dom": "^19.2.3",
|
||||||
"@vitejs/plugin-react": "^5.1.4",
|
"@vitejs/plugin-react": "^5.1.4",
|
||||||
|
"@vitest/coverage-v8": "^4.1.0",
|
||||||
"babel-plugin-react-compiler": "^1.0.0",
|
"babel-plugin-react-compiler": "^1.0.0",
|
||||||
"eslint": "^9.39.1",
|
"eslint": "^9.39.1",
|
||||||
"eslint-plugin-react-hooks": "^7.0.1",
|
"eslint-plugin-react-hooks": "^7.0.1",
|
||||||
"eslint-plugin-react-refresh": "^0.4.24",
|
"eslint-plugin-react-refresh": "^0.4.24",
|
||||||
"globals": "^16.5.0",
|
"globals": "^16.5.0",
|
||||||
|
"jsdom": "^29.0.0",
|
||||||
|
"msw": "^2.12.11",
|
||||||
"typescript": "~5.9.3",
|
"typescript": "~5.9.3",
|
||||||
"typescript-eslint": "^8.48.0",
|
"typescript-eslint": "^8.48.0",
|
||||||
"vite": "^7.3.1"
|
"vite": "^7.3.1",
|
||||||
|
"vitest": "^4.1.0"
|
||||||
|
},
|
||||||
|
"msw": {
|
||||||
|
"workerDirectory": [
|
||||||
|
"public"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
349
public/mockServiceWorker.js
Normal file
349
public/mockServiceWorker.js
Normal file
@@ -0,0 +1,349 @@
|
|||||||
|
/* eslint-disable */
|
||||||
|
/* tslint:disable */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mock Service Worker.
|
||||||
|
* @see https://github.com/mswjs/msw
|
||||||
|
* - Please do NOT modify this file.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const PACKAGE_VERSION = '2.12.11'
|
||||||
|
const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82'
|
||||||
|
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
|
||||||
|
const activeClientIds = new Set()
|
||||||
|
|
||||||
|
addEventListener('install', function () {
|
||||||
|
self.skipWaiting()
|
||||||
|
})
|
||||||
|
|
||||||
|
addEventListener('activate', function (event) {
|
||||||
|
event.waitUntil(self.clients.claim())
|
||||||
|
})
|
||||||
|
|
||||||
|
addEventListener('message', async function (event) {
|
||||||
|
const clientId = Reflect.get(event.source || {}, 'id')
|
||||||
|
|
||||||
|
if (!clientId || !self.clients) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const client = await self.clients.get(clientId)
|
||||||
|
|
||||||
|
if (!client) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const allClients = await self.clients.matchAll({
|
||||||
|
type: 'window',
|
||||||
|
})
|
||||||
|
|
||||||
|
switch (event.data) {
|
||||||
|
case 'KEEPALIVE_REQUEST': {
|
||||||
|
sendToClient(client, {
|
||||||
|
type: 'KEEPALIVE_RESPONSE',
|
||||||
|
})
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'INTEGRITY_CHECK_REQUEST': {
|
||||||
|
sendToClient(client, {
|
||||||
|
type: 'INTEGRITY_CHECK_RESPONSE',
|
||||||
|
payload: {
|
||||||
|
packageVersion: PACKAGE_VERSION,
|
||||||
|
checksum: INTEGRITY_CHECKSUM,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'MOCK_ACTIVATE': {
|
||||||
|
activeClientIds.add(clientId)
|
||||||
|
|
||||||
|
sendToClient(client, {
|
||||||
|
type: 'MOCKING_ENABLED',
|
||||||
|
payload: {
|
||||||
|
client: {
|
||||||
|
id: client.id,
|
||||||
|
frameType: client.frameType,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'CLIENT_CLOSED': {
|
||||||
|
activeClientIds.delete(clientId)
|
||||||
|
|
||||||
|
const remainingClients = allClients.filter((client) => {
|
||||||
|
return client.id !== clientId
|
||||||
|
})
|
||||||
|
|
||||||
|
// Unregister itself when there are no more clients
|
||||||
|
if (remainingClients.length === 0) {
|
||||||
|
self.registration.unregister()
|
||||||
|
}
|
||||||
|
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
addEventListener('fetch', function (event) {
|
||||||
|
const requestInterceptedAt = Date.now()
|
||||||
|
|
||||||
|
// Bypass navigation requests.
|
||||||
|
if (event.request.mode === 'navigate') {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Opening the DevTools triggers the "only-if-cached" request
|
||||||
|
// that cannot be handled by the worker. Bypass such requests.
|
||||||
|
if (
|
||||||
|
event.request.cache === 'only-if-cached' &&
|
||||||
|
event.request.mode !== 'same-origin'
|
||||||
|
) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bypass all requests when there are no active clients.
|
||||||
|
// Prevents the self-unregistered worked from handling requests
|
||||||
|
// after it's been terminated (still remains active until the next reload).
|
||||||
|
if (activeClientIds.size === 0) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const requestId = crypto.randomUUID()
|
||||||
|
event.respondWith(handleRequest(event, requestId, requestInterceptedAt))
|
||||||
|
})
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {FetchEvent} event
|
||||||
|
* @param {string} requestId
|
||||||
|
* @param {number} requestInterceptedAt
|
||||||
|
*/
|
||||||
|
async function handleRequest(event, requestId, requestInterceptedAt) {
|
||||||
|
const client = await resolveMainClient(event)
|
||||||
|
const requestCloneForEvents = event.request.clone()
|
||||||
|
const response = await getResponse(
|
||||||
|
event,
|
||||||
|
client,
|
||||||
|
requestId,
|
||||||
|
requestInterceptedAt,
|
||||||
|
)
|
||||||
|
|
||||||
|
// Send back the response clone for the "response:*" life-cycle events.
|
||||||
|
// Ensure MSW is active and ready to handle the message, otherwise
|
||||||
|
// this message will pend indefinitely.
|
||||||
|
if (client && activeClientIds.has(client.id)) {
|
||||||
|
const serializedRequest = await serializeRequest(requestCloneForEvents)
|
||||||
|
|
||||||
|
// Clone the response so both the client and the library could consume it.
|
||||||
|
const responseClone = response.clone()
|
||||||
|
|
||||||
|
sendToClient(
|
||||||
|
client,
|
||||||
|
{
|
||||||
|
type: 'RESPONSE',
|
||||||
|
payload: {
|
||||||
|
isMockedResponse: IS_MOCKED_RESPONSE in response,
|
||||||
|
request: {
|
||||||
|
id: requestId,
|
||||||
|
...serializedRequest,
|
||||||
|
},
|
||||||
|
response: {
|
||||||
|
type: responseClone.type,
|
||||||
|
status: responseClone.status,
|
||||||
|
statusText: responseClone.statusText,
|
||||||
|
headers: Object.fromEntries(responseClone.headers.entries()),
|
||||||
|
body: responseClone.body,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
responseClone.body ? [serializedRequest.body, responseClone.body] : [],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve the main client for the given event.
|
||||||
|
* Client that issues a request doesn't necessarily equal the client
|
||||||
|
* that registered the worker. It's with the latter the worker should
|
||||||
|
* communicate with during the response resolving phase.
|
||||||
|
* @param {FetchEvent} event
|
||||||
|
* @returns {Promise<Client | undefined>}
|
||||||
|
*/
|
||||||
|
async function resolveMainClient(event) {
|
||||||
|
const client = await self.clients.get(event.clientId)
|
||||||
|
|
||||||
|
if (activeClientIds.has(event.clientId)) {
|
||||||
|
return client
|
||||||
|
}
|
||||||
|
|
||||||
|
if (client?.frameType === 'top-level') {
|
||||||
|
return client
|
||||||
|
}
|
||||||
|
|
||||||
|
const allClients = await self.clients.matchAll({
|
||||||
|
type: 'window',
|
||||||
|
})
|
||||||
|
|
||||||
|
return allClients
|
||||||
|
.filter((client) => {
|
||||||
|
// Get only those clients that are currently visible.
|
||||||
|
return client.visibilityState === 'visible'
|
||||||
|
})
|
||||||
|
.find((client) => {
|
||||||
|
// Find the client ID that's recorded in the
|
||||||
|
// set of clients that have registered the worker.
|
||||||
|
return activeClientIds.has(client.id)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {FetchEvent} event
|
||||||
|
* @param {Client | undefined} client
|
||||||
|
* @param {string} requestId
|
||||||
|
* @param {number} requestInterceptedAt
|
||||||
|
* @returns {Promise<Response>}
|
||||||
|
*/
|
||||||
|
async function getResponse(event, client, requestId, requestInterceptedAt) {
|
||||||
|
// Clone the request because it might've been already used
|
||||||
|
// (i.e. its body has been read and sent to the client).
|
||||||
|
const requestClone = event.request.clone()
|
||||||
|
|
||||||
|
function passthrough() {
|
||||||
|
// Cast the request headers to a new Headers instance
|
||||||
|
// so the headers can be manipulated with.
|
||||||
|
const headers = new Headers(requestClone.headers)
|
||||||
|
|
||||||
|
// Remove the "accept" header value that marked this request as passthrough.
|
||||||
|
// This prevents request alteration and also keeps it compliant with the
|
||||||
|
// user-defined CORS policies.
|
||||||
|
const acceptHeader = headers.get('accept')
|
||||||
|
if (acceptHeader) {
|
||||||
|
const values = acceptHeader.split(',').map((value) => value.trim())
|
||||||
|
const filteredValues = values.filter(
|
||||||
|
(value) => value !== 'msw/passthrough',
|
||||||
|
)
|
||||||
|
|
||||||
|
if (filteredValues.length > 0) {
|
||||||
|
headers.set('accept', filteredValues.join(', '))
|
||||||
|
} else {
|
||||||
|
headers.delete('accept')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return fetch(requestClone, { headers })
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bypass mocking when the client is not active.
|
||||||
|
if (!client) {
|
||||||
|
return passthrough()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bypass initial page load requests (i.e. static assets).
|
||||||
|
// The absence of the immediate/parent client in the map of the active clients
|
||||||
|
// means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
|
||||||
|
// and is not ready to handle requests.
|
||||||
|
if (!activeClientIds.has(client.id)) {
|
||||||
|
return passthrough()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Notify the client that a request has been intercepted.
|
||||||
|
const serializedRequest = await serializeRequest(event.request)
|
||||||
|
const clientMessage = await sendToClient(
|
||||||
|
client,
|
||||||
|
{
|
||||||
|
type: 'REQUEST',
|
||||||
|
payload: {
|
||||||
|
id: requestId,
|
||||||
|
interceptedAt: requestInterceptedAt,
|
||||||
|
...serializedRequest,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
[serializedRequest.body],
|
||||||
|
)
|
||||||
|
|
||||||
|
switch (clientMessage.type) {
|
||||||
|
case 'MOCK_RESPONSE': {
|
||||||
|
return respondWithMock(clientMessage.data)
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'PASSTHROUGH': {
|
||||||
|
return passthrough()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return passthrough()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {Client} client
|
||||||
|
* @param {any} message
|
||||||
|
* @param {Array<Transferable>} transferrables
|
||||||
|
* @returns {Promise<any>}
|
||||||
|
*/
|
||||||
|
function sendToClient(client, message, transferrables = []) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const channel = new MessageChannel()
|
||||||
|
|
||||||
|
channel.port1.onmessage = (event) => {
|
||||||
|
if (event.data && event.data.error) {
|
||||||
|
return reject(event.data.error)
|
||||||
|
}
|
||||||
|
|
||||||
|
resolve(event.data)
|
||||||
|
}
|
||||||
|
|
||||||
|
client.postMessage(message, [
|
||||||
|
channel.port2,
|
||||||
|
...transferrables.filter(Boolean),
|
||||||
|
])
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {Response} response
|
||||||
|
* @returns {Response}
|
||||||
|
*/
|
||||||
|
function respondWithMock(response) {
|
||||||
|
// Setting response status code to 0 is a no-op.
|
||||||
|
// However, when responding with a "Response.error()", the produced Response
|
||||||
|
// instance will have status code set to 0. Since it's not possible to create
|
||||||
|
// a Response instance with status code 0, handle that use-case separately.
|
||||||
|
if (response.status === 0) {
|
||||||
|
return Response.error()
|
||||||
|
}
|
||||||
|
|
||||||
|
const mockedResponse = new Response(response.body, response)
|
||||||
|
|
||||||
|
Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
|
||||||
|
value: true,
|
||||||
|
enumerable: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
return mockedResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {Request} request
|
||||||
|
*/
|
||||||
|
async function serializeRequest(request) {
|
||||||
|
return {
|
||||||
|
url: request.url,
|
||||||
|
mode: request.mode,
|
||||||
|
method: request.method,
|
||||||
|
headers: Object.fromEntries(request.headers.entries()),
|
||||||
|
cache: request.cache,
|
||||||
|
credentials: request.credentials,
|
||||||
|
destination: request.destination,
|
||||||
|
integrity: request.integrity,
|
||||||
|
redirect: request.redirect,
|
||||||
|
referrer: request.referrer,
|
||||||
|
referrerPolicy: request.referrerPolicy,
|
||||||
|
body: await request.arrayBuffer(),
|
||||||
|
keepalive: request.keepalive,
|
||||||
|
}
|
||||||
|
}
|
||||||
1
src/entities/User/index.ts
Normal file
1
src/entities/User/index.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export * from "./model";
|
||||||
1
src/entities/User/model/index.ts
Normal file
1
src/entities/User/model/index.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export * from "./types/types";
|
||||||
10
src/entities/User/model/types/types.ts
Normal file
10
src/entities/User/model/types/types.ts
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
export interface User {
|
||||||
|
/**
|
||||||
|
* User's unique identifier.
|
||||||
|
*/
|
||||||
|
id: string;
|
||||||
|
/**
|
||||||
|
* User's email address.
|
||||||
|
*/
|
||||||
|
email: string;
|
||||||
|
}
|
||||||
4
src/features/auth/api/calls/index.ts
Normal file
4
src/features/auth/api/calls/index.ts
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
export * from "./login";
|
||||||
|
export * from "./register";
|
||||||
|
export * from "./logout";
|
||||||
|
export * from "../../../../shared/api/calls/refresh";
|
||||||
2
src/features/auth/api/calls/login/index.ts
Normal file
2
src/features/auth/api/calls/login/index.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export { login } from "./login";
|
||||||
|
export { loginMock } from "./login.mock";
|
||||||
20
src/features/auth/api/calls/login/login.mock.ts
Normal file
20
src/features/auth/api/calls/login/login.mock.ts
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import { http, HttpResponse } from "msw";
|
||||||
|
import type { AuthData } from "../../../model/types/service";
|
||||||
|
import { BASE_URL } from "shared/api";
|
||||||
|
import { LOGIN_API_ROUTE } from "./login";
|
||||||
|
import { MOCK_AUTH_RESPONSE, MOCK_EMAIL, MOCK_PASSWORD } from "../mocks";
|
||||||
|
|
||||||
|
const LOGIN_URL = `${BASE_URL}/${LOGIN_API_ROUTE}`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Msw interceptor. Mocks the login endpoint response.
|
||||||
|
*/
|
||||||
|
export const loginMock = http.post(LOGIN_URL, async ({ request }) => {
|
||||||
|
const { email, password } = (await request.json()) as AuthData;
|
||||||
|
|
||||||
|
if (email === MOCK_EMAIL && password === MOCK_PASSWORD) {
|
||||||
|
return HttpResponse.json(MOCK_AUTH_RESPONSE);
|
||||||
|
}
|
||||||
|
|
||||||
|
return HttpResponse.json({ message: "Invalid credentials" }, { status: 401 });
|
||||||
|
});
|
||||||
33
src/features/auth/api/calls/login/login.spec.ts
Normal file
33
src/features/auth/api/calls/login/login.spec.ts
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
import { setupServer } from "msw/node";
|
||||||
|
import { login } from "./login";
|
||||||
|
import { loginMock } from "./login.mock";
|
||||||
|
import { MOCK_EMAIL, MOCK_EXISTING_USER, MOCK_PASSWORD } from "../mocks";
|
||||||
|
import { MOCK_TOKEN } from "shared/api";
|
||||||
|
|
||||||
|
const server = setupServer(loginMock);
|
||||||
|
|
||||||
|
describe("login", () => {
|
||||||
|
beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
|
||||||
|
afterEach(() => server.resetHandlers());
|
||||||
|
afterAll(() => server.close());
|
||||||
|
|
||||||
|
describe("happy path", () => {
|
||||||
|
it("returns access token and user on valid credentials", async () => {
|
||||||
|
const result = await login({
|
||||||
|
email: MOCK_EMAIL,
|
||||||
|
password: MOCK_PASSWORD,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.accessToken).toBe(MOCK_TOKEN);
|
||||||
|
expect(result.user).toEqual(MOCK_EXISTING_USER);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("error cases", () => {
|
||||||
|
it("throws on invalid credentials", async () => {
|
||||||
|
await expect(
|
||||||
|
login({ email: "wrong@test.com", password: "wrong" }),
|
||||||
|
).rejects.toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
16
src/features/auth/api/calls/login/login.ts
Normal file
16
src/features/auth/api/calls/login/login.ts
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
import type { AuthData, AuthResponse } from "../../../model/types/service";
|
||||||
|
import { authHttpClient } from "../../config/authApi/authApi";
|
||||||
|
|
||||||
|
export const LOGIN_API_ROUTE = "auth/login";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Logs in a user with the given email and password.
|
||||||
|
*
|
||||||
|
* @param loginData - The user's login data (email and password).
|
||||||
|
* @returns A promise that resolves to the authentication response.
|
||||||
|
*/
|
||||||
|
export function login(loginData: AuthData) {
|
||||||
|
return authHttpClient
|
||||||
|
.post(LOGIN_API_ROUTE, { json: loginData })
|
||||||
|
.json<AuthResponse>();
|
||||||
|
}
|
||||||
2
src/features/auth/api/calls/logout/index.ts
Normal file
2
src/features/auth/api/calls/logout/index.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export { logout } from "./logout";
|
||||||
|
export { logoutMock } from "./logout.mock";
|
||||||
12
src/features/auth/api/calls/logout/logout.mock.ts
Normal file
12
src/features/auth/api/calls/logout/logout.mock.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { http, HttpResponse } from "msw";
|
||||||
|
import { BASE_URL } from "shared/api";
|
||||||
|
import { LOGOUT_API_ROUTE } from "./logout";
|
||||||
|
|
||||||
|
const LOGOUT_URL = `${BASE_URL}/${LOGOUT_API_ROUTE}`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Msw interceptor. Mocks the logout endpoint response.
|
||||||
|
*/
|
||||||
|
export const logoutMock = http.post(LOGOUT_URL, () => {
|
||||||
|
return new HttpResponse(null, { status: 204 });
|
||||||
|
});
|
||||||
19
src/features/auth/api/calls/logout/logout.spec.ts
Normal file
19
src/features/auth/api/calls/logout/logout.spec.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { setupServer } from "msw/node";
|
||||||
|
import { logout } from "./logout";
|
||||||
|
import { logoutMock } from "./logout.mock";
|
||||||
|
|
||||||
|
const server = setupServer(logoutMock);
|
||||||
|
|
||||||
|
describe("logout", () => {
|
||||||
|
beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
|
||||||
|
afterEach(() => server.resetHandlers());
|
||||||
|
afterAll(() => server.close());
|
||||||
|
|
||||||
|
describe("happy path", () => {
|
||||||
|
it("resolves without a value", async () => {
|
||||||
|
const result = await logout();
|
||||||
|
|
||||||
|
expect(result).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
13
src/features/auth/api/calls/logout/logout.ts
Normal file
13
src/features/auth/api/calls/logout/logout.ts
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
import { authHttpClient } from "../../config";
|
||||||
|
|
||||||
|
export const LOGOUT_API_ROUTE = "auth/logout";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Logs out the currently authenticated user.
|
||||||
|
* async/await is used here intentionally to discard the ky Response and return void.
|
||||||
|
*
|
||||||
|
* @returns A promise that resolves when the session is terminated.
|
||||||
|
*/
|
||||||
|
export async function logout(): Promise<void> {
|
||||||
|
await authHttpClient.post(LOGOUT_API_ROUTE);
|
||||||
|
}
|
||||||
22
src/features/auth/api/calls/mocks.ts
Normal file
22
src/features/auth/api/calls/mocks.ts
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import type { User } from "entities/User";
|
||||||
|
import type { AuthResponse } from "../../model";
|
||||||
|
import { MOCK_TOKEN } from "shared/api";
|
||||||
|
|
||||||
|
export const MOCK_EMAIL = "test@test.com";
|
||||||
|
export const MOCK_NEW_EMAIL = "new@test.com";
|
||||||
|
export const MOCK_PASSWORD = "password";
|
||||||
|
|
||||||
|
export const MOCK_EXISTING_USER: User = {
|
||||||
|
id: "1",
|
||||||
|
email: MOCK_EMAIL,
|
||||||
|
};
|
||||||
|
|
||||||
|
export const MOCK_NEW_USER: User = {
|
||||||
|
id: "2",
|
||||||
|
email: MOCK_NEW_EMAIL,
|
||||||
|
};
|
||||||
|
|
||||||
|
export const MOCK_AUTH_RESPONSE: AuthResponse = {
|
||||||
|
accessToken: MOCK_TOKEN,
|
||||||
|
user: MOCK_EXISTING_USER,
|
||||||
|
};
|
||||||
2
src/features/auth/api/calls/register/index.ts
Normal file
2
src/features/auth/api/calls/register/index.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export { register } from "./register";
|
||||||
|
export { registerMock } from "./register.mock";
|
||||||
26
src/features/auth/api/calls/register/register.mock.ts
Normal file
26
src/features/auth/api/calls/register/register.mock.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import { http, HttpResponse } from "msw";
|
||||||
|
import type { AuthData } from "../../../model/types/service";
|
||||||
|
import { BASE_URL, MOCK_TOKEN } from "shared/api";
|
||||||
|
import { REGISTER_API_ROUTE } from "./register";
|
||||||
|
import { MOCK_EMAIL } from "../mocks";
|
||||||
|
|
||||||
|
const REGISTER_URL = `${BASE_URL}/${REGISTER_API_ROUTE}`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Msw interceptor. Mocks the register endpoint response.
|
||||||
|
*/
|
||||||
|
export const registerMock = http.post(REGISTER_URL, async ({ request }) => {
|
||||||
|
const { email } = (await request.json()) as AuthData;
|
||||||
|
|
||||||
|
if (email === MOCK_EMAIL) {
|
||||||
|
return HttpResponse.json(
|
||||||
|
{ message: "User already exists" },
|
||||||
|
{ status: 409 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return HttpResponse.json({
|
||||||
|
accessToken: MOCK_TOKEN,
|
||||||
|
user: { id: "2", email },
|
||||||
|
});
|
||||||
|
});
|
||||||
38
src/features/auth/api/calls/register/register.spec.ts
Normal file
38
src/features/auth/api/calls/register/register.spec.ts
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
import { setupServer } from "msw/node";
|
||||||
|
import { register } from "./register";
|
||||||
|
import { registerMock } from "./register.mock";
|
||||||
|
import {
|
||||||
|
MOCK_EMAIL,
|
||||||
|
MOCK_NEW_EMAIL,
|
||||||
|
MOCK_NEW_USER,
|
||||||
|
MOCK_PASSWORD,
|
||||||
|
} from "../mocks";
|
||||||
|
import { MOCK_TOKEN } from "shared/api";
|
||||||
|
|
||||||
|
const server = setupServer(registerMock);
|
||||||
|
|
||||||
|
describe("register", () => {
|
||||||
|
beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
|
||||||
|
afterEach(() => server.resetHandlers());
|
||||||
|
afterAll(() => server.close());
|
||||||
|
|
||||||
|
describe("happy path", () => {
|
||||||
|
it("returns access token and user for a new email", async () => {
|
||||||
|
const result = await register({
|
||||||
|
email: MOCK_NEW_EMAIL,
|
||||||
|
password: MOCK_PASSWORD,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.accessToken).toBe(MOCK_TOKEN);
|
||||||
|
expect(result.user).toEqual(MOCK_NEW_USER);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("error cases", () => {
|
||||||
|
it("throws when email is already registered", async () => {
|
||||||
|
await expect(
|
||||||
|
register({ email: MOCK_EMAIL, password: MOCK_PASSWORD }),
|
||||||
|
).rejects.toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
16
src/features/auth/api/calls/register/register.ts
Normal file
16
src/features/auth/api/calls/register/register.ts
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
import type { AuthData, AuthResponse } from "../../../model/types/service";
|
||||||
|
import { authHttpClient } from "../../config/authApi/authApi";
|
||||||
|
|
||||||
|
export const REGISTER_API_ROUTE = "auth/register";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registers a new user with the given email and password.
|
||||||
|
*
|
||||||
|
* @param registerData - The user's registration data (email and password).
|
||||||
|
* @returns A promise that resolves to the authentication response.
|
||||||
|
*/
|
||||||
|
export function register(registerData: AuthData) {
|
||||||
|
return authHttpClient
|
||||||
|
.post(REGISTER_API_ROUTE, { json: registerData })
|
||||||
|
.json<AuthResponse>();
|
||||||
|
}
|
||||||
34
src/features/auth/api/config/authApi/authApi.ts
Normal file
34
src/features/auth/api/config/authApi/authApi.ts
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
import { api as baseApi, useTokenStore } from "shared/api";
|
||||||
|
|
||||||
|
export const authHttpClient = baseApi.extend({
|
||||||
|
hooks: {
|
||||||
|
beforeRequest: [
|
||||||
|
(request) => {
|
||||||
|
const token = useTokenStore.getState().accessToken;
|
||||||
|
|
||||||
|
if (token) {
|
||||||
|
request.headers.set("Authorization", `Bearer ${token}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return request;
|
||||||
|
},
|
||||||
|
],
|
||||||
|
afterResponse: [
|
||||||
|
async (request, options, response) => {
|
||||||
|
if (response.status !== 401) {
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { accessToken, refreshToken } = useTokenStore.getState();
|
||||||
|
if (!accessToken) return response;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await refreshToken?.();
|
||||||
|
return authHttpClient(request); // beforeRequest picks up new token automatically
|
||||||
|
} catch {
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
1
src/features/auth/api/config/index.ts
Normal file
1
src/features/auth/api/config/index.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export { authHttpClient } from "./authApi/authApi";
|
||||||
2
src/features/auth/api/index.ts
Normal file
2
src/features/auth/api/index.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export * from "./config";
|
||||||
|
export * from "./calls";
|
||||||
@@ -1,2 +1,3 @@
|
|||||||
export * from "./lib";
|
export * from "./lib";
|
||||||
export * from "./ui";
|
export * from "./ui";
|
||||||
|
export * from "./model";
|
||||||
|
|||||||
6
src/features/auth/model/index.ts
Normal file
6
src/features/auth/model/index.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
// Types
|
||||||
|
export * from "./types/service";
|
||||||
|
export * from "./types/store";
|
||||||
|
|
||||||
|
// Stores
|
||||||
|
export * from "./stores/authStore/authStore";
|
||||||
93
src/features/auth/model/stores/authStore/authStore.spec.ts
Normal file
93
src/features/auth/model/stores/authStore/authStore.spec.ts
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
import { setupServer } from "msw/node";
|
||||||
|
import {
|
||||||
|
loginMock,
|
||||||
|
registerMock,
|
||||||
|
logoutMock,
|
||||||
|
refreshMock,
|
||||||
|
} from "../../../api/calls";
|
||||||
|
import { defaultStoreState, useAuthStore } from "./authStore";
|
||||||
|
import {
|
||||||
|
MOCK_EMAIL,
|
||||||
|
MOCK_NEW_EMAIL,
|
||||||
|
MOCK_PASSWORD,
|
||||||
|
} from "../../../api/calls/mocks";
|
||||||
|
|
||||||
|
const server = setupServer(loginMock, registerMock, logoutMock, refreshMock);
|
||||||
|
|
||||||
|
describe("authStore", () => {
|
||||||
|
beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
|
||||||
|
afterEach(() => {
|
||||||
|
useAuthStore.getState().reset();
|
||||||
|
server.resetHandlers();
|
||||||
|
});
|
||||||
|
afterAll(() => server.close());
|
||||||
|
|
||||||
|
describe("reset", () => {
|
||||||
|
it("should reset the store to default state", () => {
|
||||||
|
useAuthStore.getState().reset();
|
||||||
|
expect(useAuthStore.getState()).toMatchObject(defaultStoreState);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("login", () => {
|
||||||
|
it("should set access token, user data, and update status after successful login", async () => {
|
||||||
|
await useAuthStore
|
||||||
|
.getState()
|
||||||
|
.login({ email: MOCK_EMAIL, password: MOCK_PASSWORD });
|
||||||
|
|
||||||
|
const { user, status, error } = useAuthStore.getState();
|
||||||
|
|
||||||
|
expect(user).toBeDefined();
|
||||||
|
expect(status).toBe("authenticated");
|
||||||
|
expect(error).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should set error and update status if login fails", async () => {
|
||||||
|
await useAuthStore
|
||||||
|
.getState()
|
||||||
|
.login({ email: "wrong@test.com", password: "wrongPassword" });
|
||||||
|
|
||||||
|
const { status, error } = useAuthStore.getState();
|
||||||
|
|
||||||
|
expect(status).toBe("unauthenticated");
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("register", () => {
|
||||||
|
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 });
|
||||||
|
|
||||||
|
const { user, status, error } = useAuthStore.getState();
|
||||||
|
|
||||||
|
expect(user).toBeDefined();
|
||||||
|
expect(status).toBe("authenticated");
|
||||||
|
expect(error).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should set error and update status if registration fails", async () => {
|
||||||
|
await useAuthStore
|
||||||
|
.getState()
|
||||||
|
.register({ email: MOCK_EMAIL, password: MOCK_PASSWORD });
|
||||||
|
|
||||||
|
const { status, error } = useAuthStore.getState();
|
||||||
|
|
||||||
|
expect(status).toBe("unauthenticated");
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("logout", () => {
|
||||||
|
it("should clear access token, user data, and update status after logout", async () => {
|
||||||
|
await useAuthStore.getState().logout();
|
||||||
|
|
||||||
|
const { user, status, error } = useAuthStore.getState();
|
||||||
|
|
||||||
|
expect(user).toBeUndefined();
|
||||||
|
expect(status).toBe("unauthenticated");
|
||||||
|
expect(error).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
89
src/features/auth/model/stores/authStore/authStore.ts
Normal file
89
src/features/auth/model/stores/authStore/authStore.ts
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
import { create } from "zustand";
|
||||||
|
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";
|
||||||
|
|
||||||
|
export const defaultStoreState: Readonly<AuthStoreState> = {
|
||||||
|
user: undefined,
|
||||||
|
status: "idle",
|
||||||
|
error: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
export const useAuthStore = create<AuthStore>()((set) => ({
|
||||||
|
...defaultStoreState,
|
||||||
|
reset: () => set(defaultStoreState),
|
||||||
|
login: async (loginData) => {
|
||||||
|
set({ status: "loading" });
|
||||||
|
try {
|
||||||
|
const [responseData, loginError] = await callApi(() => login(loginData));
|
||||||
|
|
||||||
|
if (loginError) {
|
||||||
|
set({ status: "unauthenticated", error: loginError });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
set({
|
||||||
|
status: "authenticated",
|
||||||
|
user: responseData?.user,
|
||||||
|
error: null,
|
||||||
|
});
|
||||||
|
|
||||||
|
// useTokenStore.setState({ accessToken: responseData?.accessToken });
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
set({
|
||||||
|
status: "unauthenticated",
|
||||||
|
error: new Error(UNEXPECTED_ERROR_MESSAGE),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
register: async (registerData) => {
|
||||||
|
try {
|
||||||
|
const [responseData, registerError] = await callApi(() =>
|
||||||
|
register(registerData),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (registerError) {
|
||||||
|
set({ status: "unauthenticated", error: registerError });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
set({
|
||||||
|
status: "authenticated",
|
||||||
|
user: responseData?.user,
|
||||||
|
error: null,
|
||||||
|
});
|
||||||
|
|
||||||
|
// useTokenStore.setState({ accessToken: responseData?.accessToken });
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
set({
|
||||||
|
status: "unauthenticated",
|
||||||
|
error: new Error(UNEXPECTED_ERROR_MESSAGE),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
logout: async () => {
|
||||||
|
set({ status: "loading" });
|
||||||
|
try {
|
||||||
|
const [, logoutError] = await callApi(() => logout());
|
||||||
|
|
||||||
|
if (logoutError) {
|
||||||
|
set({ error: logoutError });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
set({
|
||||||
|
status: "unauthenticated",
|
||||||
|
user: undefined,
|
||||||
|
error: null,
|
||||||
|
});
|
||||||
|
|
||||||
|
// useTokenStore.setState({ accessToken: null });
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
set({ error: new Error(UNEXPECTED_ERROR_MESSAGE) });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}));
|
||||||
29
src/features/auth/model/types/service.ts
Normal file
29
src/features/auth/model/types/service.ts
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import type { User } from "entities/User";
|
||||||
|
|
||||||
|
export interface AuthData {
|
||||||
|
/**
|
||||||
|
* User's email address.
|
||||||
|
*/
|
||||||
|
email: string;
|
||||||
|
/**
|
||||||
|
* User's password.
|
||||||
|
*/
|
||||||
|
password: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AuthResponse {
|
||||||
|
/**
|
||||||
|
* Access token for the authenticated user.
|
||||||
|
*/
|
||||||
|
accessToken: string;
|
||||||
|
/**
|
||||||
|
* User object associated with the access token.
|
||||||
|
*/
|
||||||
|
user: User;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AuthStatus =
|
||||||
|
| "idle"
|
||||||
|
| "loading"
|
||||||
|
| "authenticated"
|
||||||
|
| "unauthenticated";
|
||||||
32
src/features/auth/model/types/store.ts
Normal file
32
src/features/auth/model/types/store.ts
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
import type { User } from "entities/User";
|
||||||
|
import type { AuthData, AuthStatus } from "./service";
|
||||||
|
import type { ApiError } from "shared/utils";
|
||||||
|
|
||||||
|
export interface AuthStoreState {
|
||||||
|
/**
|
||||||
|
* User's credentials
|
||||||
|
*/
|
||||||
|
user?: User;
|
||||||
|
/**
|
||||||
|
* Authentication status
|
||||||
|
*/
|
||||||
|
status: AuthStatus;
|
||||||
|
/**
|
||||||
|
* Error data
|
||||||
|
*/
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AuthStore = AuthStoreState & AuthStoreActions;
|
||||||
2
src/shared/api/calls/index.ts
Normal file
2
src/shared/api/calls/index.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export * from "./refresh/refresh";
|
||||||
|
export * from "./refresh/refresh.mock";
|
||||||
2
src/shared/api/calls/refresh/index.ts
Normal file
2
src/shared/api/calls/refresh/index.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export { refresh } from "./refresh";
|
||||||
|
export { refreshMock } from "./refresh.mock";
|
||||||
26
src/shared/api/calls/refresh/refresh.mock.ts
Normal file
26
src/shared/api/calls/refresh/refresh.mock.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import { http, HttpResponse } from "msw";
|
||||||
|
import { REFRESH_API_ROUTE } from "./refresh";
|
||||||
|
import { BASE_URL, MOCK_FRESH_TOKEN, MOCK_TOKEN } from "../../model";
|
||||||
|
|
||||||
|
const REFRESH_URL = `${BASE_URL}/${REFRESH_API_ROUTE}`;
|
||||||
|
const MOCK_BEARER_TOKEN = `Bearer ${MOCK_TOKEN}`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Msw interceptor. Mocks the refresh endpoint response.
|
||||||
|
* Cookie validation is a server concern — always returns a fresh token.
|
||||||
|
* Use server.use() to override with a 401 in tests that need a failure case.
|
||||||
|
*/
|
||||||
|
export const refreshMock = http.post(REFRESH_URL, async ({ request }) => {
|
||||||
|
if (request.headers.get("Authorization") === MOCK_BEARER_TOKEN) {
|
||||||
|
return HttpResponse.json({
|
||||||
|
accessToken: MOCK_FRESH_TOKEN,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return HttpResponse.json(
|
||||||
|
{
|
||||||
|
error: "Unauthorized",
|
||||||
|
},
|
||||||
|
{ status: 401 },
|
||||||
|
);
|
||||||
|
});
|
||||||
30
src/shared/api/calls/refresh/refresh.spec.ts
Normal file
30
src/shared/api/calls/refresh/refresh.spec.ts
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
import { setupServer } from "msw/node";
|
||||||
|
import { useTokenStore } from "../../model/stores/tokenStore";
|
||||||
|
import { refresh } from "./refresh";
|
||||||
|
import { refreshMock } from "./refresh.mock";
|
||||||
|
import { MOCK_FRESH_TOKEN, MOCK_TOKEN } from "../../model/const";
|
||||||
|
|
||||||
|
const server = setupServer(refreshMock);
|
||||||
|
|
||||||
|
describe("refresh", () => {
|
||||||
|
beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
|
||||||
|
afterEach(() => {
|
||||||
|
server.resetHandlers();
|
||||||
|
useTokenStore.setState({ accessToken: undefined });
|
||||||
|
});
|
||||||
|
afterAll(() => server.close());
|
||||||
|
|
||||||
|
describe("happy path", () => {
|
||||||
|
it("returns a fresh access token and user when session is valid", async () => {
|
||||||
|
const result = await refresh(MOCK_TOKEN);
|
||||||
|
|
||||||
|
expect(result.accessToken).toBe(MOCK_FRESH_TOKEN);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("error cases", () => {
|
||||||
|
it("throws when session is expired or missing", async () => {
|
||||||
|
await expect(refresh("expired_token")).rejects.toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
10
src/shared/api/calls/refresh/refresh.ts
Normal file
10
src/shared/api/calls/refresh/refresh.ts
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import { api } from "../../config/api";
|
||||||
|
import type { RefreshTokenResponse } from "../../model/types";
|
||||||
|
|
||||||
|
export const REFRESH_API_ROUTE = "auth/refresh";
|
||||||
|
|
||||||
|
export function refresh(token: string) {
|
||||||
|
return api
|
||||||
|
.post(REFRESH_API_ROUTE, { headers: { Authorization: `Bearer ${token}` } })
|
||||||
|
.json<RefreshTokenResponse>();
|
||||||
|
}
|
||||||
20
src/shared/api/config/api.ts
Normal file
20
src/shared/api/config/api.ts
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import ky from "ky";
|
||||||
|
import { BASE_URL } from "../model/const";
|
||||||
|
import { useTokenStore } from "../model";
|
||||||
|
|
||||||
|
export const api = ky.create({
|
||||||
|
prefixUrl: BASE_URL,
|
||||||
|
hooks: {
|
||||||
|
beforeRequest: [
|
||||||
|
(request) => {
|
||||||
|
const token = useTokenStore.getState().accessToken;
|
||||||
|
|
||||||
|
if (token) {
|
||||||
|
request.headers.set("Authorization", `Bearer ${token}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return request;
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
2
src/shared/api/index.ts
Normal file
2
src/shared/api/index.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export * from "./model";
|
||||||
|
export { api } from "./config/api";
|
||||||
6
src/shared/api/model/const/index.ts
Normal file
6
src/shared/api/model/const/index.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
export const BASE_URL =
|
||||||
|
import.meta.env.VITE_API_BASE_URL || "https://localhost:3001";
|
||||||
|
|
||||||
|
export const UNEXPECTED_ERROR_MESSAGE = "An unexpected error occured";
|
||||||
|
export const MOCK_TOKEN = "mock.access.token";
|
||||||
|
export const MOCK_FRESH_TOKEN = "mock.fresh.access.token";
|
||||||
3
src/shared/api/model/index.ts
Normal file
3
src/shared/api/model/index.ts
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
export * from "./types";
|
||||||
|
export * from "./stores/tokenStore";
|
||||||
|
export * from "./const";
|
||||||
45
src/shared/api/model/stores/tokenStore.spec.ts
Normal file
45
src/shared/api/model/stores/tokenStore.spec.ts
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
import { setupServer } from "msw/node";
|
||||||
|
import { MOCK_TOKEN } from "../const";
|
||||||
|
import { defaultStoreState, useTokenStore } from "./tokenStore";
|
||||||
|
import { refreshMock } from "shared/api/calls";
|
||||||
|
|
||||||
|
const server = setupServer(refreshMock);
|
||||||
|
|
||||||
|
describe("tokenStore", () => {
|
||||||
|
beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
|
||||||
|
afterEach(() => {
|
||||||
|
useTokenStore.getState().reset();
|
||||||
|
server.resetHandlers();
|
||||||
|
});
|
||||||
|
afterAll(() => server.close());
|
||||||
|
|
||||||
|
describe("reset", () => {
|
||||||
|
it("should reset the store to default state", () => {
|
||||||
|
useTokenStore.getState().reset();
|
||||||
|
expect(useTokenStore.getState()).toMatchObject(defaultStoreState);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("refreshToken", () => {
|
||||||
|
it("should update access token after successful refresh", async () => {
|
||||||
|
useTokenStore.setState({ accessToken: MOCK_TOKEN });
|
||||||
|
|
||||||
|
await useTokenStore.getState().refreshToken();
|
||||||
|
|
||||||
|
const { accessToken, error } = useTokenStore.getState();
|
||||||
|
|
||||||
|
expect(accessToken).toBeDefined();
|
||||||
|
expect(error).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should set error if refresh fails", async () => {
|
||||||
|
useTokenStore.setState({ accessToken: "old_token" });
|
||||||
|
|
||||||
|
await useTokenStore.getState().refreshToken();
|
||||||
|
|
||||||
|
const { error } = useTokenStore.getState();
|
||||||
|
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
39
src/shared/api/model/stores/tokenStore.ts
Normal file
39
src/shared/api/model/stores/tokenStore.ts
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
import { create } from "zustand";
|
||||||
|
import type { TokenStore, TokenStoreState } from "../types";
|
||||||
|
import { callApi } from "shared/utils";
|
||||||
|
import { refresh } from "../../calls/refresh";
|
||||||
|
import { UNEXPECTED_ERROR_MESSAGE } from "../const";
|
||||||
|
|
||||||
|
export const defaultStoreState: TokenStoreState = {
|
||||||
|
accessToken: null,
|
||||||
|
error: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
export const useTokenStore = create<TokenStore>()((set, get) => ({
|
||||||
|
...defaultStoreState,
|
||||||
|
reset: () => set(defaultStoreState),
|
||||||
|
refreshToken: async () => {
|
||||||
|
try {
|
||||||
|
const currentToken = get().accessToken;
|
||||||
|
if (!currentToken) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const [refreshResponse, refreshError] = await callApi(() =>
|
||||||
|
refresh(currentToken),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (refreshError) {
|
||||||
|
set({ error: refreshError });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
set({ accessToken: refreshResponse?.accessToken });
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
set({
|
||||||
|
error: new Error(UNEXPECTED_ERROR_MESSAGE),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}));
|
||||||
17
src/shared/api/model/types/index.ts
Normal file
17
src/shared/api/model/types/index.ts
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
import type { ApiError } from "shared/utils";
|
||||||
|
|
||||||
|
export interface TokenStoreState {
|
||||||
|
accessToken: string | null;
|
||||||
|
error: ApiError | Error | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TokenStoreActions {
|
||||||
|
reset: () => void;
|
||||||
|
refreshToken: () => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type TokenStore = TokenStoreState & TokenStoreActions;
|
||||||
|
|
||||||
|
export interface RefreshTokenResponse {
|
||||||
|
accessToken: string;
|
||||||
|
}
|
||||||
1
src/shared/config/test/setup.ts
Normal file
1
src/shared/config/test/setup.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
import "@testing-library/jest-dom";
|
||||||
40
src/shared/utils/helpers/callApi/callApi.spec.ts
Normal file
40
src/shared/utils/helpers/callApi/callApi.spec.ts
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
import { HTTPError } from "ky";
|
||||||
|
import { callApi } from "./callApi";
|
||||||
|
|
||||||
|
function makeHttpError(status: number, body: object) {
|
||||||
|
const response = new Response(JSON.stringify(body), {
|
||||||
|
status,
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
});
|
||||||
|
return new HTTPError(response, new Request("http://test.com"), {});
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("callApi", () => {
|
||||||
|
describe("happy path", () => {
|
||||||
|
it("returns [data, null] when the fn resolves", async () => {
|
||||||
|
const [data, error] = await callApi(() => Promise.resolve({ id: 1 }));
|
||||||
|
|
||||||
|
expect(data).toEqual({ id: 1 });
|
||||||
|
expect(error).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("error cases", () => {
|
||||||
|
it("returns [null, ApiError] on HTTPError", async () => {
|
||||||
|
const [data, error] = await callApi(() =>
|
||||||
|
Promise.reject(makeHttpError(401, { message: "Unauthorized" })),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(data).toBeNull();
|
||||||
|
expect(error).toEqual({ status: 401, message: "Unauthorized" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("re-throws non-HTTP errors", async () => {
|
||||||
|
const unexpected = new TypeError("Network failure");
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
callApi(() => Promise.reject(unexpected)),
|
||||||
|
).rejects.toThrow("Network failure");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
33
src/shared/utils/helpers/callApi/callApi.ts
Normal file
33
src/shared/utils/helpers/callApi/callApi.ts
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
import { HTTPError } from "ky";
|
||||||
|
|
||||||
|
export interface ApiError {
|
||||||
|
/**
|
||||||
|
* Client error response status code
|
||||||
|
*/
|
||||||
|
status: number;
|
||||||
|
/**
|
||||||
|
* Error message
|
||||||
|
*/
|
||||||
|
message: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper function that calls Ky and manages its errors;
|
||||||
|
* @returns A tuple [data, error] in Golang-like fashion
|
||||||
|
*/
|
||||||
|
export async function callApi<T>(
|
||||||
|
fn: () => Promise<T>,
|
||||||
|
): Promise<[T, null] | [null, ApiError]> {
|
||||||
|
try {
|
||||||
|
const data = await fn();
|
||||||
|
return [data, null];
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof HTTPError) {
|
||||||
|
const body = await error.response.json<{ message: string }>();
|
||||||
|
return [null, { status: error.response.status, message: body.message }];
|
||||||
|
}
|
||||||
|
|
||||||
|
// re-throw unexpected errors
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
1
src/shared/utils/helpers/index.ts
Normal file
1
src/shared/utils/helpers/index.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export * from "./callApi/callApi";
|
||||||
1
src/shared/utils/index.ts
Normal file
1
src/shared/utils/index.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export * from "./helpers";
|
||||||
@@ -5,7 +5,7 @@
|
|||||||
"useDefineForClassFields": true,
|
"useDefineForClassFields": true,
|
||||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||||
"module": "ESNext",
|
"module": "ESNext",
|
||||||
"types": ["vite/client"],
|
"types": ["vite/client", "vitest/globals"],
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
|
|
||||||
/* Bundler mode */
|
/* Bundler mode */
|
||||||
@@ -22,7 +22,17 @@
|
|||||||
"noUnusedParameters": true,
|
"noUnusedParameters": true,
|
||||||
"erasableSyntaxOnly": true,
|
"erasableSyntaxOnly": true,
|
||||||
"noFallthroughCasesInSwitch": true,
|
"noFallthroughCasesInSwitch": true,
|
||||||
"noUncheckedSideEffectImports": true
|
"noUncheckedSideEffectImports": true,
|
||||||
|
|
||||||
|
/* FSD path aliases */
|
||||||
|
"baseUrl": ".",
|
||||||
|
"paths": {
|
||||||
|
"shared/*": ["src/shared/*"],
|
||||||
|
"entities/*": ["src/entities/*"],
|
||||||
|
"features/*": ["src/features/*"],
|
||||||
|
"widgets/*": ["src/widgets/*"],
|
||||||
|
"app/*": ["src/app/*"]
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"include": ["src"]
|
"include": ["src"]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,18 @@
|
|||||||
import { defineConfig } from "vite";
|
import { defineConfig } from "vite";
|
||||||
import react from "@vitejs/plugin-react";
|
import react from "@vitejs/plugin-react";
|
||||||
import { federation } from "@module-federation/vite";
|
import { federation } from "@module-federation/vite";
|
||||||
|
import path from "path";
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
|
resolve: {
|
||||||
|
alias: {
|
||||||
|
shared: path.resolve(__dirname, "src/shared"),
|
||||||
|
entities: path.resolve(__dirname, "src/entities"),
|
||||||
|
features: path.resolve(__dirname, "src/features"),
|
||||||
|
widgets: path.resolve(__dirname, "src/widgets"),
|
||||||
|
app: path.resolve(__dirname, "src/app"),
|
||||||
|
},
|
||||||
|
},
|
||||||
plugins: [
|
plugins: [
|
||||||
react({
|
react({
|
||||||
babel: {
|
babel: {
|
||||||
@@ -13,7 +23,12 @@ export default defineConfig({
|
|||||||
name: "auth-react-remote",
|
name: "auth-react-remote",
|
||||||
manifest: true,
|
manifest: true,
|
||||||
filename: "remoteEntry.js",
|
filename: "remoteEntry.js",
|
||||||
exposes: {},
|
exposes: {
|
||||||
|
"./AuthGuard": "./src/features/auth",
|
||||||
|
"./useAuth": "./src/features/auth",
|
||||||
|
"./RegisterForm": "./src/features/auth",
|
||||||
|
"./LoginForm": "./src/features/auth",
|
||||||
|
},
|
||||||
shared: ["react", "react-dom", "zustand"],
|
shared: ["react", "react-dom", "zustand"],
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
|
|||||||
32
vitest.config.ts
Normal file
32
vitest.config.ts
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
import { defineConfig } from "vitest/config";
|
||||||
|
import react from "@vitejs/plugin-react";
|
||||||
|
import path from "path";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [
|
||||||
|
react({
|
||||||
|
babel: {
|
||||||
|
plugins: [["babel-plugin-react-compiler", {}]],
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
resolve: {
|
||||||
|
alias: {
|
||||||
|
shared: path.resolve(__dirname, "src/shared"),
|
||||||
|
entities: path.resolve(__dirname, "src/entities"),
|
||||||
|
features: path.resolve(__dirname, "src/features"),
|
||||||
|
widgets: path.resolve(__dirname, "src/widgets"),
|
||||||
|
app: path.resolve(__dirname, "src/app"),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
test: {
|
||||||
|
globals: true,
|
||||||
|
environment: "jsdom",
|
||||||
|
setupFiles: ["./src/shared/config/test/setup.ts"],
|
||||||
|
coverage: {
|
||||||
|
provider: "v8",
|
||||||
|
reporter: ["text", "json", "html"],
|
||||||
|
exclude: ["node_modules/", "src/test/"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user