
Security News
Axios Supply Chain Attack Reaches OpenAI macOS Signing Pipeline, Forces Certificate Rotation
OpenAI rotated macOS signing certificates after a malicious Axios package reached its CI pipeline in a broader software supply chain attack.
request-store-manager
Advanced tools
Allows you to write less boilerplate code when making API requests.
Позволяет писать меньше шаблонного кода при запросах к api.
При создании нового фронтового приложения каждый раз приходится организовывать работу связки:
Часто разработка фронта и бэка происходит в асинхронном формате. Фронтовое приложение хочется иметь возможность разрабатывать/запускать не зависимо от серверной части. Но добавление моков на все приложение занимает не мало времени.
Так же, данные запрашиваются из разных мест. А хотелось бы собрать все запросы в одном файле. И при вызове запроса писать как можно меньше однообразного кода.
Данная библиотека позволяет:
npm install --save request-store-manager
src/apisrc/api
import type { RequestManagerBase, IHttpsRequest, TNotificationsBase } from 'request-store-manager';
type TError = { message?: string[]; error?: string; statusCode?: number };
interface ITask {
id: number;
title: string;
}
/**
* Задайте имя токена. В запросах вы будете указывать это имя. Если вы работаете с несколькими api,
* то можно задать несколько имен.
**/
type TTokens = 'main' | 'second' | 'third';
/**
* Задайте формат хранилища
**/
type TStore = {
tasks: { backlog: string[]; done: string[] };
zero: boolean;
non: null;
}
/**
* Опишите запросы (для GET можно добавить storeKey для автосохранения), типы успешных ответов
**/
interface RM extends RequestManagerBase<TTokens, TStore> {
getTasks: {
fn: (quantity: number) => IHttpsRequest<TTokens>;
success: { data: { type: 'backlog' | 'done'; text: string }[]; quantity: number };
storeKey: 'tasks';
error: TError;
};
getZero: {
fn: () => IHttpsRequest<TTokens>;
success: boolean;
storeKey: 'zero';
};
postAuth: {
fn: () => IHttpsRequest<TTokens>;
success: boolean;
};
}
/**
* Дополнительно
* =================================================
* Вы можете расширить передаваемые поля уведомления. По умолчанию Partial<Record<'title' | 'text' | 'action', string>>
**/
interface TNotifications extends TNotificationsBase {
action2: string;
}
import './api';
api/index.ts
import { HttpsStore, ICustomFetchCheckProps, NeedsStore, NotificationsStore, SettingsStore } from 'request-store-manager';
import { GET_TASKS, POST_AUTH, POST_TASK } from './urls';
import { mockPosts, mockSuccessAnswer, mockTasks, mockUsers } from './mocks';
export * from './types';
function validationSuccessAnswer(dataJson: unknown, response: Response | undefined): dataJson is TAnswer<unknown> {
return !!response?.ok && IsObject(dataJson);
}
requestManager = new RequestManager<TTokens, TStore, RM>({
settings: {
logger: false,
notifications: {},
cache: { prefix: 'test' },
request: { mockMode: true },
https: {
waitToken: false,
notifications: false,
loader: false,
},
},
tokens: {
main: {
template: 'bearer',
cache: {
maxAge: 60 * 24,
},
},
},
namedRequests: {
getTasks: {
request: (quantity: number) => ({
url: 'https://test.com/' + quantity,
method: 'GET',
tokenName: 'main',
}),
validation: (dataJson, response): dataJson is RM['getTasks']['success'] =>
!!response?.ok && typeof dataJson === 'object',
mock: (input, init) => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
const quantity = Number(url.split('/').reverse()[0]);
return new Response(
JSON.stringify({
data: [
{ type: 'backlog', text: 'task1' },
{ type: 'done', text: 'tsak2' },
],
quantity,
}),
{
status: 200,
statusText: 'OK',
},
);
},
store: {
key: 'tasks',
default: { backlog: [], done: [] },
converter: ({ state, validData }) => {
const { backlog, done } = Object.groupBy(validData.data, ({ type }) => type);
return { backlog: backlog?.map(({ text }) => text) || [], done: done?.map(({ text }) => text) || [] };
},
validation: (data): data is Store[RM['getTasks']['storeKey']] =>
!!data && typeof data === 'object' && 'backlog' in data && 'done' in data,
cache: { maxAge: 0, place: 'sessionStorage' },
empty: (value) => value.backlog.length === 0 && value.done.length === 0,
},
afterRequest: ({ response, input }) => {
if (!response.ok) return;
requestManager
.getModule('notifications')
.send({ data: { text: 'Данные успешно получены.' }, type: 'success' });
},
},
getZero: {
request: () => ({
url: 'https://test.com/',
method: 'GET',
tokenName: 'main',
}),
store: {
key: 'zero',
default: false,
},
},
postAuth: () => ({
url: 'https://test.com/',
method: 'GET',
tokenName: 'main',
}),
},
messages: {
codes: {
403: {
title: 'errors.error403',
},
default: {
title: 'errors.errorTitle',
},
},
},
});
App.tsx
import * as React from 'react';
import { useRoutes } from 'react-router-dom';
import { routes } from 'src/navigation/routes';
import { Loader, Notifications } from 'src/modules';
export const App: React.FC = () => {
const page = useRoutes(routes);
return (
<div>
<Loader />
<Notifications />
{page}
</div>
);
};
Loader.tsx
import * as React from 'react';
import requestManager from '../api';
import { LoaderComponent, LoaderComponentProps } from 'src/components';
export const Loader: React.FC<LoaderComponentProps> = (props) => {
const { active } = React.useSyncExternalStore(requestManager.connectLoader.subscribe, requestManager.connectLoader.state); // react v >= 18
if (!active) return null;
return <LoaderComponent {...props} active={active} />;
};
App.tsx
import * as React from 'react';
import { useRoutes } from 'react-router-dom';
import { routes } from 'src/navigation/routes';
import { Loader, Notifications } from 'src/modules';
export const App: React.FC = () => {
const page = useRoutes(routes);
return (
<div>
<Loader />
<Notifications />
{page}
</div>
);
};
Notifications.tsx
import * as React from 'react';
import requestManager from '../api';
import { useTranslation } from 'react-i18next';
import { Alert, AlertTitle } from '@mui/material';
// For test notification view
// requestManager.sendNotification({ data: { title: 'My title', text: 'Descr' } });
export const Notifications: React.FC = () => {
const notifications = React.useSyncExternalStore(requestManager.connectNotifications.subscribe, requestManager.connectNotifications.state); // react v >= 18
const { t } = useTranslation();
return (
<div>
{notifications.map(({ id, type, data, response, drop }) => (
<Alert
key={id}
severity={type}
onClose={() => {
drop(id);
}}
>
<AlertTitle>{t(data?.title || '', { errorCode: response?.status || '' })}</AlertTitle>
{data?.text ? t(data.text) : null}
</Alert>
))}
</div>
);
};
auth.hook.ts
import requestManager from '../api';
import * as React from 'react';
import { useNavigate } from 'react-router-dom';
export const useAuth = () => {
const navigate = useNavigate();
return {
login: React.useCallback(
async (props: { email: string; password: string }) => {
const { validData } = await requestManager.namedRequest('postAuth', props);
if (validData) {
requestManager.setToken('main', validData.token);
navigate('/dashboard');
}
},
[navigate],
),
logout: React.useCallback(() => {
requestManager.restart();
navigate('/');
}, [navigate]),
};
};
LoginPage.tsx
import * as React from 'react';
import { useAuth } from 'src/hooks';
export const LoginPage: React.FC = () => {
const { login } = useAuth();
return (
<div>
<h1>Login Page</h1>
<button onClick={() => { login({ email, password }) }}>Login</button>
</div>
);
};
TasksPage.tsx
import { HttpsStore, ScenariosStore, useNeeds } from 'library-react-hooks';
import * as React from 'react';
import { ITask } from 'src/types';
export const TasksPage: React.FC = () => {
const { tasks } = React.useSyncExternalStore(requestManager.subscribe, requestManager.state); // react v >= 18
React.useEffect(() => {
requestManager.needAction('tasks', NeedsActionTypes.request, 1);
}, []);
const { store } = useNeeds(['tasks']); // GET укажите какие данные нужно подгрузить на этой странице
const onAdd = React.useCallback(async (task: Omit<ITask, 'id'>) => {
await requestManager.namedRequest('postTask', task); // POST, PUT, PATCH
// ответ можно обработать тут или в afterRequest
}, []);
const freeRequest = async () => {
const { dataJson, response } = await requestManager.getModule('request').fetch('https://test.com/3');
if (response?.ok) {
// do something
} else {}
};
return (
<div>
<h1>Tasks Page</h1>
<ul>
{store?.tasks?.map(({ id, title }) => (
<div key={id}>{title}</div>
))}
</ul>
<button onClick={() => { onAdd({ title: 'new task' }) }}>Add task</button>
</div>
);
};
Contributions, issues and feature requests are welcome. Check the contributing guide.
Copyright © 2025 Bystrova Ann.
This project is MIT licensed.
Bystrova Ann - ann.bystrova96@mail.ru
FAQs
Allows you to write less boilerplate code when making API requests.
The npm package request-store-manager receives a total of 13 weekly downloads. As such, request-store-manager popularity was classified as not popular.
We found that request-store-manager demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
OpenAI rotated macOS signing certificates after a malicious Axios package reached its CI pipeline in a broader software supply chain attack.

Security News
Open source is under attack because of how much value it creates. It has been the foundation of every major software innovation for the last three decades. This is not the time to walk away from it.

Security News
Socket CEO Feross Aboukhadijeh breaks down how North Korea hijacked Axios and what it means for the future of software supply chain security.