WayrApp Backend & Ecosystem Documentation - v1.0.0
    Preparing search index...

    Class UserService

    UserService - Core business logic service for user management operations

    Provides comprehensive user management functionality including authentication, profile management, and account lifecycle operations. Acts as the business logic layer between controllers and the data repository.

    UserService

    const userRepository = new UserRepository(prisma);
    const userService = new UserService(userRepository);

    // Create a new user
    const newUser = await userService.createUser({
    email: 'user@example.com',
    username: 'johndoe',
    role: 'student'
    });

    // Authenticate user
    const authenticatedUser = await userService.verifyUserByEmail(
    'user@example.com',
    'password123'
    );
    Index

    Constructors

    Methods

    • Retrieves a user by their unique identifier

      Parameters

      • id: string

        The unique user identifier

      Returns Promise<null | User>

      Promise resolving to user object or null if not found

      When database operation fails

      const user = await userService.findById('user-123');
      if (user) {
      console.log(`Found user: ${user.email}`);
      }
    • Retrieves a user by their email address

      Parameters

      • email: string

        The user's email address

      Returns Promise<null | User>

      Promise resolving to user object or null if not found

      When database operation fails

      const user = await userService.findByEmail('user@example.com');
      
    • Retrieves a user by their username

      Parameters

      • username: string

        The user's username

      Returns Promise<null | User>

      Promise resolving to user object or null if not found

      When database operation fails

      const user = await userService.findByUsername('johndoe');
      
    • Creates a new user account without password (for OAuth or external auth)

      Parameters

      • userData: CreateUserDto

        User data for account creation

        • email

          User's email address (required)

        • username

          User's username (optional)

        • country_code

          User's country code (optional)

        • profile_picture_url

          User's profile picture URL (optional)

        • role

          User's role (defaults to 'student')

      Returns Promise<User>

      Promise resolving to the created user object

      When email or username already exists (409 CONFLICT)

      When database operation fails (500 INTERNAL_SERVER_ERROR)

      const newUser = await userService.createUser({
      email: 'user@example.com',
      username: 'johndoe',
      country_code: 'US',
      role: 'student'
      });
    • Updates existing user information

      Parameters

      • id: string

        The unique user identifier

      • updates: UpdateUserDto

        Object containing fields to update

        • username

          New username (optional)

        • country_code

          New country code (optional)

        • profile_picture_url

          New profile picture URL (optional)

        • is_active

          Account active status (optional)

        • role

          User role (optional)

      Returns Promise<User>

      Promise resolving to the updated user object

      When user is not found (404 NOT_FOUND)

      When username already taken (409 CONFLICT)

      When database operation fails (500 INTERNAL_SERVER_ERROR)

      const updatedUser = await userService.updateUser('user-123', {
      username: 'newusername',
      country_code: 'CA'
      });
    • Creates a new user account with password hashing for standard registration

      Parameters

      • userData: CreateUserDto & { password: string }

        User data including password

        • email

          User's email address (required)

        • password

          User's plain text password (required)

        • username

          User's username (optional)

        • country_code

          User's country code (optional)

        • profile_picture_url

          User's profile picture URL (optional)

        • role

          User's role (defaults to 'student')

        • password: string

          User's plain text password (required)

      Returns Promise<User>

      Promise resolving to the created user object (without password hash)

      When email or username already exists (409 CONFLICT)

      When database operation fails (500 INTERNAL_SERVER_ERROR)

      const newUser = await userService.createUserWithPassword({
      email: 'user@example.com',
      password: 'SecurePass123!',
      username: 'johndoe',
      role: 'student'
      });
    • Verifies a user's password against the stored hash

      Parameters

      • userId: string

        The unique user identifier

      • password: string

        The plain text password to verify

      Returns Promise<boolean>

      Promise resolving to true if password is valid, false otherwise

      When database operation fails

      const isValid = await userService.verifyPassword('user-123', 'userPassword');
      if (isValid) {
      console.log('Password is correct');
      }
    • Authenticates a user by email and password combination

      Parameters

      • email: string

        The user's email address

      • password: string

        The user's plain text password

      Returns Promise<null | User>

      Promise resolving to user object if credentials are valid, null otherwise

      When database operation fails

      const authenticatedUser = await userService.verifyUserByEmail(
      'user@example.com',
      'password123'
      );
      if (authenticatedUser) {
      // User is authenticated, proceed with login
      console.log(`Welcome ${authenticatedUser.email}`);
      } else {
      // Invalid credentials
      console.log('Invalid email or password');
      }
    • Updates the user's last login timestamp to current time

      Parameters

      • userId: string

        The unique user identifier

      Returns Promise<void>

      Promise that resolves when update is complete This method is designed to be non-blocking and will not throw errors if the update fails, only logging warnings to prevent login flow interruption

      // Called after successful authentication
      await userService.updateLastLogin('user-123');
    • Deactivates a user account by setting is_active to false

      Parameters

      • id: string

        The unique user identifier

      Returns Promise<User>

      Promise resolving to the updated user object

      When user is not found (404 NOT_FOUND)

      When database operation fails (500 INTERNAL_SERVER_ERROR)

      const deactivatedUser = await userService.deactivateUser('user-123');
      console.log(`User ${deactivatedUser.email} has been deactivated`);
    • Activates a user account by setting is_active to true

      Parameters

      • id: string

        The unique user identifier

      Returns Promise<User>

      Promise resolving to the updated user object

      When user is not found (404 NOT_FOUND)

      When database operation fails (500 INTERNAL_SERVER_ERROR)

      const activatedUser = await userService.activateUser('user-123');
      console.log(`User ${activatedUser.email} has been activated`);
    • Checks if a user exists by their unique identifier

      Parameters

      • id: string

        The unique user identifier

      Returns Promise<boolean>

      Promise resolving to true if user exists, false otherwise

      When database operation fails

      const exists = await userService.userExists('user-123');
      if (exists) {
      console.log('User exists in the system');
      }
    • Retrieves a paginated list of users with optional filtering and sorting

      Parameters

      • Optionaloptions: QueryOptions = {}

        Query options for pagination and filtering

        • page

          Page number for pagination

        • limit

          Number of items per page

        • sortBy

          Field to sort by

        • sortOrder

          Sort order

        • filters

          Filters to apply

        • filters.role

          Filter by user role

        • filters.is_active

          Filter by active status

        • filters.search

          Search in email and username

      Returns Promise<PaginatedResult<User>>

      Promise resolving to paginated user results

      When database operation fails (500 INTERNAL_SERVER_ERROR)

      const users = await userService.findAll({
      page: 1,
      limit: 10,
      sortBy: 'created_at',
      sortOrder: 'desc',
      filters: {
      role: 'student',
      is_active: true,
      search: 'john'
      }
      });
      console.log(`Found ${users.data.length} users`);
    • Updates a user's password after verifying their current password

      Parameters

      • userId: string

        The unique user identifier

      • currentPassword: string

        The user's current plain text password

      • newPassword: string

        The new plain text password to set

      Returns Promise<boolean>

      Promise resolving to true when password is successfully updated

      When current password is incorrect (401 UNAUTHORIZED)

      When user is not found (404 NOT_FOUND)

      When database operation fails (500 INTERNAL_SERVER_ERROR)

      try {
      await userService.updatePassword(
      'user-123',
      'oldPassword123',
      'newSecurePassword456!'
      );
      console.log('Password updated successfully');
      } catch (error) {
      if (error.statusCode === 401) {
      console.log('Current password is incorrect');
      }
      }
    • Retrieves a user's profile information without sensitive data

      Parameters

      • id: string

        The unique user identifier

      Returns Promise<null | Omit<User, "password_hash">>

      Promise resolving to user profile or null if not found

      When database operation fails Returns user data safe for client consumption, excluding password hash and normalizing null values to empty strings for optional fields

      const profile = await userService.getUserProfile('user-123');
      if (profile) {
      console.log(`Profile for: ${profile.email}`);
      console.log(`Username: ${profile.username || 'Not set'}`);
      console.log(`Active: ${profile.is_active}`);
      }