landson-agri-sdk-kit
Version:
Software Development Kit for the Landson Agri API
830 lines (818 loc) • 22.3 kB
TypeScript
import { AxiosRequestConfig } from 'axios';
interface ApiConfig {
baseURL?: string;
timeout?: number;
headers?: Record<string, string>;
debug?: boolean;
}
interface ApiResponse<T = any> {
success: boolean;
data?: T;
status?: number;
error?: {
message: string;
details?: any;
};
}
interface User {
id: string;
email: string;
firstName?: string;
lastName?: string;
fullName?: string;
phoneNumber?: string;
status: UserStatus;
emailVerified: boolean;
phoneVerified: boolean;
profileImageUrl?: string;
preferredLanguage?: string;
timezone?: string;
roles: Role[];
createdAt: string;
updatedAt: string;
}
declare enum UserStatus {
ACTIVE = "ACTIVE",
INACTIVE = "INACTIVE",
SUSPENDED = "SUSPENDED",
PENDING_VERIFICATION = "PENDING_VERIFICATION"
}
interface Role {
id: string;
name: string;
description?: string;
permissions?: Permission[];
}
interface Permission {
id: string;
resource: string;
action: string;
description?: string;
}
interface LoginRequest {
email: string;
password: string;
}
interface LoginResponse {
accessToken: string;
refreshToken: string;
expiresAt: string;
expiresIn: number;
user: User;
tokenId: string;
}
interface PhoneLoginRequest {
phoneNumber: string;
}
interface PhoneLoginVerifyRequest {
phoneNumber: string;
code: string;
}
interface RegisterRequest {
email: string;
password: string;
firstName: string;
lastName: string;
phoneNumber: string;
}
interface RegisterResponse {
id: string;
email: string;
firstName: string;
lastName: string;
phoneNumber: string;
status: UserStatus;
message: string;
}
interface VerifyPhoneRequest {
email: string;
phoneNumber: string;
code: string;
}
interface VerifyPhoneResponse {
message: string;
verified: boolean;
status: UserStatus;
}
interface RequestPasswordResetRequest {
email: string;
}
interface ResetPasswordRequest {
email: string;
code: string;
newPassword: string;
}
interface SendPhoneVerificationRequest {
phoneNumber: string;
}
interface SendPhoneVerificationResponse {
message: string;
expiresAt: string;
sentViaSms: boolean;
}
interface VerifyUserPhoneRequest {
code: string;
}
interface VerifyUserPhoneResponse {
message: string;
}
interface LoginOtpRequest {
email: string;
}
interface ResendOtpRequest {
email: string;
type: 'login' | 'registration' | 'password-reset' | 'phone-verification';
}
interface VerifyOtpRequest {
email: string;
code: string;
type: 'login' | 'registration' | 'password-reset' | 'phone-verification';
}
interface ChangePasswordRequest {
currentPassword: string;
newPassword: string;
}
interface UpdateUserRequest {
firstName?: string;
lastName?: string;
phoneNumber?: string;
preferredLanguage?: string;
timezone?: string;
profileImageUrl?: string;
status?: UserStatus;
}
interface UserQueryParams {
page?: number;
size?: number;
search?: string;
status?: string;
sortBy?: string;
sortDir?: 'asc' | 'desc';
}
interface PaginatedUsers {
data: User[];
pagination: {
totalItems: number;
page: number;
size: number;
totalPages: number;
};
}
interface CreateUserRequest {
email: string;
password: string;
firstName: string;
lastName: string;
phoneNumber?: string;
status?: UserStatus;
roleIds?: string[];
}
interface UpdateProfileImageUrlRequest {
profileImageUrl: string;
}
interface GetProfileImageUploadUrlResponse {
uploadUrl: string;
key: string;
expiresIn: number;
}
declare enum CategoryStatus {
ACTIVE = "ACTIVE",
INACTIVE = "INACTIVE",
ARCHIVED = "ARCHIVED"
}
interface Category {
id: string;
name: string;
slug: string;
description?: string;
imageUrl?: string;
bannerUrl?: string;
status: CategoryStatus;
parentId?: string;
sortOrder: number;
isPromoted: boolean;
viewCount: number;
metadata?: Record<string, any>;
createdAt: string;
updatedAt: string;
children?: Category[];
}
interface CreateCategoryRequest {
name: string;
description?: string;
imageUrl?: string;
bannerUrl?: string;
status?: CategoryStatus;
parentId?: string;
sortOrder?: number;
isPromoted?: boolean;
metadata?: Record<string, any>;
}
interface UpdateCategoryRequest {
name?: string;
description?: string;
imageUrl?: string;
bannerUrl?: string;
status?: CategoryStatus;
parentId?: string;
sortOrder?: number;
isPromoted?: boolean;
metadata?: Record<string, any>;
}
interface CategoryQueryParams {
search?: string;
parentId?: string;
rootOnly?: boolean;
status?: CategoryStatus[];
isPromoted?: boolean;
orderBy?: string;
orderDirection?: 'asc' | 'desc';
skip?: number;
take?: number;
includeChildren?: boolean;
includeStats?: boolean;
tree?: boolean;
}
interface PaginatedCategories {
data: Category[];
meta: {
total: number;
skip: number;
take: number;
hasMore: boolean;
};
}
interface CategoryStats {
totalCategories: number;
totalActive: number;
totalInactive: number;
totalArchived: number;
totalRootCategories: number;
topViewed: {
id: string;
name: string;
slug: string;
viewCount: number;
}[];
recentlyUpdated: {
id: string;
name: string;
slug: string;
updatedAt: string;
}[];
}
declare class AuthService {
private client;
constructor(client: LandsonAgriClient);
/**
* Login with email and password
*/
login(data: LoginRequest): Promise<ApiResponse<LoginResponse>>;
/**
* Request an OTP code for phone login
*/
requestPhoneLogin(data: PhoneLoginRequest): Promise<ApiResponse<{
message: string;
expiresAt: string;
}>>;
/**
* Verify phone login with OTP code
*/
verifyPhoneLogin(data: PhoneLoginVerifyRequest): Promise<ApiResponse<LoginResponse>>;
/**
* Register a new user
*/
register(data: RegisterRequest): Promise<ApiResponse<RegisterResponse>>;
/**
* Verify phone number after registration
*/
verifyPhone(data: VerifyPhoneRequest): Promise<ApiResponse<VerifyPhoneResponse>>;
/**
* Request login OTP code
*/
requestLoginOtp(data: LoginOtpRequest): Promise<ApiResponse<{
message: string;
expiresAt: string;
}>>;
/**
* Resend OTP code
*/
resendOtp(data: ResendOtpRequest): Promise<ApiResponse<{
message: string;
expiresAt: string;
}>>;
/**
* Verify OTP code
*/
verifyOtp(data: VerifyOtpRequest): Promise<ApiResponse<LoginResponse>>;
/**
* Request password reset
*/
requestPasswordReset(data: RequestPasswordResetRequest): Promise<ApiResponse<{
message: string;
}>>;
/**
* Reset password with OTP code
*/
resetPassword(data: ResetPasswordRequest): Promise<ApiResponse<{
message: string;
}>>;
/**
* Send phone verification code
*/
sendPhoneVerification(data: SendPhoneVerificationRequest): Promise<ApiResponse<SendPhoneVerificationResponse>>;
/**
* Verify user's phone number
*/
verifyUserPhone(data: VerifyUserPhoneRequest): Promise<ApiResponse<VerifyUserPhoneResponse>>;
/**
* Logout user
*/
logout(): Promise<ApiResponse<{
success: boolean;
}>>;
/**
* Refresh token
*/
refreshToken(refreshToken: string): Promise<ApiResponse<LoginResponse>>;
/**
* Get current user profile
*/
getCurrentUser(): Promise<ApiResponse<any>>;
/**
* Test SMS service
*/
testSms(phoneNumber: string): Promise<ApiResponse<{
success: boolean;
message: string;
smsEnabled: boolean;
twilioConfigured: boolean;
}>>;
}
interface UpdateUserData {
firstName?: string;
lastName?: string;
phoneNumber?: string;
profileImageUrl?: string;
preferredLanguage?: string;
timezone?: string;
}
declare class UserService {
private client;
constructor(client: LandsonAgriClient);
/**
* Get current user profile
*/
getCurrentUser(): Promise<ApiResponse<User>>;
/**
* Update current user profile
*/
updateCurrentUser(data: UpdateUserRequest): Promise<ApiResponse<User>>;
/**
* Change current user password
*/
changePassword(data: ChangePasswordRequest): Promise<ApiResponse<{
message: string;
}>>;
/**
* Upload profile image
*/
uploadProfileImage(file: File): Promise<ApiResponse<{
profileImageUrl: string;
}>>;
/**
* Delete profile image
*/
deleteProfileImage(): Promise<ApiResponse<{
message: string;
}>>;
/**
* Update profile image URL directly
*/
updateProfileImageUrl(data: UpdateProfileImageUrlRequest): Promise<ApiResponse<User>>;
/**
* Get presigned URL for profile image upload
*/
getProfileImageUploadUrl(contentType?: string): Promise<ApiResponse<GetProfileImageUploadUrlResponse>>;
/**
* Get all users (admin only)
*/
getUsers(params?: UserQueryParams): Promise<ApiResponse<PaginatedUsers>>;
/**
* Get a specific user by ID (admin only)
*/
getUserById(userId: string): Promise<ApiResponse<User>>;
/**
* Update a specific user by ID (admin only)
*/
updateUser(userId: string, data: UpdateUserRequest): Promise<ApiResponse<User>>;
/**
* Delete a user by ID (admin only)
*/
deleteUser(userId: string): Promise<ApiResponse<{
message: string;
}>>;
/**
* Change user status (admin only)
*/
changeUserStatus(userId: string, status: string): Promise<ApiResponse<User>>;
/**
* Create a new user (admin only)
*/
createUser(data: CreateUserRequest): Promise<ApiResponse<User>>;
}
interface CreateRoleRequest {
name: string;
description?: string;
permissionIds?: string[];
}
interface UpdateRoleRequest {
name?: string;
description?: string;
permissionIds?: string[];
}
interface RoleQueryParams {
page?: number;
size?: number;
search?: string;
sortBy?: string;
sortDir?: 'asc' | 'desc';
}
interface PaginatedRoles {
data: Role[];
pagination: {
totalItems: number;
page: number;
size: number;
totalPages: number;
};
}
declare class RoleService {
private client;
constructor(client: LandsonAgriClient);
/**
* Get all roles with pagination and filtering (admin only)
*/
getRoles(params?: RoleQueryParams): Promise<ApiResponse<PaginatedRoles>>;
/**
* Get a specific role by ID (admin only)
*/
getRoleById(roleId: string): Promise<ApiResponse<Role>>;
/**
* Create a new role (admin only)
*/
createRole(data: CreateRoleRequest): Promise<ApiResponse<Role>>;
/**
* Update a role (admin only)
*/
updateRole(roleId: string, data: UpdateRoleRequest): Promise<ApiResponse<Role>>;
/**
* Delete a role (admin only)
*/
deleteRole(roleId: string): Promise<ApiResponse<{
message: string;
}>>;
/**
* Get all permissions (admin only)
*/
getPermissions(): Promise<ApiResponse<Permission[]>>;
/**
* Assign roles to a user (admin only)
*/
assignRolesToUser(userId: string, roleIds: string[]): Promise<ApiResponse<User>>;
/**
* Remove roles from a user (admin only)
*/
removeRolesFromUser(userId: string, roleIds: string[]): Promise<ApiResponse<User>>;
}
interface FileMetadata {
id: string;
key: string;
filename: string;
contentType: string;
size: number;
etag: string;
url?: string;
createdAt: Date;
lastModified: Date;
isPublic: boolean;
folder?: string;
}
interface UploadFileOptions {
folder?: string;
filename?: string;
isPublic?: boolean;
}
interface GeneratePresignedUrlOptions {
folder?: string;
filename?: string;
contentType: string;
contentLength: string;
isPublic?: boolean;
}
interface FolderItem {
name: string;
path: string;
type: 'file' | 'folder';
size: number;
lastModified: Date;
contentType?: string;
isPublic?: boolean;
}
interface FolderContents {
path: string;
contents: FolderItem[];
}
interface UpdateFileOptions {
filename?: string;
folder?: string;
isPublic?: boolean;
}
interface CreateFolderOptions {
path: string;
}
declare class StorageService {
private client;
constructor(client: LandsonAgriClient);
/**
* Upload a file directly to S3
*/
uploadFile(file: File, options?: UploadFileOptions): Promise<ApiResponse<FileMetadata>>;
/**
* Generate a pre-signed URL for direct upload to S3
*/
generatePresignedUrl(options: GeneratePresignedUrlOptions): Promise<ApiResponse<{
url: string;
key: string;
fields?: Record<string, string>;
}>>;
/**
* Get download URL for a file
*/
getDownloadUrl(key: string): Promise<ApiResponse<{
url: string;
}>>;
/**
* Download a file directly (browser only)
* This will start the download of the file through the browser
*/
downloadFile(key: string): Promise<void>;
/**
* Get metadata for a file
*/
getFileMetadata(key: string): Promise<ApiResponse<FileMetadata>>;
/**
* Update file metadata or move the file
*/
updateFile(key: string, options: UpdateFileOptions): Promise<ApiResponse<FileMetadata>>;
/**
* Delete a file from S3
*/
deleteFile(key: string): Promise<ApiResponse<{
success: boolean;
}>>;
/**
* List files in a folder
*/
listFiles(prefix?: string, recursive?: boolean): Promise<ApiResponse<FolderContents>>;
/**
* Create a new folder
*/
createFolder(options: CreateFolderOptions): Promise<ApiResponse<{
success: boolean;
path: string;
}>>;
/**
* Check if storage service is healthy
*/
healthCheck(): Promise<ApiResponse<boolean>>;
}
interface NotificationSubscription {
email: string;
notificationTypes?: string[];
frequency?: 'immediate' | 'daily' | 'weekly';
}
declare class NotificationService {
private client;
constructor(client: LandsonAgriClient);
/**
* Subscribe to notifications
*/
subscribe(data: NotificationSubscription): Promise<ApiResponse<{
success: boolean;
message: string;
email: string;
}>>;
/**
* Verify notification subscription
*/
verify(email: string, token: string): Promise<ApiResponse<{
success: boolean;
message: string;
}>>;
/**
* Unsubscribe from notifications
*/
unsubscribe(email: string): Promise<ApiResponse<{
success: boolean;
message: string;
}>>;
}
interface VersionStatistics {
version: string;
requestCount: number;
uniqueUsers: number;
averageResponseTime: number;
}
interface EndpointStatistics {
endpoint: string;
method: string;
requestCount: number;
averageResponseTime: number;
errorRate: number;
}
interface VersionSpecificStats {
version: string;
endpoints: EndpointStatistics[];
}
declare class AnalyticsService {
private client;
constructor(client: LandsonAgriClient);
/**
* Get version statistics
*/
getVersionStatistics(): Promise<ApiResponse<{
success: boolean;
data: VersionStatistics[];
}>>;
/**
* Get popular endpoints
*/
getPopularEndpoints(version?: string): Promise<ApiResponse<{
success: boolean;
data: EndpointStatistics[];
}>>;
/**
* Get version-specific stats
*/
getVersionSpecificStats(version: string): Promise<ApiResponse<{
success: boolean;
version: string;
endpoints: EndpointStatistics[];
}>>;
}
interface HealthStatus {
status: 'ok' | 'error';
message?: string;
timestamp: string;
version?: string;
uptime?: number;
}
interface DetailedHealthStatus extends HealthStatus {
details: {
database: SubsystemStatus;
redis: SubsystemStatus;
memory: ResourceStatus;
cpu: ResourceStatus;
disk: ResourceStatus;
external?: SubsystemStatus[];
analytics?: SubsystemStatus;
errorMonitoring?: SubsystemStatus;
mail?: SubsystemStatus;
s3?: SubsystemStatus;
};
}
interface SubsystemStatus {
status: 'ok' | 'error';
message?: string;
latency?: number;
}
interface ResourceStatus {
status: 'ok' | 'warning' | 'error';
message?: string;
used: number;
total: number;
percentage: number;
}
declare class HealthService {
private client;
constructor(client: LandsonAgriClient);
/**
* Basic health check
*/
check(): Promise<ApiResponse<HealthStatus>>;
/**
* Detailed health check with all subsystems
*/
detailedCheck(): Promise<ApiResponse<DetailedHealthStatus>>;
/**
* Database health check
*/
checkDatabase(): Promise<ApiResponse<SubsystemStatus>>;
/**
* Redis health check
*/
checkRedis(): Promise<ApiResponse<SubsystemStatus>>;
/**
* Memory usage health check
*/
checkMemory(): Promise<ApiResponse<ResourceStatus>>;
/**
* CPU usage health check
*/
checkCpu(): Promise<ApiResponse<ResourceStatus>>;
/**
* Disk space health check
*/
checkDisk(): Promise<ApiResponse<ResourceStatus>>;
/**
* External dependencies health check
*/
checkExternal(url?: string): Promise<ApiResponse<SubsystemStatus | SubsystemStatus[]>>;
/**
* Analytics service health check
*/
checkAnalytics(): Promise<ApiResponse<SubsystemStatus>>;
/**
* Error monitoring service health check
*/
checkErrorMonitoring(): Promise<ApiResponse<SubsystemStatus>>;
/**
* Mail service health check
*/
checkMail(): Promise<ApiResponse<SubsystemStatus>>;
/**
* S3 storage service health check
*/
checkS3(): Promise<ApiResponse<SubsystemStatus>>;
}
declare class CategoryService {
private client;
constructor(client: LandsonAgriClient);
/**
* Get all categories with filtering
*/
getCategories(params?: CategoryQueryParams): Promise<ApiResponse<PaginatedCategories>>;
/**
* Get category statistics (admin only)
*/
getStats(): Promise<ApiResponse<CategoryStats>>;
/**
* Get a category by ID
*/
getCategoryById(id: string, options?: {
includeChildren?: boolean;
trackView?: boolean;
}): Promise<ApiResponse<Category>>;
/**
* Get a category by slug
*/
getCategoryBySlug(slug: string, options?: {
includeChildren?: boolean;
trackView?: boolean;
}): Promise<ApiResponse<Category>>;
/**
* Create a new category (admin only)
*/
createCategory(data: CreateCategoryRequest): Promise<ApiResponse<Category>>;
/**
* Update a category (admin only)
*/
updateCategory(id: string, data: UpdateCategoryRequest): Promise<ApiResponse<Category>>;
/**
* Delete a category (admin only)
*/
deleteCategory(id: string, hard?: boolean): Promise<ApiResponse<{
success: boolean;
id: string;
}>>;
/**
* Get hierarchical category tree
*/
getCategoryTree(params?: Omit<CategoryQueryParams, 'skip' | 'take' | 'includeChildren'>): Promise<ApiResponse<Category[]>>;
}
declare class LandsonAgriClient {
private client;
private accessToken;
private sessionId;
private debugMode;
readonly auth: AuthService;
readonly users: UserService;
readonly roles: RoleService;
readonly storage: StorageService;
readonly notifications: NotificationService;
readonly analytics: AnalyticsService;
readonly health: HealthService;
readonly categories: CategoryService;
constructor(config: ApiConfig);
setDebugMode(debug: boolean): void;
isDebugMode(): boolean;
setAccessToken(token: string): void;
clearAccessToken(): void;
getAccessToken(): string | null;
setSessionId(id: string): void;
clearSessionId(): void;
getSessionId(): string | null;
request<T = any>(config: AxiosRequestConfig): Promise<ApiResponse<T>>;
}
export { AnalyticsService, type ApiConfig, type ApiResponse, AuthService, type Category, type CategoryQueryParams, CategoryService, type CategoryStats, CategoryStatus, type ChangePasswordRequest, type CreateCategoryRequest, type CreateFolderOptions, type CreateRoleRequest, type CreateUserRequest, type DetailedHealthStatus, type EndpointStatistics, type FileMetadata, type FolderContents, type FolderItem, type GeneratePresignedUrlOptions, type GetProfileImageUploadUrlResponse, HealthService, type HealthStatus, LandsonAgriClient, type LoginOtpRequest, type LoginRequest, type LoginResponse, NotificationService, type NotificationSubscription, type PaginatedCategories, type PaginatedRoles, type PaginatedUsers, type Permission, type PhoneLoginRequest, type PhoneLoginVerifyRequest, type RegisterRequest, type RegisterResponse, type RequestPasswordResetRequest, type ResendOtpRequest, type ResetPasswordRequest, type ResourceStatus, type Role, type RoleQueryParams, RoleService, type SendPhoneVerificationRequest, type SendPhoneVerificationResponse, StorageService, type SubsystemStatus, type UpdateCategoryRequest, type UpdateFileOptions, type UpdateProfileImageUrlRequest, type UpdateRoleRequest, type UpdateUserData, type UpdateUserRequest, type UploadFileOptions, type User, type UserQueryParams, UserService, UserStatus, type VerifyOtpRequest, type VerifyPhoneRequest, type VerifyPhoneResponse, type VerifyUserPhoneRequest, type VerifyUserPhoneResponse, type VersionSpecificStats, type VersionStatistics };