UNPKG

fayda-auth

Version:

A library for interacting with the Fayda authentication service.

65 lines (59 loc) 2.35 kB
import axios, { AxiosInstance, isAxiosError } from 'axios'; import { FaydaAuthOptions, InitiateOTPResponse, VerifyOTPResponse, ApiError } from './types/index'; import { FaydaAuthError } from './FaydaAuthError'; export class FaydaAuth { private apiKey: string; private client: AxiosInstance; constructor(options: FaydaAuthOptions) { if (!options.apiKey) { throw new FaydaAuthError({ success: false, error: 'MISSING_API_KEY', message: 'API key is required.', statusCode: 401, timestamp: new Date().toISOString() }); } this.apiKey = options.apiKey; this.client = axios.create({ baseURL: options.baseUrl || 'https://fayda-auth.vercel.app/api/fayda', headers: { 'Authorization': `Bearer ${this.apiKey}`, 'Content-Type': 'application/json' } }); } private handleError(error: unknown): never { if (isAxiosError(error) && error.response) { const apiError = error.response.data as ApiError; if (apiError && apiError.error) { throw new FaydaAuthError(apiError); } } // Generic error for when the API doesn't return a standard error format throw new FaydaAuthError({ success: false, error: 'UNKNOWN_ERROR', message: 'An unexpected error occurred. Please try again later.', statusCode: 500, timestamp: new Date().toISOString(), details: { originalError: error instanceof Error ? error.message : String(error) } }); } async initiateOTP(fcn: string): Promise<InitiateOTPResponse> { try { const response = await this.client.post<InitiateOTPResponse>('/otp/initiate', { fcn }); return response.data; } catch (error) { this.handleError(error); } } async verifyOTP(transactionId: string, otp: string, fcn: string): Promise<VerifyOTPResponse> { try { const response = await this.client.post<VerifyOTPResponse>('/otp/verify', { transactionId, otp, fcn }); return response.data; } catch (error) { this.handleError(error); } } }