UNPKG

@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
/** * 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 };