NeoScan_Radiologist/app/modules/Auth/services/signupAPI.ts
2025-08-05 18:01:36 +05:30

392 lines
10 KiB
TypeScript

/*
* File: signupAPI.ts
* Description: Signup API service with validation and hospital endpoints
* Design & Developed by Tech4Biz Solutions
* Copyright (c) Spurrin Innovations. All rights reserved.
*/
import { create } from 'apisauce';
import { SignUpData, EmailValidationApiResponse, UsernameValidationApiResponse, HospitalListApiResponse, SignUpApiResponse } from '../types/signup';
// ============================================================================
// API CONFIGURATION
// ============================================================================
/**
* API Base Configuration
*
* Purpose: Configure the base API client for signup operations
*
* Features:
* - Base URL configuration
* - Request/response interceptors
* - Error handling
* - Timeout settings
*/
const API_BASE_URL = 'https://api.neoscan-physician.com/v1'; // TODO: Replace with actual API URL
const api = create({
baseURL: API_BASE_URL,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
timeout: 30000, // 30 seconds
});
// ============================================================================
// REQUEST INTERCEPTORS
// ============================================================================
/**
* Request Interceptor
*
* Purpose: Add authentication headers and logging
*/
api.addRequestTransform((request) => {
// Add any common headers here
console.log('API Request:', {
method: request.method,
url: request.url,
data: request.data,
});
});
// ============================================================================
// RESPONSE INTERCEPTORS
// ============================================================================
/**
* Response Interceptor
*
* Purpose: Handle common response patterns and errors
*/
api.addResponseTransform((response) => {
console.log('API Response:', {
status: response.status,
url: response.config?.url,
data: response.data,
});
// Handle common error patterns
if (response.status === 401) {
// Handle unauthorized access
console.error('Unauthorized access');
}
if (response.status === 500) {
// Handle server errors
console.error('Server error occurred');
}
});
// ============================================================================
// EMAIL VALIDATION API
// ============================================================================
/**
* Validate Email
*
* Purpose: Check if email is available for registration
*
* @param email - Email address to validate
* @returns Promise with validation result
*/
export const validatemail = async (email: string): Promise<EmailValidationApiResponse> => {
try {
const response = await api.post<EmailValidationApiResponse>('/auth/validate-email', {
email,
});
if (response.ok && response.data) {
return response.data;
} else {
throw new Error(response.problem || 'Failed to validate email');
}
} catch (error) {
console.error('Email validation error:', error);
throw error;
}
};
// ============================================================================
// USERNAME VALIDATION API
// ============================================================================
/**
* Validate Username
*
* Purpose: Check if username is available for registration
*
* @param username - Username to validate
* @returns Promise with validation result
*/
export const validateusername = async (username: string): Promise<UsernameValidationApiResponse> => {
try {
const response = await api.post<UsernameValidationApiResponse>('/auth/validate-username', {
username,
});
if (response.ok && response.data) {
return response.data;
} else {
throw new Error(response.problem || 'Failed to validate username');
}
} catch (error) {
console.error('Username validation error:', error);
throw error;
}
};
// ============================================================================
// HOSPITAL API
// ============================================================================
/**
* Get Hospitals List
*
* Purpose: Fetch list of available hospitals
*
* @param params - Query parameters for filtering
* @returns Promise with hospital list
*/
export const gethospitals = async (params?: {
page?: number;
limit?: number;
search?: string;
type?: string;
city?: string;
state?: string;
}): Promise<HospitalListApiResponse> => {
try {
const response = await api.get<HospitalListApiResponse>('/hospitals', params);
if (response.ok && response.data) {
return response.data;
} else {
throw new Error(response.problem || 'Failed to fetch hospitals');
}
} catch (error) {
console.error('Get hospitals error:', error);
throw error;
}
};
/**
* Get Hospital by ID
*
* Purpose: Fetch specific hospital details
*
* @param hospitalId - Hospital ID
* @returns Promise with hospital details
*/
export const getHospitalById = async (hospitalId: string) => {
try {
const response = await api.get(`/hospitals/${hospitalId}`);
if (response.ok && response.data) {
return response.data;
} else {
throw new Error(response.problem || 'Failed to fetch hospital details');
}
} catch (error) {
console.error('Get hospital by ID error:', error);
throw error;
}
};
// ============================================================================
// SIGNUP API
// ============================================================================
/**
* Complete Signup
*
* Purpose: Submit complete signup data
*
* @param formData - FormData with signup information
* @returns Promise with signup result
*/
export const signup = async (formData: FormData): Promise<SignUpApiResponse> => {
try {
const response = await api.post<SignUpApiResponse>('/auth/signup', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
console.log('actual response ',response)
if (response.ok && response.data) {
return response.data;
} else {
throw new Error(response.problem || 'Failed to complete signup');
}
} catch (error) {
console.error('Complete signup error:', error);
throw error;
}
};
// ============================================================================
// MOCK API FUNCTIONS (FOR DEVELOPMENT)
// ============================================================================
/**
* Mock Validate Email
*
* Purpose: Mock email validation for development
*
* @param email - Email address to validate
* @returns Promise with mock validation result
*/
export const mockValidatemail = async (email: string): Promise<EmailValidationApiResponse> => {
// Simulate API delay
await new Promise(resolve => setTimeout(resolve, 1000));
// Mock validation logic
const isAvailable = email !== 'existing@hospital.com';
return {
success: true,
isAvailable,
message: isAvailable ? 'Email is available' : 'Email is already registered',
suggestions: isAvailable ? undefined : ['Try a different email address'],
};
};
/**
* Mock Validate Username
*
* Purpose: Mock username validation for development
*
* @param username - Username to validate
* @returns Promise with mock validation result
*/
export const mockValidateusername = async (username: string): Promise<UsernameValidationApiResponse> => {
// Simulate API delay
await new Promise(resolve => setTimeout(resolve, 800));
// Mock validation logic
const isAvailable = username !== 'existinguser';
return {
success: true,
isAvailable,
message: isAvailable ? 'Username is available' : 'Username is already taken',
suggestions: isAvailable ? undefined : ['Try adding numbers or special characters'],
};
};
/**
* Mock Get Hospitals
*
* Purpose: Mock hospital list for development
*
* @returns Promise with mock hospital list
*/
export const mockGethospitals = async (): Promise<HospitalListApiResponse> => {
// Simulate API delay
await new Promise(resolve => setTimeout(resolve, 1500));
// Mock hospital data
const mockHospitals = [
{
id: '1',
name: 'General Hospital',
address: '123 Main Street',
city: 'New York',
state: 'NY',
country: 'USA',
phoneNumber: '+1-555-0123',
email: 'info@generalhospital.com',
website: 'https://generalhospital.com',
type: 'GENERAL' as const,
specialties: ['Emergency Medicine', 'Cardiology', 'Neurology'],
isActive: true,
},
{
id: '2',
name: 'University Medical Center',
address: '456 University Ave',
city: 'Boston',
state: 'MA',
country: 'USA',
phoneNumber: '+1-555-0456',
email: 'info@umc.edu',
website: 'https://umc.edu',
type: 'UNIVERSITY' as const,
specialties: ['Emergency Medicine', 'Trauma', 'Research'],
isActive: true,
},
{
id: '3',
name: 'Specialty Medical Center',
address: '789 Specialty Blvd',
city: 'Los Angeles',
state: 'CA',
country: 'USA',
phoneNumber: '+1-555-0789',
email: 'info@specialtycenter.com',
website: 'https://specialtycenter.com',
type: 'SPECIALTY' as const,
specialties: ['Cardiology', 'Neurology', 'Oncology'],
isActive: true,
},
];
return {
success: true,
data: mockHospitals,
total: mockHospitals.length,
page: 1,
limit: 10,
};
};
/**
* Mock Complete Signup
*
* Purpose: Mock signup completion for development
*
* @param signUpData - Complete signup data
* @returns Promise with mock signup result
*/
export const mockSignup = async (signUpData: SignUpData): Promise<SignUpApiResponse> => {
// Simulate API delay
await new Promise(resolve => setTimeout(resolve, 2000));
// Mock successful signup
return {
success: true,
message: 'Account created successfully',
data: {
userId: 'user_' + Date.now(),
email: signUpData.email,
token: 'mock_token_' + Date.now(),
},
};
};
// ============================================================================
// EXPORTS
// ============================================================================
export const authAPI = {
// Real API functions
validatemail,
validateusername,
gethospitals,
getHospitalById,
signup,
// Mock API functions (for development)
mockValidatemail,
mockValidateusername,
mockGethospitals,
mockSignup,
};
/*
* End of File: signupAPI.ts
* Design & Developed by Tech4Biz Solutions
* Copyright (c) Spurrin Innovations. All rights reserved.
*/