trestle_client
v1.1.45
Published
trestle client library
Readme
Trestle Client
Trestle Client is a JavaScript/Node.js library designed to interact with the Trestle API. It provides functionality to make API requests, handle authentication, and manage errors effectively.
Features
- API Request Handling: Make requests to the Trestle API with appropriate error handling for different response statuses (e.g., 401, 429, 500).
- Authentication: Supports token retrieval for authentication and handles errors related to authentication failures.
- Error Handling: Includes custom error classes to handle different API errors such as authentication errors, rate limits, and general API errors.
- Logger: Provides a logging utility to capture different levels of logs (debug, info, warn, error).
- Metadata Parsing: Helps in parsing XML metadata to extract schema names for further processing.
Installation
To install and use the Trestle Client library, follow these steps:
1. Install Dependencies
You need to install the required dependencies before using the Trestle Client.
npm installIf you're using it as part of an existing Node.js project, you can install it via:
npm install --save <path-to-trestle-client>2. Add the Library to Your Project
import { TrestleClient } from 'trestle-client';
import { TrestleAuth } from 'trestle-client';
import { parseMetadata } from 'trestle-client';
import { getLogger } from 'trestle-client';Functionality
1. TrestleClient
TrestleClient is the core class to interact with the Trestle API. It provides the method makeRequest for making HTTP requests to the Trestle API.
Methods
makeRequest(endpoint: string): Promise<Object>: Makes a GET request to the specified API endpoint and returns the data.- Handles different response statuses (e.g., 401 for Unauthorized, 429 for Rate Limiting, and 500 for Server Errors).
Example
import { TrestleClient } from 'trestle-client';
const trestleClient = new TrestleClient();
// Successful request example
const data = await trestleClient.makeRequest('mock-endpoint');
console.log(data); // { result: 'mock-data' }2. TrestleAuth
TrestleAuth helps in authenticating with the Trestle API by retrieving an authentication token.
Methods
getToken(): Promise<string>: Retrieves an access token for API authentication.
Example
import { TrestleAuth } from 'trestle-client';
const trestleAuth = new TrestleAuth();
// Fetch token example
const token = await trestleAuth.getToken();
console.log(token); // 'mock-token'3. Error Handling
The library includes custom error classes to handle different types of API errors.
TrestleAPIError: A general error class for handling API errors with a status code and error message.TrestleAuthError: Specific to authentication errors (e.g., 401 Unauthorized).TrestleRateLimitError: Specific to rate limit errors (e.g., 429 Too Many Requests).
Example
import { TrestleAPIError, TrestleAuthError, TrestleRateLimitError } from 'trestle-client';
try {
// Simulating an error
throw new TrestleAuthError({ status_code: 401, json: () => ({ error: 'Unauthorized' }) });
} catch (error) {
if (error instanceof TrestleAuthError) {
console.error('Authentication error occurred:', error.message); // 'Authentication failed'
}
}4. Logger
The logger utility is used to log messages with various severity levels, including debug, info, warn, and error.
Methods
getLogger(name: string, level: string): Logger: Returns a logger instance with the specified name and log level.
Example
import { getLogger } from 'trestle-client';
const logger = getLogger('TestLogger', 'debug');
logger.debug('This is a debug message');
logger.info('This is an info message');5. Metadata Parsing
parseMetadata is a utility function that parses XML metadata and extracts schema names.
Method
parseMetadata(metadata: string): Array<string>: Parses XML metadata and returns an array of schema names.
Example
import { parseMetadata } from 'trestle-client';
const metadata = `
<Schema Namespace="Schema1" />
<Schema Namespace="Schema2" />
<Schema Namespace="Schema3" />
`;
const schemas = parseMetadata(metadata);
console.log(schemas); // ['Schema1', 'Schema2', 'Schema3']Usage Examples
1. Making API Requests
import { TrestleClient } from 'trestle-client';
const trestleClient = new TrestleClient();
try {
const data = await trestleClient.makeRequest('mock-endpoint');
console.log(data); // Expected output: { result: 'mock-data' }
} catch (error) {
console.error('Request failed:', error);
}2. Retrieving an Authentication Token
import { TrestleAuth } from 'trestle-client';
const trestleAuth = new TrestleAuth();
try {
const token = await trestleAuth.getToken();
console.log(token); // Expected output: 'mock-token'
} catch (error) {
console.error('Failed to retrieve token:', error);
}3. Handling Errors
import { TrestleAuthError } from 'trestle-client';
try {
// Simulating an authentication error
throw new TrestleAuthError({ status_code: 401, json: () => ({ error: 'Unauthorized' }) });
} catch (error) {
if (error instanceof TrestleAuthError) {
console.error('Authentication error:', error.message); // Output: Authentication failed
}
}4. Logging Messages
import { getLogger } from 'trestle-client';
const logger = getLogger('AppLogger', 'debug');
logger.debug('Debug message');
logger.info('Informational message');
logger.warn('Warning message');
logger.error('Error message');Testing
To run the tests for this project, use the following command:
npm testMake sure to use a testing framework such as Mocha or Jest for running tests.
