UNPKG

landson-agri-sdk-kit

Version:

Software Development Kit for the Landson Agri API

271 lines (211 loc) 7.22 kB
# Landson Agri SDK A TypeScript SDK for interacting with the Landson Agri API. ## Installation ```bash npm install landson-agri-sdk ``` ## Usage ### Initialize the SDK ```typescript import { LandsonAgriClient } from 'landson-agri-sdk'; // Create a new client instance const client = new LandsonAgriClient({ baseURL: 'backend url', // Optional, defaults to this URL timeout: 10000, // Optional, defaults to 10000ms headers: { // Optional custom headers 'x-custom-header': 'custom-value' } }); ``` ### Authentication ```typescript // Register a new user const registerResponse = await client.auth.register({ email: 'user@example.com', password: 'securePassword123', firstName: 'John', lastName: 'Doe', phoneNumber: '+14155552671' }); // Login with email and password const loginResponse = await client.auth.login({ email: 'user@example.com', password: 'securePassword123' }); // If login is successful, the SDK automatically sets the access token if (loginResponse.success) { console.log('Logged in successfully:', loginResponse.data.user); } // Verify phone number for a new registration const verifyPhoneResponse = await client.auth.verifyPhone({ email: 'user@example.com', phoneNumber: '+14155552671', code: '123456' }); // Phone login - request OTP const phoneLoginRequest = await client.auth.requestPhoneLogin({ phoneNumber: '+14155552671' }); // Phone login - verify OTP const phoneLoginVerify = await client.auth.verifyPhoneLogin({ phoneNumber: '+14155552671', code: '123456' }); // Logout await client.auth.logout(); ``` ### User Management ```typescript // Get current user const userResponse = await client.users.getCurrentUser(); // Update current user const updateResponse = await client.users.updateCurrentUser({ firstName: 'John', lastName: 'Smith' }); // Upload profile image const fileInput = document.querySelector('input[type="file"]'); const file = fileInput.files[0]; const uploadResponse = await client.users.uploadProfileImage(file); // Admin functions // Get all users (with pagination) const usersResponse = await client.users.getUsers({ page: 0, size: 10, search: 'john', sortBy: 'createdAt', sortDir: 'desc' }); // Get user by ID const userByIdResponse = await client.users.getUserById('user-id-here'); // Update user (admin only) const adminUpdateResponse = await client.users.updateUser('user-id-here', { firstName: 'Jane', lastName: 'Doe' }); // Delete user (admin only) const deleteResponse = await client.users.deleteUser('user-id-here'); // Change user status (admin only) const statusResponse = await client.users.changeUserStatus('user-id-here', 'INACTIVE'); ``` ### Role Management ```typescript // Get all roles (admin only) const rolesResponse = await client.roles.getRoles({ page: 0, size: 10, search: 'admin' }); // Get role by ID (admin only) const roleResponse = await client.roles.getRoleById('role-id-here'); // Create a new role (admin only) const createRoleResponse = await client.roles.createRole({ name: 'Manager', description: 'Department manager role', permissionIds: ['perm1', 'perm2'] }); // Update a role (admin only) const updateRoleResponse = await client.roles.updateRole('role-id-here', { name: 'Senior Manager', description: 'Updated description' }); // Delete a role (admin only) const deleteRoleResponse = await client.roles.deleteRole('role-id-here'); // Get all permissions (admin only) const permissionsResponse = await client.roles.getPermissions(); // Assign roles to a user (admin only) const assignRolesResponse = await client.roles.assignRolesToUser('user-id-here', ['role1', 'role2']); // Remove roles from a user (admin only) const removeRolesResponse = await client.roles.removeRolesFromUser('user-id-here', ['role1']); ``` ### Storage Service ```typescript // Upload a file directly const fileInput = document.querySelector('input[type="file"]'); const file = fileInput.files[0]; const uploadResponse = await client.storage.uploadFile(file, { folder: 'documents', filename: 'my-document.pdf', isPublic: true }); // Generate a pre-signed URL for client-side upload const presignedResponse = await client.storage.generatePresignedUrl({ folder: 'images', filename: 'profile.jpg', contentType: 'image/jpeg', isPublic: true }); // Get a download URL for a file const downloadUrlResponse = await client.storage.getDownloadUrl('documents/my-document.pdf'); // Get file metadata const metadataResponse = await client.storage.getFileMetadata('documents/my-document.pdf'); // Update file properties const updateFileResponse = await client.storage.updateFile('documents/my-document.pdf', { newFilename: 'renamed-document.pdf', isPublic: false }); // Delete a file const deleteFileResponse = await client.storage.deleteFile('documents/my-document.pdf'); // List files in a folder const listFilesResponse = await client.storage.listFiles('documents', true); // Create a new folder const createFolderResponse = await client.storage.createFolder({ path: 'documents/invoices' }); ``` ### Notifications ```typescript // Subscribe to notifications const subscribeResponse = await client.notifications.subscribe({ email: 'user@example.com', notificationTypes: ['system', 'marketing'], frequency: 'daily' }); // Verify notification subscription const verifyResponse = await client.notifications.verify( 'user@example.com', 'verification-token-123' ); // Unsubscribe from notifications const unsubscribeResponse = await client.notifications.unsubscribe('user@example.com'); ``` ### Analytics (Admin Only) ```typescript // Get version statistics const versionStatsResponse = await client.analytics.getVersionStatistics(); // Get popular endpoints const endpointsResponse = await client.analytics.getPopularEndpoints(); // Get version-specific stats const versionSpecificResponse = await client.analytics.getVersionSpecificStats('v1'); ``` ### Health Checks ```typescript // Basic health check const healthResponse = await client.health.check(); // Detailed health check const detailedHealthResponse = await client.health.detailedCheck(); // Check specific subsystems const databaseHealthResponse = await client.health.checkDatabase(); const redisHealthResponse = await client.health.checkRedis(); const memoryHealthResponse = await client.health.checkMemory(); const cpuHealthResponse = await client.health.checkCpu(); const diskHealthResponse = await client.health.checkDisk(); ``` ## Error Handling The SDK provides a consistent way to handle API responses: ```typescript const response = await client.auth.login({ email: 'invalid@example.com', password: 'wrongpassword' }); if (!response.success) { console.error('Error:', response.error?.message); console.error('Status code:', response.status); console.error('Details:', response.error?.details); } else { console.log('Success:', response.data); } ``` ## License MIT