@supernick135/face-scanner-client
Version:
Node.js client library for ZKTeco face scanning devices integration with comprehensive API support
297 lines (248 loc) ⢠9.93 kB
JavaScript
/**
* Biometric Management Example - Face Scanner API Client
* This example shows how to manage biometric users and data
*/
const { BiometricClient } = require('../lib');
async function biometricManagementExample() {
console.log('š¤ Face Scanner API - Biometric Management Example');
// Create biometric client
const bioClient = new BiometricClient({
baseURL: 'http://localhost:9999',
apiKey: 'your-api-key-here' // Replace with your actual API key
});
try {
// 1. Get biometric statistics
console.log('\nš Getting biometric statistics...');
const stats = await bioClient.getBiometricStats();
console.log('Biometric stats:', stats);
// 2. Get all users
console.log('\nš„ Getting biometric users...');
const users = await bioClient.getUsers({ limit: 10 });
console.log(`Found ${users.length} biometric users:`);
users.forEach(user => {
console.log(` - ${user.name} (${user.id}) - Department: ${user.department || 'N/A'}`);
});
// 3. Create a new user (example)
console.log('\nā Creating new user...');
const newUserData = {
id: 'USER_' + Date.now(),
name: 'John Doe',
email: 'john.doe@example.com',
department: 'Engineering',
employeeId: 'EMP001'
};
try {
const newUser = await bioClient.createUser(newUserData);
console.log('ā
User created:', newUser);
// 4. Get user details
console.log('\nš Getting user details...');
const userDetails = await bioClient.getUser(newUser.id);
console.log('User details:', userDetails);
// 5. Get user templates
console.log('\nš Getting user templates...');
const templates = await bioClient.getUserTemplates(newUser.id);
console.log(`User has ${templates.length} biometric templates`);
// 6. Get user photos
console.log('\nš· Getting user photos...');
const photos = await bioClient.getUserPhotos(newUser.id);
console.log(`User has ${photos.length} photos`);
// 7. Update user information
console.log('\nāļø Updating user...');
const updatedUser = await bioClient.updateUser(newUser.id, {
department: 'Research & Development',
title: 'Senior Engineer'
});
console.log('ā
User updated:', updatedUser);
// 8. Get user activity
console.log('\nš Getting user activity...');
const activity = await bioClient.getUserActivity(newUser.id, {
startDate: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString(), // Last 7 days
limit: 10
});
console.log(`User activity (${activity.length} events):`);
activity.forEach(event => {
console.log(` - ${event.type} at ${event.timestamp} from device ${event.deviceId}`);
});
// 9. Delete user (cleanup)
console.log('\nšļø Cleaning up - deleting test user...');
await bioClient.deleteUser(newUser.id);
console.log('ā
Test user deleted');
} catch (userError) {
console.log('ā User operations error:', userError.message);
}
// 10. Search users
console.log('\nš Searching users...');
const searchResults = await bioClient.searchUsers('engineer', { limit: 5 });
console.log(`Search results (${searchResults.length}):`);
searchResults.forEach(user => {
console.log(` - ${user.name} (${user.department})`);
});
} catch (error) {
console.error('ā Error:', error.message);
console.error('Details:', error.response?.data || error);
}
}
// Example: Bulk user operations
async function bulkOperationsExample() {
console.log('\nš¦ Bulk Operations Example');
const bioClient = new BiometricClient({
baseURL: 'http://localhost:9999',
apiKey: 'your-api-key-here'
});
try {
// Create multiple users
const bulkUsers = [
{
id: 'BULK_001',
name: 'Alice Smith',
department: 'Marketing',
email: 'alice@example.com'
},
{
id: 'BULK_002',
name: 'Bob Johnson',
department: 'Sales',
email: 'bob@example.com'
},
{
id: 'BULK_003',
name: 'Carol Brown',
department: 'HR',
email: 'carol@example.com'
}
];
console.log('ā Creating bulk users...');
const bulkCreateResult = await bioClient.bulkCreateUsers(bulkUsers);
console.log(`ā
Created ${bulkCreateResult.success.length} users`);
if (bulkCreateResult.errors.length > 0) {
console.log(`ā Failed to create ${bulkCreateResult.errors.length} users`);
}
// Update users
const bulkUpdates = bulkUsers.map(user => ({
id: user.id,
title: 'Team Member',
status: 'active'
}));
console.log('āļø Bulk updating users...');
const bulkUpdateResult = await bioClient.bulkUpdateUsers(bulkUpdates);
console.log(`ā
Updated ${bulkUpdateResult.success.length} users`);
// Export users
console.log('š¤ Exporting users...');
const exportData = await bioClient.exportUsers({
format: 'json',
includePhotos: false,
includeTemplates: false
});
console.log(`š Exported ${exportData.users.length} users to ${exportData.format} format`);
// Clean up - delete bulk users
console.log('šļø Cleaning up bulk users...');
const userIds = bulkUsers.map(user => user.id);
const bulkDeleteResult = await bioClient.bulkDeleteUsers(userIds);
console.log(`ā
Deleted ${bulkDeleteResult.success.length} users`);
} catch (error) {
console.error('ā Bulk operations error:', error.message);
}
}
// Example: Synchronization
async function synchronizationExample() {
console.log('\nš Synchronization Example');
const bioClient = new BiometricClient({
baseURL: 'http://localhost:9999',
apiKey: 'your-api-key-here'
});
try {
// Get devices first
const devices = await bioClient.getDevices();
console.log(`Found ${devices.length} devices for synchronization`);
if (devices.length > 0) {
const deviceId = devices[0].id;
// Sync specific device
console.log(`š Syncing device: ${deviceId}`);
const syncResult = await bioClient.syncDevice(deviceId);
console.log('Sync result:', syncResult);
// Check sync status
console.log('š Checking sync status...');
const syncStatus = await bioClient.getSyncStatus(deviceId);
console.log('Sync status:', syncStatus);
// Sync all devices
console.log('š Syncing all devices...');
const allSyncResults = await bioClient.syncAllDevices();
allSyncResults.forEach(result => {
console.log(`Device ${result.deviceId}: ${result.success ? 'ā
' : 'ā'} ${result.error || 'Success'}`);
});
}
} catch (error) {
console.error('ā Synchronization error:', error.message);
}
}
// Example: Enrollment workflow
async function enrollmentWorkflowExample() {
console.log('\nš Enrollment Workflow Example');
const bioClient = new BiometricClient({
baseURL: 'http://localhost:9999',
apiKey: 'your-api-key-here'
});
try {
const userId = 'ENROLL_TEST_' + Date.now();
const deviceId = 'PYA8244800545'; // Replace with actual device ID
// 1. Create user for enrollment
console.log('š¤ Creating user for enrollment...');
const user = await bioClient.createUser({
id: userId,
name: 'Enrollment Test User',
department: 'Test'
});
console.log('ā
User created for enrollment');
// 2. Start enrollment process
console.log('š Starting enrollment...');
const enrollment = await bioClient.startEnrollment(userId, deviceId);
console.log('Enrollment started:', enrollment.id);
// 3. Monitor enrollment status
console.log('š Monitoring enrollment status...');
let enrollmentComplete = false;
let attempts = 0;
const maxAttempts = 10;
while (!enrollmentComplete && attempts < maxAttempts) {
await new Promise(resolve => setTimeout(resolve, 3000)); // Wait 3 seconds
const status = await bioClient.getEnrollmentStatus(enrollment.id);
console.log(` Status: ${status.status} (attempt ${attempts + 1}/${maxAttempts})`);
if (status.status === 'completed') {
console.log('ā
Enrollment completed successfully!');
enrollmentComplete = true;
} else if (status.status === 'failed') {
console.log('ā Enrollment failed:', status.error);
break;
}
attempts++;
}
if (!enrollmentComplete && attempts >= maxAttempts) {
console.log('ā° Enrollment monitoring timeout - cancelling');
await bioClient.cancelEnrollment(enrollment.id);
}
// Cleanup
console.log('šļø Cleaning up test user...');
await bioClient.deleteUser(userId);
} catch (error) {
console.error('ā Enrollment workflow error:', error.message);
}
}
// Run examples
if (require.main === module) {
(async () => {
try {
await biometricManagementExample();
await bulkOperationsExample();
await synchronizationExample();
await enrollmentWorkflowExample();
console.log('\nš Biometric management examples completed!');
} catch (error) {
console.error('\nš„ Examples failed:', error.message);
}
})();
}
module.exports = {
biometricManagementExample,
bulkOperationsExample,
synchronizationExample,
enrollmentWorkflowExample
};