@tedckh/smart-api-client
v1.0.6
Published
A TypeScript-first API client for quick and robust implementation of RESTful API requests with standardized responses and exception handling. Built on top of [apisauce](https://github.com/infinitered/apisauce) and [axios](https://github.com/axios/axios).
Readme
@tedckh/smart-api-client
A TypeScript-first API client for quick and robust implementation of RESTful API requests with standardized responses and exception handling. Built on top of apisauce and axios.
Features
- Unified API client for RESTful requests
- Standardized error and exception handling
- Authorization header and 401 handler support
- TypeScript ready
Installation
npm install @tedckh/smart-api-clientSample Usage
import { ApiCore, isApiError } from '@tedckh/smart-api-client'
// 1. Configure the API client (set base URL and timeout)
ApiCore.setConfig({
baseUrl: 'https://api.example.com',
timeout: 10000, // 10 seconds
})
// 2. Make a GET request
async function fetchUser(userId: string) {
try {
const user = await ApiCore.primary.get(`/users/${userId}`)
console.log('User data:', user)
return user
} catch (error) {
// 3. Handle standardized API errors
if (isApiError(error)) {
// Handle known API error (e.g., network, timeout, unauthorized, etc.)
console.error('API Error:', error.kind, error.message)
} else {
// Handle unknown/unexpected errors
console.error('Unexpected Error:', error)
}
throw error // rethrow if needed
}
}
// Example usage
fetchUser('12345')
.then(user => {
// Do something with user
})
.catch(err => {
// Error already handled in fetchUser
})Advanced Usage
setApiConfig
You can use setApiConfig to quickly configure the API client globally:
import { setApiConfig } from '@tedckh/smart-api-client'
setApiConfig({
baseUrl: 'https://api.example.com',
timeout: 8000,
headers: {
'X-Custom-Header': 'value',
},
})This is equivalent to calling ApiCore.setConfig and is useful for quick setup.
setDefaultApiErrorHandler
You can set a global error handler for all API errors:
import { ApiCore } from '@tedckh/smart-api-client'
ApiCore.primary.setDefaultApiErrorHandler((err) => {
// Handle all API errors here
console.error('Global API error:', err)
// You can show a toast, log to a service, etc.
})Example: Custom Error Handler (Plain Function)
You can use a plain function for more advanced error handling:
import { ApiCore, isApiError, ApiProblem } from '@tedckh/smart-api-client'
function handleDefaultApiError(error: any) {
if (!isApiError(error)) {
// TODO: handle non-API errors
console.log('is not api error')
return;
}
switch (error.kind as ApiProblem['kind']) {
case 'timeout':
case 'cannot-connect':
case 'server':
case 'unauthorized':
case 'forbidden':
case 'not-found':
case 'rejected':
case 'cancelled':
case 'unknown':
// TODO: handle API errors
console.log('api error')
return
}
}
// Set as the default API error handler
ApiCore.primary.setDefaultApiErrorHandler(handleDefaultApiError)This approach allows you to centralize and customize your API error handling logic, making it easy to integrate with any framework or plain JavaScript/TypeScript projects.
Error Types: ApiProblemKind Enum
The ApiProblemKind enum provides a type-safe way to check and handle different categories of API errors. This is useful for writing robust error handling logic.
Possible Values
ApiProblemKind.Timeout— The request timed outApiProblemKind.CannotConnect— Cannot connect to the serverApiProblemKind.Server— Server error (5xx)ApiProblemKind.Unauthorized— Unauthorized (401)ApiProblemKind.Forbidden— Forbidden (403)ApiProblemKind.NotFound— Resource not found (404)ApiProblemKind.Rejected— Other client error (4xx)ApiProblemKind.Cancelled— Request was cancelledApiProblemKind.Unknown— Unknown error
Example Usage
import { ApiCore, isApiError, ApiProblemKind } from '@tedckh/smart-api-client'
function handleDefaultApiError(error: any) {
if (!isApiError(error)) {
// handle non-API errors
return;
}
switch (error.kind) {
case ApiProblemKind.Timeout:
// handle timeout
break;
case ApiProblemKind.CannotConnect:
// handle cannot connect
break;
case ApiProblemKind.Server:
// handle server error
break;
case ApiProblemKind.Unauthorized:
// handle unauthorized (401)
break;
case ApiProblemKind.Forbidden:
// handle forbidden (403)
break;
case ApiProblemKind.NotFound:
// handle not found (404)
break;
case ApiProblemKind.Rejected:
// handle other client error (4xx)
break;
case ApiProblemKind.Cancelled:
// handle cancelled request
break;
case ApiProblemKind.Unknown:
// handle unknown error
break;
}
}Using the enum ensures type safety and better code completion in your editor.
Build
npm run build