You've already forked AstralRinth
forked from didirus/AstralRinth
feat: base api-client impl (#4694)
* feat: base api-client impl * fix: doc * feat: start work on module stuff * feat: migrate v2/v3 projects into module system * fix: lint & README.md contributing * refactor: remove utils old api client prototype * fix: lint * fix: api url issues * fix: baseurl in error.vue * fix: readme * fix typo in readme * Update apps/frontend/src/providers/api-client.ts Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Signed-off-by: Calum H. <hendersoncal117@gmail.com> * Update packages/api-client/src/features/verbose-logging.ts Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Signed-off-by: Calum H. <hendersoncal117@gmail.com> * Update packages/api-client/src/features/retry.ts Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Signed-off-by: Calum H. <hendersoncal117@gmail.com> --------- Signed-off-by: Calum H. <hendersoncal117@gmail.com> Co-authored-by: Prospector <6166773+Prospector@users.noreply.github.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
310
packages/api-client/src/core/abstract-client.ts
Normal file
310
packages/api-client/src/core/abstract-client.ts
Normal file
@@ -0,0 +1,310 @@
|
||||
import type { InferredClientModules } from '../modules'
|
||||
import { buildModuleStructure } from '../modules'
|
||||
import type { ClientConfig } from '../types/client'
|
||||
import type { RequestContext, RequestOptions } from '../types/request'
|
||||
import type { AbstractFeature } from './abstract-feature'
|
||||
import type { AbstractModule } from './abstract-module'
|
||||
import { ModrinthApiError, ModrinthServerError } from './errors'
|
||||
|
||||
/**
|
||||
* Abstract base client for Modrinth APIs
|
||||
*/
|
||||
export abstract class AbstractModrinthClient {
|
||||
protected config: ClientConfig
|
||||
protected features: AbstractFeature[]
|
||||
|
||||
/**
|
||||
* Maps full module ID (e.g., 'labrinth_projects_v2') to instantiated module
|
||||
*/
|
||||
private _moduleInstances: Map<string, AbstractModule> = new Map()
|
||||
|
||||
/**
|
||||
* Maps API name (e.g., 'labrinth') to namespace object
|
||||
*/
|
||||
private _moduleNamespaces: Map<string, Record<string, AbstractModule>> = new Map()
|
||||
|
||||
// TODO: When adding kyros/archon add readonly fields for those too.
|
||||
public readonly labrinth!: InferredClientModules['labrinth']
|
||||
|
||||
constructor(config: ClientConfig) {
|
||||
this.config = {
|
||||
timeout: 10000,
|
||||
labrinthBaseUrl: 'https://api.modrinth.com',
|
||||
archonBaseUrl: 'https://archon.modrinth.com',
|
||||
...config,
|
||||
}
|
||||
this.features = config.features ?? []
|
||||
this.initializeModules()
|
||||
}
|
||||
|
||||
/**
|
||||
* This creates the nested API structure (e.g., client.labrinth.projects_v2)
|
||||
* but doesn't instantiate modules until first access
|
||||
*
|
||||
* Module IDs in the registry are validated at runtime to ensure they match
|
||||
* what the module declares via getModuleID().
|
||||
*/
|
||||
private initializeModules(): void {
|
||||
const structure = buildModuleStructure()
|
||||
|
||||
for (const [api, modules] of Object.entries(structure)) {
|
||||
const namespaceObj: Record<string, AbstractModule> = {}
|
||||
|
||||
// Define lazy getters for each module
|
||||
for (const [moduleName, ModuleConstructor] of Object.entries(modules)) {
|
||||
const fullModuleId = `${api}_${moduleName}`
|
||||
|
||||
Object.defineProperty(namespaceObj, moduleName, {
|
||||
get: () => {
|
||||
// Lazy instantiation
|
||||
if (!this._moduleInstances.has(fullModuleId)) {
|
||||
const instance = new ModuleConstructor(this)
|
||||
|
||||
// Validate the module ID matches what we expect
|
||||
const declaredId = instance.getModuleID()
|
||||
if (declaredId !== fullModuleId) {
|
||||
throw new Error(
|
||||
`Module ID mismatch: registry expects "${fullModuleId}" but module declares "${declaredId}"`,
|
||||
)
|
||||
}
|
||||
|
||||
this._moduleInstances.set(fullModuleId, instance)
|
||||
}
|
||||
return this._moduleInstances.get(fullModuleId)!
|
||||
},
|
||||
enumerable: true,
|
||||
configurable: false,
|
||||
})
|
||||
}
|
||||
|
||||
// Assign namespace to client (e.g., this.labrinth = namespaceObj)
|
||||
// defineProperty bypasses readonly restriction
|
||||
Object.defineProperty(this, api, {
|
||||
value: namespaceObj,
|
||||
writable: false,
|
||||
enumerable: true,
|
||||
configurable: false,
|
||||
})
|
||||
|
||||
this._moduleNamespaces.set(api, namespaceObj)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Make a request to the API
|
||||
*
|
||||
* @param path - API path (e.g., '/project/sodium')
|
||||
* @param options - Request options
|
||||
* @returns Promise resolving to the response data
|
||||
* @throws {ModrinthApiError} When the request fails or features throw errors
|
||||
*/
|
||||
async request<T>(path: string, options: RequestOptions): Promise<T> {
|
||||
let baseUrl: string
|
||||
if (options.api === 'labrinth') {
|
||||
baseUrl = this.config.labrinthBaseUrl!
|
||||
} else if (options.api === 'archon') {
|
||||
baseUrl = this.config.archonBaseUrl!
|
||||
} else {
|
||||
baseUrl = options.api
|
||||
}
|
||||
|
||||
const url = this.buildUrl(path, baseUrl, options.version)
|
||||
|
||||
// Merge options with defaults
|
||||
const mergedOptions: RequestOptions = {
|
||||
method: 'GET',
|
||||
timeout: this.config.timeout,
|
||||
...options,
|
||||
headers: {
|
||||
...this.buildDefaultHeaders(),
|
||||
...options.headers,
|
||||
},
|
||||
}
|
||||
|
||||
const context = this.buildContext(url, path, mergedOptions)
|
||||
|
||||
try {
|
||||
const result = await this.executeFeatureChain<T>(context)
|
||||
|
||||
await this.config.hooks?.onResponse?.(result, context)
|
||||
|
||||
return result
|
||||
} catch (error) {
|
||||
const apiError = this.normalizeError(error, context)
|
||||
await this.config.hooks?.onError?.(apiError, context)
|
||||
|
||||
throw apiError
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the feature chain and the actual request
|
||||
*
|
||||
* Features are executed in order, with each feature calling next() to continue.
|
||||
* The last "feature" in the chain is the actual request execution.
|
||||
*/
|
||||
protected async executeFeatureChain<T>(context: RequestContext): Promise<T> {
|
||||
// Filter to only features that should apply
|
||||
const applicableFeatures = this.features.filter((feature) => feature.shouldApply(context))
|
||||
|
||||
// Build the feature chain
|
||||
// We work backwards from the actual request, wrapping each feature around the previous
|
||||
let index = applicableFeatures.length
|
||||
|
||||
const next = async (): Promise<T> => {
|
||||
index--
|
||||
|
||||
if (index >= 0) {
|
||||
// Execute the next feature in the chain
|
||||
const feature = applicableFeatures[index]
|
||||
return feature.execute(next, context)
|
||||
} else {
|
||||
// We've reached the end of the chain, execute the actual request
|
||||
await this.config.hooks?.onRequest?.(context)
|
||||
return this.executeRequest<T>(context.url, context.options)
|
||||
}
|
||||
}
|
||||
|
||||
return next()
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the full URL for a request
|
||||
*/
|
||||
protected buildUrl(path: string, baseUrl: string, version: number | 'internal'): string {
|
||||
// Remove trailing slash from base URL
|
||||
const base = baseUrl.replace(/\/$/, '')
|
||||
|
||||
// Build version path
|
||||
let versionPath = ''
|
||||
if (version === 'internal') {
|
||||
versionPath = '/_internal'
|
||||
} else if (typeof version === 'number') {
|
||||
versionPath = `/v${version}`
|
||||
}
|
||||
|
||||
const cleanPath = path.startsWith('/') ? path : `/${path}`
|
||||
|
||||
return `${base}${versionPath}${cleanPath}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the request context
|
||||
*/
|
||||
protected buildContext(url: string, path: string, options: RequestOptions): RequestContext {
|
||||
return {
|
||||
url,
|
||||
path,
|
||||
options,
|
||||
attempt: 1,
|
||||
startTime: Date.now(),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build default headers for all requests
|
||||
*
|
||||
* Subclasses can override this to add platform-specific headers
|
||||
* (e.g., Nuxt rate limit key)
|
||||
*/
|
||||
protected buildDefaultHeaders(): Record<string, string> {
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
...this.config.headers,
|
||||
}
|
||||
|
||||
if (this.config.userAgent) {
|
||||
headers['User-Agent'] = this.config.userAgent
|
||||
}
|
||||
|
||||
return headers
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the actual HTTP request
|
||||
*
|
||||
* This must be implemented by platform-specific clients.
|
||||
*
|
||||
* @param url - Full URL to request
|
||||
* @param options - Request options
|
||||
* @returns Promise resolving to the response data
|
||||
* @throws {Error} Platform-specific errors that will be normalized by normalizeError()
|
||||
*/
|
||||
protected abstract executeRequest<T>(url: string, options: RequestOptions): Promise<T>
|
||||
|
||||
/**
|
||||
* Normalize an error into a ModrinthApiError
|
||||
*
|
||||
* Platform implementations should override this to handle platform-specific errors
|
||||
* (e.g., FetchError from ofetch, Tauri HTTP errors)
|
||||
*/
|
||||
protected normalizeError(error: unknown, context?: RequestContext): ModrinthApiError {
|
||||
if (error instanceof ModrinthApiError) {
|
||||
return error
|
||||
}
|
||||
|
||||
return ModrinthApiError.fromUnknown(error, context?.path)
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to create a normalized error from extracted status code and response data
|
||||
*/
|
||||
protected createNormalizedError(
|
||||
error: Error,
|
||||
statusCode: number | undefined,
|
||||
responseData: unknown,
|
||||
): ModrinthApiError {
|
||||
if (statusCode && responseData) {
|
||||
return ModrinthServerError.fromResponse(statusCode, responseData)
|
||||
}
|
||||
|
||||
return new ModrinthApiError(error.message, {
|
||||
statusCode,
|
||||
originalError: error,
|
||||
responseData,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a feature to this client
|
||||
*
|
||||
* Features are executed in the order they are added.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const client = new GenericModrinthClient()
|
||||
* client.addFeature(new AuthFeature({ token: 'mrp_...' }))
|
||||
* client.addFeature(new RetryFeature({ maxAttempts: 3 }))
|
||||
* ```
|
||||
*/
|
||||
addFeature(feature: AbstractFeature): this {
|
||||
this.features.push(feature)
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a feature from this client
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const retryFeature = new RetryFeature({ maxAttempts: 3 })
|
||||
* client.addFeature(retryFeature)
|
||||
* // Later, remove it
|
||||
* client.removeFeature(retryFeature)
|
||||
* ```
|
||||
*/
|
||||
removeFeature(feature: AbstractFeature): this {
|
||||
const index = this.features.indexOf(feature)
|
||||
if (index !== -1) {
|
||||
this.features.splice(index, 1)
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all features on this client
|
||||
*/
|
||||
getFeatures(): AbstractFeature[] {
|
||||
return [...this.features]
|
||||
}
|
||||
}
|
||||
91
packages/api-client/src/core/abstract-feature.ts
Normal file
91
packages/api-client/src/core/abstract-feature.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import type { RequestContext } from '../types/request'
|
||||
|
||||
/**
|
||||
* Base configuration for features
|
||||
*/
|
||||
export interface FeatureConfig {
|
||||
/**
|
||||
* Optional name for this feature (for debugging)
|
||||
*/
|
||||
name?: string
|
||||
|
||||
/**
|
||||
* Whether this feature is enabled
|
||||
* @default true
|
||||
*/
|
||||
enabled?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Abstract base class for request features
|
||||
*
|
||||
* Features are composable middleware that can intercept and modify requests.
|
||||
* They are executed in a chain, with each feature calling next() to continue the chain.
|
||||
*/
|
||||
export abstract class AbstractFeature {
|
||||
protected config: FeatureConfig
|
||||
|
||||
constructor(config?: FeatureConfig) {
|
||||
this.config = {
|
||||
enabled: true,
|
||||
...config,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the feature logic
|
||||
*
|
||||
* @param next - Function to call the next feature in the chain (or the actual request)
|
||||
* @param context - Full request context
|
||||
* @returns Promise resolving to the response data
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* async execute<T>(next: () => Promise<T>, context: RequestContext): Promise<T> {
|
||||
* // Do something before request
|
||||
* console.log('Before request:', context.url)
|
||||
*
|
||||
* try {
|
||||
* const result = await next()
|
||||
*
|
||||
* // Do something after successful request
|
||||
* console.log('Request succeeded')
|
||||
*
|
||||
* return result
|
||||
* } catch (error) {
|
||||
* // Handle errors
|
||||
* console.error('Request failed:', error)
|
||||
* throw error
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
abstract execute<T>(next: () => Promise<T>, context: RequestContext): Promise<T>
|
||||
|
||||
/**
|
||||
* Determine if this feature should apply to the given request
|
||||
*
|
||||
* By default, features apply if they are enabled.
|
||||
* Override this to add custom logic (e.g., only apply to GET requests).
|
||||
*
|
||||
* @param context - Request context
|
||||
* @returns true if the feature should execute, false to skip
|
||||
*/
|
||||
shouldApply(_context: RequestContext): boolean {
|
||||
return this.config.enabled !== false
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the name of this feature (for debugging)
|
||||
*/
|
||||
get name(): string {
|
||||
return this.config.name ?? this.constructor.name
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this feature is enabled
|
||||
*/
|
||||
get enabled(): boolean {
|
||||
return this.config.enabled !== false
|
||||
}
|
||||
}
|
||||
15
packages/api-client/src/core/abstract-module.ts
Normal file
15
packages/api-client/src/core/abstract-module.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import type { AbstractModrinthClient } from './abstract-client'
|
||||
|
||||
export abstract class AbstractModule {
|
||||
protected client: AbstractModrinthClient
|
||||
|
||||
public constructor(client: AbstractModrinthClient) {
|
||||
this.client = client
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the module's name, used for error reporting & for module field generation.
|
||||
* @returns Module name
|
||||
*/
|
||||
public abstract getModuleID(): string
|
||||
}
|
||||
142
packages/api-client/src/core/errors.ts
Normal file
142
packages/api-client/src/core/errors.ts
Normal file
@@ -0,0 +1,142 @@
|
||||
import type { ApiErrorData, ModrinthErrorResponse } from '../types/errors'
|
||||
import { isModrinthErrorResponse } from '../types/errors'
|
||||
|
||||
/**
|
||||
* Base error class for all Modrinth API errors
|
||||
*/
|
||||
export class ModrinthApiError extends Error {
|
||||
/**
|
||||
* HTTP status code (if available)
|
||||
*/
|
||||
readonly statusCode?: number
|
||||
|
||||
/**
|
||||
* Original error that was caught
|
||||
*/
|
||||
readonly originalError?: Error
|
||||
|
||||
/**
|
||||
* Response data from the API (if available)
|
||||
*/
|
||||
readonly responseData?: unknown
|
||||
|
||||
/**
|
||||
* Error context (e.g., module name, operation being performed)
|
||||
*/
|
||||
readonly context?: string
|
||||
|
||||
constructor(message: string, data?: ApiErrorData) {
|
||||
super(message)
|
||||
this.name = 'ModrinthApiError'
|
||||
|
||||
this.statusCode = data?.statusCode
|
||||
this.originalError = data?.originalError
|
||||
this.responseData = data?.responseData
|
||||
this.context = data?.context
|
||||
|
||||
// Maintains proper stack trace for where our error was thrown (only available on V8)
|
||||
if (Error.captureStackTrace) {
|
||||
Error.captureStackTrace(this, ModrinthApiError)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a ModrinthApiError from an unknown error
|
||||
*/
|
||||
static fromUnknown(error: unknown, context?: string): ModrinthApiError {
|
||||
if (error instanceof ModrinthApiError) {
|
||||
return error
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
return new ModrinthApiError(error.message, {
|
||||
originalError: error,
|
||||
context,
|
||||
})
|
||||
}
|
||||
|
||||
return new ModrinthApiError(String(error), { context })
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Error class for Modrinth server errors (kyros/archon)
|
||||
* Extends ModrinthApiError with V1 error response parsing
|
||||
*/
|
||||
export class ModrinthServerError extends ModrinthApiError {
|
||||
/**
|
||||
* V1 error information (if available)
|
||||
*/
|
||||
readonly v1Error?: ModrinthErrorResponse
|
||||
|
||||
constructor(message: string, data?: ApiErrorData & { v1Error?: ModrinthErrorResponse }) {
|
||||
// If we have a V1 error, format the message nicely
|
||||
let errorMessage = message
|
||||
if (data?.v1Error) {
|
||||
errorMessage = `[${data.v1Error.error}] ${data.v1Error.description}`
|
||||
if (data.v1Error.context) {
|
||||
errorMessage = `${data.v1Error.context}: ${errorMessage}`
|
||||
}
|
||||
}
|
||||
|
||||
super(errorMessage, data)
|
||||
this.name = 'ModrinthServerError'
|
||||
this.v1Error = data?.v1Error
|
||||
|
||||
if (Error.captureStackTrace) {
|
||||
Error.captureStackTrace(this, ModrinthServerError)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a ModrinthServerError from response data
|
||||
*/
|
||||
static fromResponse(
|
||||
statusCode: number,
|
||||
responseData: unknown,
|
||||
context?: string,
|
||||
): ModrinthServerError {
|
||||
const v1Error = isModrinthErrorResponse(responseData) ? responseData : undefined
|
||||
|
||||
let message = `HTTP ${statusCode}`
|
||||
if (v1Error) {
|
||||
message = v1Error.description
|
||||
} else if (typeof responseData === 'string') {
|
||||
message = responseData
|
||||
}
|
||||
|
||||
return new ModrinthServerError(message, {
|
||||
statusCode,
|
||||
responseData,
|
||||
context,
|
||||
v1Error,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a ModrinthServerError from an unknown error
|
||||
*/
|
||||
static fromUnknown(error: unknown, context?: string): ModrinthServerError {
|
||||
if (error instanceof ModrinthServerError) {
|
||||
return error
|
||||
}
|
||||
|
||||
if (error instanceof ModrinthApiError) {
|
||||
return new ModrinthServerError(error.message, {
|
||||
statusCode: error.statusCode,
|
||||
originalError: error.originalError,
|
||||
responseData: error.responseData,
|
||||
context: context ?? error.context,
|
||||
})
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
return new ModrinthServerError(error.message, {
|
||||
originalError: error,
|
||||
context,
|
||||
})
|
||||
}
|
||||
|
||||
return new ModrinthServerError(String(error), { context })
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user