npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@slavahawk/wlist-api

v1.0.11

Published

Typed API client for W-List (admin/customer/root/common)

Readme

W-List API Client

Типизированный API клиент для W-List с поддержкой аутентификации и автоматического обновления токенов.

Установка

npm install @w-list/api

Основные возможности

  • 🔐 Безопасная аутентификация с использованием cookies
  • 🔄 Автоматическое обновление токенов
  • 📝 Полная типизация всех API методов
  • 🛡️ Защита от CSRF атак
  • Очередь запросов при обновлении токенов

Быстрый старт

1. Инициализация аутентификации

import { initializeAuth, AuthService } from '@w-list/api';

// Инициализируем систему аутентификации с расширенной конфигурацией
initializeAuth({
  apiUrl: 'https://api.w-list.ru',
  router, // опционально
  maxRetries: 3,           // Максимум 3 попытки обновления токена
  retryDelay: 1000,        // Задержка 1 секунда между попытками
  refreshThreshold: 5 * 60 * 1000, // Обновлять за 5 минут до истечения
});

// Теперь можно использовать AuthService

2. Вход в систему

import { AuthService } from '@w-list/api';

try {
  const response = await AuthService.login({
    email: '[email protected]',
    password: 'password123'
  });
  
  console.log('Успешный вход:', response);
} catch (error) {
  console.error('Ошибка входа:', error);
}

3. Использование API

import { Admin, Customer, Common } from '@w-list/api';

// Получение списка вин (требует аутентификации)
const wines = await Admin.getWineById(123);

// Получение профиля пользователя
const profile = await AuthService.getMe();

// Выход из системы
await AuthService.logout();

Безопасность

Cookies vs LocalStorage

Система использует cookies вместо localStorage для большей безопасности:

  • HttpOnly (для серверной части)
  • Secure (только HTTPS)
  • SameSite=Strict (защита от CSRF)
  • Автоматическое истечение токенов

Настройки токенов

  • Access Token: 1 час жизни
  • Refresh Token: 7 дней жизни
  • Автоматическое обновление: за 5 минут до истечения

API Методы

Аутентификация

// Вход
AuthService.login(credentials)

// Регистрация
AuthService.register(userData)

// Обновление токена
AuthService.refresh(refreshToken)

// Выход
AuthService.logout()

// Проверка аутентификации
AuthService.isAuthenticated()

// Получение времени истечения токена
AuthService.getTokenExpiration()

// Автоматическое обновление при необходимости
AuthService.refreshIfNeeded()

Управление токенами

import { getToken, setToken, clearTokens, hasValidToken } from '@w-list/api';

// Получение токена
const token = getToken('accessToken');

// Установка токена
setToken('accessToken', 'new-token-value');

// Очистка всех токенов
clearTokens();

// Проверка валидности токена
const isValid = hasValidToken();

Обработка ошибок

import { ApiError } from '@w-list/api';

try {
  await AuthService.login(credentials);
} catch (error) {
  if (error instanceof ApiError) {
    console.error('API ошибка:', error.message);
    console.error('Статус:', error.status);
    console.error('Детали:', error.details);
  }
}

Интеграция с роутером

import { initializeAuth } from '@w-list/api';

// Vue Router
const router = {
  replace: (path: string) => router.push(path)
};

// React Router
const router = {
  replace: (path: string) => navigate(path)
};

// Инициализация
initializeAuth(router, 'https://api.w-list.ru');

Автоматическое обновление токенов

Система автоматически:

  1. Перехватывает 401 ошибки
  2. Пытается обновить токен
  3. Повторяет исходный запрос
  4. Очищает токены при неудаче
// Запрос будет автоматически повторен после обновления токена
const wines = await Admin.getAll({ request: filter });

Типы

Все API методы полностью типизированы. Импортируйте типы напрямую из generated файлов:

import type { 
  AuthRequest, 
  AuthResponse, 
  GetMeResponse 
} from '@w-list/api/generated/common/common.gen';

Конфигурация

Переменные окружения

# URL API
VITE_API_URL=https://api.w-list.ru
API_URL=https://api.w-list.ru

Настройка Orval

Конфигурация для генерации типов находится в orval.config.ts:

export default defineConfig({
  common: {
    input: { target: './openapi/wlist.openapi.json', filters: { tags: ['Auth'] } },
    // ...
  },
  // ...
});

Разработка

Генерация API

# Получение OpenAPI спецификации
npm run api:fetch

# Генерация типов и методов
npm run api:gen

# Сборка
npm run build

Структура проекта

src/
├── api/
│   ├── http.ts          # HTTP клиент с интерцепторами
│   ├── token.ts         # Работа с токенами
│   ├── helpers.ts       # Вспомогательные функции
│   └── types.ts         # Типы для роутера
├── generated/           # Сгенерированные API методы
│   ├── admin/
│   ├── customer/
│   ├── common/
│   └── root/
├── services/
│   └── auth.service.ts  # Сервис аутентификации
└── types.ts            # Общие типы

Лицензия

MIT