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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@dimrev4/user-core

v0.2.7

Published

OpenAPI client for @dimrev4/user-core

Readme

@dimrev4/user-core SDK

TypeScript SDK for User Core API - Comprehensive client for user management, authentication, groups, and permissions in fitness applications.

🚀 Features

  • 🔐 JWT Authentication, Registration, Logout

  • 👥 Full User CRUD with self-service endpoints

  • 🏢 Group management with membership control

  • 🛡️ Granular permissions (system + group-level)

  • 📊 Pagination, filtering, and sorting support

  • 💪 100% TypeScript with full type safety

  • ⚡ Axios-based with interceptors support

📦 Installation

npm install @dimrev4/user-core
# or
yarn add @dimrev4/user-core
# or
pnpm add @dimrev4/user-core

🔧 Quick Start

1. Setup

import {
  Configuration,
  AuthV1Api,
  UserV1Api,
  GroupV1Api,
} from '@dimrev4/user-core';

const config = new Configuration({
  basePath: 'https://api.yourdomain.com',
});

const authApi = new AuthV1Api(config);
const userApi = new UserV1Api(config);
const groupApi = new GroupV1Api(config);

2. Authentication

// Login
const loginResponse = await authApi.authV1ControllerLogin({
  email: '[email protected]',
  password: 'securePassword123!',
});

const { user, accessToken } = loginResponse.data;

// Create authenticated client
const authConfig = new Configuration({
  basePath: 'https://api.yourdomain.com',
  accessToken,
});

const authenticatedUserApi = new UserV1Api(authConfig);

3. User Management

// Get current user
const me = await authenticatedUserApi.userV1ControllerGetUserSelf();
console.log('Current user:', me.data.username);

// List users with pagination
const users = await authenticatedUserApi.userV1ControllerGetUsers({
  limit: 10,
  offset: 0,
  orderBy: 'createdAt',
});

// Create user
const newUser = await authenticatedUserApi.userV1ControllerCreate({
  email: '[email protected]',
  username: 'newuser',
  password: 'SecurePass123!',
});

4. Group Management

// Create group
const group = await groupApi.groupV1ControllerCreate({
  name: 'Development Team',
  userId: 'creator-user-id',
});

const groupId = group.data.id;

// Add user to group
const groupMembersApi = new GroupV1Api(authConfig);
await groupMembersApi.groupMembersV1ControllerAddUserToGroup(
  groupId,
  'user-id',
  {
    canCreate: true,
    canRead: true,
    canUpdate: true,
    canDelete: false,
  },
);

🏗️ API Overview

Authentication (AuthV1Api)

  • POST /api/auth/v1/login - Authenticate user
  • POST /api/auth/v1/register - Create new account
  • POST /api/auth/v1/logout - Invalidate session
  • POST /api/auth/v1/get-me - Get current user info

User Management (UserV1Api)

  • GET /api/users/v1 - List users (paginated)
  • GET /api/users/v1/self - Get current user
  • GET /api/users/v1/{id} - Get user by ID
  • POST /api/users/v1 - Create user
  • PUT /api/users/v1/self - Update own profile
  • DELETE /api/users/v1/self - Delete own account

Group Management (GroupV1Api)

  • GET /api/groups/v1 - List all groups
  • GET /api/groups/v1/self - Get user's groups
  • POST /api/groups/v1 - Create group
  • PUT /api/groups/v1/{id} - Update group
  • DELETE /api/groups/v1/{id} - Delete group

Group Members (GroupMembersV1Api)

  • POST /api/groups/members/v1/{groupId}/{userId} - Add user to group
  • PUT /api/groups/members/v1/{groupId}/{userId} - Update permissions
  • DELETE /api/groups/members/v1/{groupId}/{userId} - Remove user

🔐 Permissions

System Permissions

{
  "user": {
    "readAll": true, // List all users
    "readOne": true, // View specific user
    "create": true, // Create users
    "update": true, // Update any user
    "delete": true // Delete any user
  },
  "group": {
    "readAll": true, // List all groups
    "create": true, // Create groups
    "update": true, // Update groups
    "delete": true // Delete groups
  }
}

Group Permissions

{
  "isRoot": true, // Full group admin
  "canCreate": true, // Create group content
  "canRead": true, // View group content
  "canUpdate": true, // Modify group content
  "canDelete": true // Delete group content
}

🧪 Error Handling

import { AxiosError } from 'axios';

try {
  const users = await authenticatedUserApi.userV1ControllerGetUsers();
} catch (error) {
  if (error instanceof AxiosError) {
    switch (error.response?.status) {
      case 400:
        console.error('Validation failed:', error.response.data.message);
        break;
      case 401:
        console.error('Unauthorized:', error.response.data.message);
        // Handle token refresh or redirect
        break;
      case 403:
        console.error('Forbidden: Insufficient permissions');
        break;
      case 404:
        console.error('Resource not found');
        break;
      case 409:
        console.error('Conflict:', error.response.data.message);
        break;
      default:
        console.error('API Error:', error.message);
    }
  }
}

⚙️ Advanced Configuration

Custom Axios Instance

import axios from 'axios';
import { Configuration, UserV1Api } from '@dimrev4/user-core';

const axiosInstance = axios.create({
  timeout: 15000,
});

// Add auth token automatically
axiosInstance.interceptors.request.use((config) => {
  const token = localStorage.getItem('access_token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

const config = new Configuration({});
const userApi = new UserV1Api(config, undefined, axiosInstance);

Environment Setup

const config = new Configuration({
  basePath:
    process.env.NODE_ENV === 'production'
      ? 'https://api.yourdomain.com'
      : 'http://localhost:3000/api',
  timeout: 10000,
  accessToken: process.env.API_TOKEN,
});

🌍 Pagination & Filtering

const users = await authenticatedUserApi.userV1ControllerGetUsers({
  // Pagination
  offset: 0,
  limit: 25,

  // Filtering
  username: 'john',
  email: 'company.com',

  // Sorting
  orderBy: 'createdAt', // createdAt, updatedAt, username, email
});

console.log(`${users.data.totalItems} users found`);
console.log(`Page ${users.data.currentPage} of ${users.data.totalPages}`);

🧪 Testing

Mock with MSW

import { rest } from 'msw';
import { setupServer } from 'msw/node';
import { UserV1Api } from '@dimrev4/user-core';

const server = setupServer(
  rest.get('*/api/users/v1/self', (req, res, ctx) => {
    return res(
      ctx.status(200),
      ctx.json({
        id: '1',
        username: 'testuser',
        email: '[email protected]',
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        deletedAt: null,
        userToGroup: [],
      }),
    );
  }),
);

beforeAll(() => server.listen());
afterAll(() => server.close());

test('gets current user', async () => {
  const config = new Configuration({ basePath: 'http://localhost' });
  const api = new UserV1Api(config);

  const response = await api.userV1ControllerGetUserSelf();
  expect(response.data.username).toBe('testuser');
});

🚨 Common Issues

| Issue | Solution | | ---------------------- | --------------------------------------- | | 401 Unauthorized | Set accessToken in Configuration | | 403 Forbidden | Check required permissions for endpoint | | CORS Error | Configure API CORS or use proxy in dev | | Token not sent | Use accessToken parameter in config | | Validation Error (400) | Check request body against DTO schema |

Token Management Helper

class AuthManager {
  static login(email: string, password: string, config: Configuration) {
    const authApi = new AuthV1Api(config);
    return authApi
      .authV1ControllerLogin({ email, password })
      .then((response) => {
        config.accessToken = response.data.accessToken;
        localStorage.setItem('access_token', response.data.accessToken);
        return response.data.user;
      });
  }

  static logout(config: Configuration) {
    localStorage.removeItem('access_token');
    config.accessToken = '';
  }

  static getAuthenticatedConfig(baseUrl: string): Configuration {
    return new Configuration({
      basePath: baseUrl,
      accessToken: localStorage.getItem('access_token') || '',
    });
  }
}

// Usage
const config = AuthManager.getAuthenticatedConfig('https://api.example.com');
const userApi = new UserV1Api(config);

📊 TypeScript Types

Key interfaces for type safety:

interface CreateUserRequestDto {
  email: string;
  username: string;
  password: string;
}

interface UserDetailsDto {
  id: string;
  username: string;
  email: string;
  createdAt: string;
  updatedAt: string;
  deletedAt: string | null;
  userToGroup: UserToGroupDetailsDto[];
}

interface GroupDetailsDto {
  id: string;
  name: string;
  createdAt: string;
  updatedAt: string;
  deletedAt: string | null;
  userToGroup: UserToGroupDetailsDto[];
}

interface UserToGroupDetailsDto {
  groupId: string;
  userId: string;
  canCreate: boolean;
  canRead: boolean;
  canUpdate: boolean;
  canDelete: boolean;
  isRoot: boolean;
  group: GroupDto;
  user: UserDto;
}

🔗 Resources

  • API Docs: Available at /api endpoint (Swagger UI)
  • Repository: GitHub
  • Issues: GitHub Issues
  • License: Unlicense

🤝 Contributing

  1. Fork the repository
  2. Update OpenAPI spec for new features
  3. Run npm run generate to rebuild SDK
  4. Submit pull request with tests

Auto-generated from User Core API v0.0 | Last Updated: Oct 2025