API Reference - User API

Working with Users using Collections

Interactive Examples

Try these examples with your saved connection. If you haven't connected yet, visit the Try It Out page first.

Get Current User

Fetch the currently logged-in user using API filter.

const users = api.collections.user;
const username = api.getActiveConnection().user;

// Fetch with username filter
await users.fetch({ username } as any);
const currentUser = users.first();

if (currentUser) {
  console.log('Logged in as:', currentUser.username);
  console.log('Email:', currentUser.email);
  console.log('Is superuser:', currentUser.is_superuser);
}

Get First 10 Users

Fetch the first 10 users using Collections.

const users = api.collections.user;
await users.fetch({ limit: 10 });
console.log('Users:', users.models);
console.log('Has more:', users.hasMore);

Find User by Username

Search for a specific user by their username using API filter.

const users = api.collections.user;
// Fetch with username filter
await users.fetch({ username: 'admin' } as any);
const user = users.first();

if (user) {
  console.log('User found:', user.email);
}

Filter Active Users

Fetch users and filter for only active accounts.

const users = api.collections.user;
await users.fetch({ limit: 100 });

const activeUsers = users.filter(u => u.is_active);
console.log(`Found ${activeUsers.length} active users`);

Get All Superusers

Find all users with superuser privileges.

const users = api.collections.user;
await users.fetch({ limit: 100 });

const superusers = users.filter(u => u.is_superuser);
console.log(`Found ${superusers.length} superusers`);

UserCollection

The UserCollection class provides a Backbone.js-inspired interface for managing user data with built-in indexing, pagination, and array operations.

Accessing the UserCollection

import { initializeSGERP } from 'sgerp-frontend-lib';

const api = initializeSGERP({
  activeConnection: 'admin@localhost',
  connections: {
    'admin@localhost': {
      id: 'admin@localhost',
      environment: 'localhost',
      user: 'admin',
      password: 'admin123',
      baseUrl: 'https://sgerp-stage.d.gcdev.swatrider.com',
    },
  },
});

// Access the UserCollection
const users = api.collections.user;

Common User Operations

Get Current User

Get the currently logged-in user using API filter:

const users = api.collections.user;
const username = api.getActiveConnection().user;

// Fetch with username filter
await users.fetch({ username } as any);
const currentUser = users.first();

if (currentUser) {
  console.log('Logged in as:', currentUser.username);
  console.log('Email:', currentUser.email);
  console.log('Is superuser:', currentUser.is_superuser);
}

Check if User is Active

Check if the current user is active:

const users = api.collections.user;
const username = api.getActiveConnection().user;

// Fetch current user
await users.fetch({ username } as any);
const currentUser = users.first();

if (currentUser?.is_active) {
  console.log('User is active');
} else {
  console.log('User is inactive or not found');
}

Get User by ID

Find a specific user by their ID:

const users = api.collections.user;

// Fetch with ID filter
await users.fetch({ id: 123 } as any);
const user = users.first();

if (user) {
  console.log('User found:', user.username);
  console.log('Email:', user.email);
}

Get All Users

Fetch and work with user collections:

const users = api.collections.user;

// Fetch first page
await users.fetch({ limit: 10 });
console.log('Total users:', users.length);
console.log('Has more:', users.hasMore);

// Iterate through users
users.forEach(user => {
  console.log(user.username, user.email);
});

// Fetch all users
await users.fetchAll();
console.log('All users loaded:', users.length);

Types

User

interface User {
  id: number;
  last_login: string;
  is_superuser: boolean;
  username: string;
  first_name: string;
  last_name: string;
  email: string;
  is_staff: boolean;
  is_active: boolean;
  date_joined: string;
  created_at: string;
  modified_at: string;
  external_id: string | null;
  options: Record<string, any>;
  organization_id: number | null;
  phone: string | null;
  created_by_id: number | null;
}

SGERPMeta

Pagination metadata for list responses.

interface SGERPMeta {
  has_more: boolean;
  next: string | null;
  next_offset: number | null;
}

SGERPListResponse

Generic list response wrapper.

interface SGERPListResponse<T> {
  meta: SGERPMeta;
  objects: T[];
}

Complete Example

import { initializeSGERP, type User } from 'sgerp-frontend-lib';

// Initialize the library
const api = initializeSGERP({
  activeConnection: 'admin@staging',
  connections: {
    'admin@staging': {
      id: 'admin@staging',
      environment: 'staging',
      user: 'admin',
      password: 'your-password',
      baseUrl: 'https://sgerp-stage.d.gcdev.swatrider.com',
    },
  },
});

// Get current user
async function getCurrentUser() {
  const users = api.collections.user;
  const username = api.getActiveConnection().user;

  await users.fetch({ username } as any);
  const currentUser = users.first();

  if (currentUser?.is_active) {
    console.log('Logged in as:', currentUser.username);
    console.log('Email:', currentUser.email);
    console.log('Is admin:', currentUser.is_superuser);
  } else {
    console.log('User not active or not found');
  }
}

// Get user by ID
async function getUserById(userId: number) {
  const users = api.collections.user;

  await users.fetch({ id: userId } as any);
  const user = users.first();

  if (user) {
    console.log('Found user:', {
      id: user.id,
      username: user.username,
      email: user.email,
      active: user.is_active,
    });
  } else {
    console.log('User not found');
  }
}

// List all users with pagination
async function listAllUsers() {
  const users = api.collections.user;

  // Fetch first page
  await users.fetch({ limit: 20 });
  console.log(`Loaded ${users.length} users (has more: ${users.hasMore})`);

  users.forEach(user => {
    console.log(`  - ${user.username} (${user.email})`);
  });

  // Load all pages
  while (users.hasMore) {
    await users.fetchNext();
  }

  console.log(`Total users: ${users.length}`);
}

// Filter users (client-side)
async function getActiveUsers() {
  const users = api.collections.user;
  await users.fetchAll();

  const activeUsers = users.filter(u => u.is_active);
  console.log(`Found ${activeUsers.length} active users`);

  return activeUsers;
}

// Run examples
await getCurrentUser();
await getUserById(1);
await listAllUsers();
await getActiveUsers();

Error Handling

import { getCurrentUser, APIError } from 'sgerp-frontend-lib';

try {
  const user = await getCurrentUser();
  console.log('User:', user);
} catch (error) {
  if (error instanceof APIError) {
    if (error.status === 401) {
      console.error('Authentication failed - check credentials');
    } else if (error.status === 404) {
      console.error('User not found');
    } else {
      console.error('API error:', error.message);
    }
  } else {
    console.error('Unknown error:', error);
  }
}