namecheap/ts/config.ts
2025-04-02 15:19:18 +00:00

100 lines
2.4 KiB
TypeScript

/**
* Namecheap API Client - Configuration
*/
import type { INamecheapAuth } from './types.js';
export class NamecheapConfig implements INamecheapAuth {
// Required authentication properties
apiUser: string;
apiKey: string;
userName: string;
clientIp: string;
// API endpoint configuration
baseUrl: string = 'https://api.namecheap.com/xml.response';
// Whether to use sandbox environment (for testing)
useSandbox: boolean = false;
// Default request timeout in milliseconds
timeout: number = 30000;
/**
* Create a new Namecheap API configuration
*/
constructor(config: INamecheapAuth) {
this.apiUser = config.apiUser;
this.apiKey = config.apiKey;
this.userName = config.userName || config.apiUser; // Default userName to apiUser if not provided
this.clientIp = config.clientIp;
this.validateConfig();
}
/**
* Validate configuration parameters
* @throws Error if configuration is invalid
*/
private validateConfig(): void {
if (!this.apiUser) {
throw new Error('Namecheap API User is required');
}
if (!this.apiKey) {
throw new Error('Namecheap API Key is required');
}
if (!this.userName) {
throw new Error('Namecheap User Name is required');
}
if (!this.clientIp) {
throw new Error('Client IP address is required');
}
// Validate IP address format
const ipRegex = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
if (!ipRegex.test(this.clientIp)) {
throw new Error('Invalid IP address format');
}
}
/**
* Enable sandbox mode for testing
*/
enableSandbox(): void {
this.useSandbox = true;
this.baseUrl = 'https://api.sandbox.namecheap.com/xml.response';
}
/**
* Disable sandbox mode
*/
disableSandbox(): void {
this.useSandbox = false;
this.baseUrl = 'https://api.namecheap.com/xml.response';
}
/**
* Set request timeout
* @param ms Timeout in milliseconds
*/
setTimeout(ms: number): void {
this.timeout = ms;
}
/**
* Get base parameters that should be included in every API request
* @param command API command to execute
* @returns Base parameters object
*/
getBaseParams(command: string): Record<string, string | number> {
return {
ApiUser: this.apiUser,
ApiKey: this.apiKey,
UserName: this.userName,
ClientIp: this.clientIp,
Command: command
};
}
}