@vvlad1973/base-api
v1.1.1
Published
Base API class with OpenAPI validation
Maintainers
Readme
@vvlad1973/base-api
Base API class with OpenAPI schema validation.
Features
- OpenAPI 3.0+ specification support
- Automatic parameter validation using JSON Schema
- Event emitter support for API events
- TypeScript support with full type definitions
- Transport layer abstraction via
ITransport
Installation
npm install @vvlad1973/base-apiUsage
Basic API Client
import {
BaseApi,
type BaseApiOptions,
type HttpMethod,
type ApiCallOptions,
} from '@vvlad1973/base-api';
class MyApi extends BaseApi {
protected async callApi<T>(
operationId: string,
httpMethod: HttpMethod,
endpoint: string,
params: object,
options?: ApiCallOptions
): Promise<T> {
// Implement your API call logic here
const response = await fetch(`/api${endpoint}`, {
method: httpMethod.toUpperCase(),
headers: { 'Content-Type': options?.contentType ?? 'application/json' },
body: JSON.stringify(params),
});
return response.json();
}
}
// Initialize with OpenAPI specification
const options: BaseApiOptions = {
specification: {
openapi: '3.0.0',
info: { title: 'My API', version: '1.0.0' },
components: {
schemas: {},
responses: {},
},
paths: {},
},
};
await MyApi.initializeWithSpec(options);
// Create instance and use
const api = new MyApi();With Async Specification Loading
const options: BaseApiOptions = {
specification: async () => {
const response = await fetch('/api/openapi.json');
return response.json();
},
};
await MyApi.initializeWithSpec(options);Using Transport Abstraction
import {
BaseApi,
type ITransport,
type TransportRequestOptions,
} from '@vvlad1973/base-api';
class MyTransport implements ITransport {
async request<T>(options: TransportRequestOptions): Promise<T> {
// Implement transport logic
}
async close(): Promise<void> {}
}
class MyApi extends BaseApi {
constructor(private transport: ITransport) {
super();
}
protected async callApi<T>(
operationId: string,
httpMethod: HttpMethod,
endpoint: string,
params: object,
options?: ApiCallOptions
): Promise<T> {
return this.transport.request<T>({
operationId,
httpMethod,
endpoint,
params,
routeId: options?.routeId,
contentType: options?.contentType,
});
}
}API Reference
BaseApi
Abstract class that provides OpenAPI validation functionality.
Static Methods
initializeWithSpec(options: BaseApiOptions): Promise<void>- Initialize the validator with OpenAPI specificationinit(options: BaseApiOptions): Promise<void>- Internal initialization method
Protected Methods
callApi<T>(operationId, httpMethod, endpoint, params, options?): Promise<T>- Abstract method to implement API callsexecuteCallApi<T>(operationId, httpMethod, endpoint, params, options?): Promise<T>- Execute API call with parameter validation
Types
interface BaseApiOptions {
specification: OpenApiSpecification | (() => Promise<OpenApiSpecification>);
}
interface ApiCallOptions {
contentType?: string;
routeId?: string;
}
interface ApiCallParams {
path?: Record<string, string | number>;
query?: Record<string, unknown>;
body?: Record<string, unknown>;
}
interface OpenApiSpecification {
openapi: string;
info: { title: string; version: string };
components: {
schemas: Record<string, JsonSchemaItem>;
responses?: Record<string, OpenApiResponse>;
};
paths: Record<string, OpenApiPathItem>;
}
type HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete';Transport Interfaces
interface ITransport {
request<T>(options: TransportRequestOptions): Promise<T>;
close(): Promise<void>;
}
interface TransportRequestOptions {
operationId: string;
httpMethod: HttpMethod;
endpoint: string;
params: object;
routeId?: string;
contentType?: string;
}
interface HttpClientOptions {
baseUrl?: string;
timeout?: number;
retries?: number;
retryDelay?: number;
exponentialBackoff?: boolean;
userAgent?: string;
}
interface TokensData {
addToken(tokenId: string, token: string): boolean;
removeToken(tokenId: string, defaultId?: string): boolean;
getToken(tokenId: string): string | undefined;
setDefaultToken(tokenId: string): boolean;
getDefaultToken(): string | undefined;
getDefaultTokenId(): string | undefined;
getTokenIds(): string[];
hasToken(tokenId: string): boolean;
getTokenCount(): number;
clear(): void;
}Constants
DEFAULT_CONTENT_TYPE- Default content type for API calls ('application/json')JSON_SCHEMA_URL- JSON Schema specification URL ('http://json-schema.org/draft-07/schema#')ContentTypeSuffix- Map of content type to schema name suffix
Utility Functions
capitalize(str: string): string- Capitalize first lettergetMethodOptionsName(methodName: string, suffix?: string): string- Get method options schema nameresolveRefName(ref: string): string- Resolve JSON Schema$refnamegetMethodName(path: string): string- Generate method name from API pathextractMethodName(operationId: string): string- Extract method name fromoperationIdextractApiGroup(operationId: string): string- Extract API group fromoperationIdcollectSchemas(item, sourceMap, destinationMap?, processedLinks?): Map- Collect all referenced schemas recursivelygenerateParamsSchemas(path, request, destinationMap): void- Generate parameter schemas from OpenAPI path
Requirements
- Node.js >= 18.0.0
- npm >= 9.0.0
Dependencies
- @vvlad1973/data-validator - JSON Schema validation
License
MIT License with Commercial Use restrictions. See LICENSE file for details.
Author
Vladislav Vnukovskiy [email protected]
