UNPKG

zdata-client

Version:

TypeScript client library for zdata backend API with authentication and full CRUD operations

296 lines 9.6 kB
/** * @fileoverview zdata API Client implementation */ import { type ApiConfig, type AuthResponse, type FindRecordsParams, type IApiClient, type LoginRequest, type PaginatedResponse, type RegisterRequest } from "./types.js"; /** * zdata API Client for handling authentication and CRUD operations * * This client provides a complete interface to the zdata backend API, * including user authentication, token management, and full CRUD operations * for any resource with automatic error handling and type safety. * * @example * ```typescript * import { ZDataClient } from 'zdata-client'; * * const client = new ZDataClient({ * baseUrl: 'https://api.example.com', * workspaceId: 'workspace-123' * }); * * // Authentication * await client.login({ * email: 'user@example.com', * password: 'password' * }); * * // CRUD operations * const users = await client.findRecords({ * resourceName: 'users', * page: 1, * limit: 10, * search: 'john' * }); * * const newUser = await client.createRecord('users', { * name: 'John Doe', * email: 'john@example.com' * }); * // newUser will have id, created_at, updated_at fields added * ``` */ export declare class ZDataClient implements IApiClient { private readonly httpClient; private accessToken; /** * Create a new zdata API client instance * @param config - Client configuration options * @throws {Error} When configuration is invalid */ constructor(config: ApiConfig); /** * Authenticate user with email and password * * @param credentials - User login credentials * @returns Promise resolving to authentication response with user data and token * @throws {InvalidCredentialsError} When email/password combination is invalid * @throws {ValidationError} When request data is malformed * @throws {ApiClientError} When API request fails * * @example * ```typescript * try { * const auth = await client.login({ * email: 'user@example.com', * password: 'securePassword123' * }); * console.log('Logged in as:', auth.user.name); * } catch (error) { * if (error instanceof InvalidCredentialsError) { * console.error('Invalid email or password'); * } * } * ``` */ login(credentials: LoginRequest): Promise<AuthResponse>; /** * Register a new user account * * @param userData - User registration data * @returns Promise resolving to authentication response with user data and token * @throws {ValidationError} When registration data is invalid * @throws {ApiClientError} When API request fails (e.g., email already exists) * * @example * ```typescript * try { * const auth = await client.register({ * name: 'John Doe', * email: 'john@example.com', * password: 'securePassword123' * }); * console.log('Registered user:', auth.user.name); * } catch (error) { * if (error instanceof ValidationError) { * console.error('Validation errors:', error.errors); * } * } * ``` */ register(userData: RegisterRequest): Promise<AuthResponse>; /** * Clear authentication token and log out user * * @example * ```typescript * client.logout(); * console.log('User logged out'); * ``` */ logout(): void; /** * Check if user is currently authenticated * * @returns True if user has a valid access token * * @example * ```typescript * if (client.isAuthenticated()) { * console.log('User is logged in'); * } else { * console.log('User needs to log in'); * } * ``` */ isAuthenticated(): boolean; /** * Create a new record in the specified resource * * @template T - The entity type to create * @param resourceName - Name of the resource to create record in * @param data - Record data to create (without base entity fields) * @returns Promise resolving to the created record with base entity fields * @throws {ValidationError} When record data is invalid * @throws {ApiClientError} When API request fails * * @example * ```typescript * interface User { * name: string; * email: string; * } * * const newUser = await client.createRecord<User>('users', { * name: 'John Doe', * email: 'john@example.com' * }); * // newUser will have id, created_at, updated_at fields added * ``` */ createRecord<T = unknown>(resourceName: string, data: import("./types.js").CreateEntity<T>): Promise<import("./types.js").EntityWithBase<T>>; /** * Update an existing record * * @template T - The entity type to update * @param resourceName - Name of the resource * @param id - Unique identifier of the record to update * @param data - Partial record data to update (without base entity fields) * @returns Promise resolving to the updated record with base entity fields * @throws {ValidationError} When record data is invalid * @throws {ApiClientError} When API request fails * * @example * ```typescript * interface User { * name: string; * email: string; * } * * const updatedUser = await client.updateRecord<User>('users', 'user-123', { * name: 'John Smith' * }); * // updatedUser will have all fields including updated updated_at * ``` */ updateRecord<T = unknown>(resourceName: string, id: string, data: Partial<import("./types.js").CreateEntity<T>>): Promise<import("./types.js").EntityWithBase<T>>; /** * Delete a record by ID * * @param resourceName - Name of the resource * @param id - Record identifier * @returns Promise that resolves when deletion is complete * @throws {ApiClientError} When record is not found or API request fails * * @example * ```typescript * await client.deleteRecord('users', 'user-123'); * console.log('User deleted successfully'); * ``` */ deleteRecord(resourceName: string, id: string): Promise<void>; /** * Find a specific record by ID * * @template T - The entity type to return * @param resourceName - Name of the resource * @param id - Record identifier * @returns Promise resolving to the found record with base entity fields * @throws {ApiClientError} When record is not found or API request fails * * @example * ```typescript * interface User { * name: string; * email: string; * } * * const user = await client.findRecordById<User>('users', 'user-123'); * // user will have id, created_at, updated_at fields included * console.log('Found user:', user.name); * ``` */ findRecordById<T = unknown>(resourceName: string, id: string): Promise<import("./types.js").EntityWithBase<T>>; /** * Find records with pagination and optional search * * @template T - The entity type to return * @param params - Query parameters including resource name, pagination, and search * @returns Promise resolving to paginated response with records containing base entity fields * @throws {ApiClientError} When API request fails * * @example * ```typescript * interface User { * name: string; * email: string; * } * * const result = await client.findRecords<User>({ * resourceName: 'users', * page: 1, * limit: 10, * search: 'john' * }); * * console.log(`Found ${result.meta.totalRecords} users`); * result.records.forEach(user => { * // user has id, created_at, updated_at fields included * console.log(user.name, user.id); * }); * * if (result.meta.hasNext) { * console.log('More results available'); * } * ``` */ findRecords<T = unknown>(params: FindRecordsParams): Promise<PaginatedResponse<import("./types.js").EntityWithBase<T>>>; /** * Set the access token for authentication * * This method allows manual token management, useful when implementing * custom authentication flows or token persistence. * * @param token - JWT access token * @throws {Error} When token is invalid or empty * * @example * ```typescript * // Set token from external source * const savedToken = localStorage.getItem('authToken'); * if (savedToken) { * client.setAccessToken(savedToken); * } * ``` */ setAccessToken(token: string): void; /** * Get the current access token * * @returns Current access token or null if not authenticated * * @example * ```typescript * const token = client.getAccessToken(); * if (token) { * localStorage.setItem('authToken', token); * } * ``` */ getAccessToken(): string | null; private validateConfig; private validateLoginCredentials; private validateRegisterData; private validateResourceName; private validateId; private createHttpClient; private setupInterceptors; private handleHttpError; private buildSearchParams; private makeRequest; } /** * Legacy alias for backward compatibility * @deprecated Use ZDataClient instead */ export declare const ExternalApiClient: typeof ZDataClient; //# sourceMappingURL=client.d.ts.map