The getUserById tool retrieves a single user record by its document ID from the Firebase/Firestore database.
tools/getUserById.js
Retrieves a specific user by document ID. The user is retrieved from the Firestore path: /Accounts/{accountId}/Users/{userId}.
{
userId: string; // REQUIRED: User document ID
}
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
userId |
string | Yes | - | Firestore document ID of the user |
{
user: User | null;
}
{
id: string; // Firestore document ID
path: string; // Full Firestore path
userId: number; // Unique user ID
email: string; // User email address
name: string; // User name
role: string; // Role reference or ID
active: boolean; // Whether user is active
// ... other user fields
}
// Get a specific user by ID
const result = await getUserById(context, {
userId: "user123"
});
if (result.user) {
console.log(result.user.name); // User name
console.log(result.user.email); // User email
} else {
console.log("User not found");
}
const result = await getUserById(context, {
userId: "user123"
});
if (result.user) {
if (result.user.active) {
console.log(`${result.user.name} (${result.user.email}) is active`);
} else {
console.log(`${result.user.name} is inactive`);
}
} else {
console.log("User does not exist");
}
The tool transforms the Firestore document by:
id and full pathreturn {
user: {
id: docSnap.id,
path: docSnap.ref.path,
...docSnap.data(),
},
};
The tool validates that userId is provided:
if (!userId) {
throw new Error("The 'userId' parameter is required.");
}
If the user document doesn’t exist, the tool returns { user: null } instead of throwing an error.
| Error | Cause | Solution |
|---|---|---|
| “The ‘userId’ parameter is required.” | Missing userId | Provide userId in params |
| “Failed to fetch user with id [id].” | Firestore error | Check Firebase connection and permissions |
Errors are logged with the user ID and re-thrown:
catch (error) {
console.error(`Error fetching user with id ${userId}:`, error);
throw new Error(`Failed to fetch user with id ${userId}.`);
}
getDoc() for efficient single document retrieval/Accounts/{accountId}/Users/{userId}
- userId: number
- email: string
- name: string
- role: string
- active: boolean