Skip to main content

User Filter

Get a specific user by filtering on username or email. This is useful for checking if a user exists, retrieving user details, and managing user group memberships.

Definition​

db(databaseName: string)
.user(userFilter: TUserFilter): IUser;

Where TUserFilter is defined as:

type TUserFilter = Partial<TUser>;

type TUser = {
userName: string | null;
email: string | null;
};

And IUser provides the following methods:

interface IUser {
// Retrieves the user's information
info(): Promise<Result<TUserMeResponse | null>>;

// Lists all groups associated with the user
listGroup(): Promise<Result<TGroupListByUserResponse>>;

// Checks if the user exists in the system
exist(): Promise<Result<boolean>>;
}

type TUserMeResponse = {
id: bigint;
userName: string | null;
email: string | null;
};

// Array of group names the user belongs to
type TGroupListByUserResponse = string[];

Parameters​

  • userFilter (TUserFilter, required): An object containing filter criteria:
    • userName (string | null, optional): Filter by username
    • email (string | null, optional): Filter by email address

Returns​

  • IUser: A user object with methods to query user information and group memberships:
    • info(): Get user details (id, userName, email)
    • listGroup(): Get array of group names the user belongs to
    • exist(): Check if the user exists in the system

Example​

Basic Usage​

const dbTest = zkdb.db('db_test');

// Filter user by username
const user = dbTest.user({ userName: 'alice' });

// Check if user exists
const result = await user.exist();

if (result.isOk()) {
const exists = result.unwrap();
console.log(`User alice exists: ${exists}`);
} else {
console.error('Error checking user:', result.unwrapErr());
}

// Using unwrapOr for concise code
const exists = (await dbTest.user({ userName: 'alice' }).exist()).unwrapOr(false);

Filter by Email​

const dbTest = zkdb.db('db_test');

// Filter user by email
const userByEmail = dbTest.user({ email: '[email protected]' });

// Check if user exists
const exists = (await userByEmail.exist()).unwrapOr(false);
console.log(`User with email [email protected] exists: ${exists}`);

Get User Information​

const dbTest = zkdb.db('db_test');

// Get user by username
const user = dbTest.user({ userName: 'alice' });

// Get user information
const infoResult = await user.info();

if (infoResult.isOk()) {
const userInfo = infoResult.unwrap();
if (userInfo) {
console.log(`User ID: ${userInfo.id}`);
console.log(`Username: ${userInfo.userName}`);
console.log(`Email: ${userInfo.email}`);
} else {
console.log('User not found');
}
} else {
console.error('Error fetching user info:', infoResult.unwrapErr());
}

List User's Groups​

const dbTest = zkdb.db('db_test');

// Get user by username
const user = dbTest.user({ userName: 'alice' });

// List all groups the user belongs to
const groupsResult = await user.listGroup();

if (groupsResult.isOk()) {
const groupNames = groupsResult.unwrap();

console.log(`User belongs to ${groupNames.length} groups:`);
groupNames.forEach(groupName => {
console.log(`- ${groupName}`);
});
} else {
console.error('Error fetching groups:', groupsResult.unwrapErr());
}

Combined Filter​

const dbTest = zkdb.db('db_test');

// Filter by both username and email (more specific matching)
const user = dbTest.user({
userName: 'alice',
email: '[email protected]'
});

const exists = (await user.exist()).unwrapOr(false);
console.log(`User with matching username AND email exists: ${exists}`);

Example Result​

{
"id": 1n,
"userName": "alice",
"email": "[email protected]"
}

For listGroup():

["editors", "viewers", "admins"]

Usage in Examples​

Validate User Before Adding to Group​

import { zkdb } from './connection';

const dbTest = zkdb.db('db_test');

async function addUserToGroupSafe(userName: string, groupName: string) {
// First, check if the user exists
const user = dbTest.user({ userName });
const existsResult = await user.exist();

if (existsResult.isErr()) {
console.error('Error checking user existence:', existsResult.unwrapErr());
return false;
}

if (!existsResult.unwrap()) {
console.log(`User ${userName} does not exist`);
return false;
}

// Get user info to get the ID
const infoResult = await user.info();
if (infoResult.isErr() || !infoResult.unwrap()) {
console.error('Could not get user info');
return false;
}

const userInfo = infoResult.unwrap()!;

// Add user to group
const group = dbTest.group(groupName);
const addResult = await group.userAdd([userInfo.id]);

if (addResult.isOk()) {
console.log(`Successfully added ${userName} to ${groupName}`);
return true;
} else {
console.error('Error adding user to group:', addResult.unwrapErr());
return false;
}
}

await addUserToGroupSafe('alice', 'editors');

Check User's Group Membership​

import { zkdb } from './connection';

const dbTest = zkdb.db('db_test');

async function isUserInGroup(userName: string, groupName: string): Promise<boolean> {
const user = dbTest.user({ userName });

const groupsResult = await user.listGroup();

if (groupsResult.isErr()) {
console.error('Error fetching groups:', groupsResult.unwrapErr());
return false;
}

const groupNames = groupsResult.unwrap();
return groupNames.includes(groupName);
}

const isMember = await isUserInGroup('alice', 'editors');
console.log(`Alice is ${isMember ? '' : 'not '}a member of editors group`);

Notes​

  • Exact Matching: The filter uses exact matching, not partial/wildcard matching
  • Case Sensitivity: Filters are case-sensitive
  • Null Values: Both userName and email can be null in user records
  • Synchronous Return: The user() method returns an IUser object immediately; async operations happen when calling info(), listGroup(), or exist()
  • For Listing All Users: Use userList() to get a paginated list of all users

See Also​

  • User List: userList() - Get a paginated list of all users
  • Group Management: group() - Manage group operations
  • Group List: groupList() - List all groups in a database
  • Database Info: info() - Get database information including owner