mirror of
https://github.com/SamyRai/turash.git
synced 2025-12-26 23:01:33 +00:00
- Remove nested git repository from bugulma/frontend/.git - Add all frontend files to main repository tracking - Convert from separate frontend/backend repos to unified monorepo - Preserve all frontend code and development history as tracked files - Eliminate nested repository complexity for simpler development workflow This creates a proper monorepo structure with frontend and backend coexisting in the same repository for easier development and deployment.
348 lines
9.4 KiB
TypeScript
348 lines
9.4 KiB
TypeScript
/**
|
|
* Service Base Class
|
|
* Provides common patterns and utilities for API services
|
|
* Reduces boilerplate and ensures consistency across services
|
|
*/
|
|
|
|
import { z, ZodSchema } from 'zod';
|
|
import { httpClient } from '@/lib/http-client';
|
|
import { validateData, validateDataStrict, validateArrayWithFallback, ValidationResult } from '@/lib/schema-validation';
|
|
import { QueryBuilder } from '@/lib/query-builder';
|
|
|
|
// Service configuration interface
|
|
export interface ServiceConfig {
|
|
basePath: string;
|
|
enableLogging?: boolean;
|
|
defaultTimeout?: number;
|
|
retries?: number;
|
|
}
|
|
|
|
// Generic service response types
|
|
export interface ServiceResponse<T> {
|
|
data: T;
|
|
success: boolean;
|
|
error?: string;
|
|
}
|
|
|
|
// Base service class
|
|
export abstract class BaseService {
|
|
protected config: Required<ServiceConfig>;
|
|
|
|
constructor(config: ServiceConfig) {
|
|
this.config = {
|
|
enableLogging: import.meta.env.DEV,
|
|
defaultTimeout: 30000,
|
|
retries: 3,
|
|
...config,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Build full endpoint path
|
|
*/
|
|
protected buildEndpoint(path: string = ''): string {
|
|
const base = this.config.basePath.replace(/\/$/, ''); // Remove trailing slash
|
|
const cleanPath = path.replace(/^\//, ''); // Remove leading slash
|
|
return cleanPath ? `${base}/${cleanPath}` : base;
|
|
}
|
|
|
|
/**
|
|
* Execute HTTP GET request with validation
|
|
*/
|
|
protected async get<T>(
|
|
path: string,
|
|
schema: ZodSchema<T>,
|
|
queryParams?: Record<string, unknown>,
|
|
options?: {
|
|
context?: string;
|
|
useArrayFallback?: boolean;
|
|
timeout?: number;
|
|
}
|
|
): Promise<ValidationResult<T>> {
|
|
const { context, useArrayFallback, timeout } = options || {};
|
|
const endpoint = this.buildEndpoint(path);
|
|
const url = queryParams ? QueryBuilder.create().params(queryParams).toUrl(endpoint) : endpoint;
|
|
|
|
if (this.config.enableLogging) {
|
|
console.log(`[Service:${this.constructor.name}] GET ${url}`);
|
|
}
|
|
|
|
try {
|
|
const rawData = await httpClient.get(url, {
|
|
timeout: timeout || this.config.defaultTimeout,
|
|
retries: this.config.retries,
|
|
});
|
|
|
|
if (useArrayFallback && Array.isArray(rawData)) {
|
|
return validateArrayWithFallback(schema, rawData, { context });
|
|
}
|
|
|
|
return validateData(schema, rawData, {
|
|
context: context || `${this.constructor.name}.get`,
|
|
logErrors: this.config.enableLogging,
|
|
});
|
|
} catch (error) {
|
|
const errorMessage = `GET ${endpoint} failed: ${error instanceof Error ? error.message : 'Unknown error'}`;
|
|
|
|
if (this.config.enableLogging) {
|
|
console.error(`[Service:${this.constructor.name}] ${errorMessage}`, error);
|
|
}
|
|
|
|
return {
|
|
success: false,
|
|
error: {
|
|
message: errorMessage,
|
|
details: [],
|
|
},
|
|
};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Execute HTTP POST request with validation
|
|
*/
|
|
protected async post<T>(
|
|
path: string,
|
|
data: unknown,
|
|
schema: ZodSchema<T>,
|
|
options?: {
|
|
context?: string;
|
|
timeout?: number;
|
|
isFormData?: boolean;
|
|
}
|
|
): Promise<ValidationResult<T>> {
|
|
const { context, timeout, isFormData } = options || {};
|
|
const endpoint = this.buildEndpoint(path);
|
|
|
|
if (this.config.enableLogging) {
|
|
console.log(`[Service:${this.constructor.name}] POST ${endpoint}`, isFormData ? 'FormData' : data);
|
|
}
|
|
|
|
try {
|
|
const rawData = isFormData
|
|
? await httpClient.post(endpoint, data as FormData, {
|
|
timeout: timeout || this.config.defaultTimeout,
|
|
retries: this.config.retries,
|
|
})
|
|
: await httpClient.post(endpoint, data, {
|
|
timeout: timeout || this.config.defaultTimeout,
|
|
retries: this.config.retries,
|
|
});
|
|
|
|
return validateData(schema, rawData, {
|
|
context: context || `${this.constructor.name}.post`,
|
|
logErrors: this.config.enableLogging,
|
|
});
|
|
} catch (error) {
|
|
const errorMessage = `POST ${endpoint} failed: ${error instanceof Error ? error.message : 'Unknown error'}`;
|
|
|
|
if (this.config.enableLogging) {
|
|
console.error(`[Service:${this.constructor.name}] ${errorMessage}`, error);
|
|
}
|
|
|
|
return {
|
|
success: false,
|
|
error: {
|
|
message: errorMessage,
|
|
details: [],
|
|
},
|
|
};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Execute HTTP PUT request with validation
|
|
*/
|
|
protected async put<T>(
|
|
path: string,
|
|
data: unknown,
|
|
schema: ZodSchema<T>,
|
|
options?: {
|
|
context?: string;
|
|
timeout?: number;
|
|
}
|
|
): Promise<ValidationResult<T>> {
|
|
const { context, timeout } = options || {};
|
|
const endpoint = this.buildEndpoint(path);
|
|
|
|
if (this.config.enableLogging) {
|
|
console.log(`[Service:${this.constructor.name}] PUT ${endpoint}`, data);
|
|
}
|
|
|
|
try {
|
|
const rawData = await httpClient.put(endpoint, data, {
|
|
timeout: timeout || this.config.defaultTimeout,
|
|
retries: this.config.retries,
|
|
});
|
|
|
|
return validateData(schema, rawData, {
|
|
context: context || `${this.constructor.name}.put`,
|
|
logErrors: this.config.enableLogging,
|
|
});
|
|
} catch (error) {
|
|
const errorMessage = `PUT ${endpoint} failed: ${error instanceof Error ? error.message : 'Unknown error'}`;
|
|
|
|
if (this.config.enableLogging) {
|
|
console.error(`[Service:${this.constructor.name}] ${errorMessage}`, error);
|
|
}
|
|
|
|
return {
|
|
success: false,
|
|
error: {
|
|
message: errorMessage,
|
|
details: [],
|
|
},
|
|
};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Execute HTTP DELETE request
|
|
*/
|
|
protected async delete(
|
|
path: string,
|
|
options?: {
|
|
context?: string;
|
|
timeout?: number;
|
|
}
|
|
): Promise<ValidationResult<void>> {
|
|
const { context, timeout } = options || {};
|
|
const endpoint = this.buildEndpoint(path);
|
|
|
|
if (this.config.enableLogging) {
|
|
console.log(`[Service:${this.constructor.name}] DELETE ${endpoint}`);
|
|
}
|
|
|
|
try {
|
|
await httpClient.delete(endpoint, {
|
|
timeout: timeout || this.config.defaultTimeout,
|
|
retries: this.config.retries,
|
|
});
|
|
|
|
return { success: true, data: undefined };
|
|
} catch (error) {
|
|
const errorMessage = `DELETE ${endpoint} failed: ${error instanceof Error ? error.message : 'Unknown error'}`;
|
|
|
|
if (this.config.enableLogging) {
|
|
console.error(`[Service:${this.constructor.name}] ${errorMessage}`, error);
|
|
}
|
|
|
|
return {
|
|
success: false,
|
|
error: {
|
|
message: errorMessage,
|
|
details: [],
|
|
},
|
|
};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Strict validation wrapper (throws on failure)
|
|
*/
|
|
protected validateStrict<T>(schema: ZodSchema<T>, data: unknown, context?: string): T {
|
|
return validateDataStrict(schema, data, context || this.constructor.name);
|
|
}
|
|
|
|
/**
|
|
* Create a query builder for this service
|
|
*/
|
|
protected createQuery(): QueryBuilder {
|
|
return QueryBuilder.create();
|
|
}
|
|
|
|
/**
|
|
* Log service events (only in development)
|
|
*/
|
|
protected log(message: string, ...args: unknown[]): void {
|
|
if (this.config.enableLogging) {
|
|
console.log(`[Service:${this.constructor.name}] ${message}`, ...args);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Log errors (only in development)
|
|
*/
|
|
protected logError(message: string, error?: unknown): void {
|
|
if (this.config.enableLogging) {
|
|
console.error(`[Service:${this.constructor.name}] ${message}`, error);
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* CRUD Service mixin for common patterns
|
|
*/
|
|
export abstract class CrudService<T, TCreate, TUpdate = Partial<TCreate>> extends BaseService {
|
|
protected abstract entitySchema: ZodSchema<T>;
|
|
protected abstract createSchema: ZodSchema<TCreate>;
|
|
protected abstract updateSchema: ZodSchema<TUpdate>;
|
|
|
|
/**
|
|
* Get all entities
|
|
*/
|
|
async getAll(options?: {
|
|
query?: Record<string, unknown>;
|
|
context?: string;
|
|
useArrayFallback?: boolean;
|
|
}): Promise<ValidationResult<T[]>> {
|
|
return this.get('', this.entitySchema.array(), options?.query, {
|
|
context: options?.context || 'getAll',
|
|
useArrayFallback: options?.useArrayFallback ?? true,
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Get entity by ID
|
|
*/
|
|
async getById(id: string, options?: { context?: string }): Promise<ValidationResult<T>> {
|
|
return this.get(id, this.entitySchema, undefined, {
|
|
context: options?.context || `getById(${id})`,
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Create new entity
|
|
*/
|
|
async create(data: TCreate, options?: { context?: string }): Promise<ValidationResult<T>> {
|
|
const validatedData = this.validateStrict(this.createSchema, data, 'create validation');
|
|
return this.post('', validatedData, this.entitySchema, {
|
|
context: options?.context || 'create',
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Update entity
|
|
*/
|
|
async update(id: string, data: TUpdate, options?: { context?: string }): Promise<ValidationResult<T>> {
|
|
const validatedData = this.validateStrict(this.updateSchema, data, 'update validation');
|
|
return this.put(id, validatedData, this.entitySchema, {
|
|
context: options?.context || `update(${id})`,
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Delete entity
|
|
*/
|
|
async remove(id: string, options?: { context?: string }): Promise<ValidationResult<void>> {
|
|
return this.delete(id, {
|
|
context: options?.context || `delete(${id})`,
|
|
});
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Factory function to create service instances
|
|
*/
|
|
export function createService<T extends BaseService>(
|
|
ServiceClass: new (config: ServiceConfig) => T,
|
|
basePath: string,
|
|
options?: Partial<ServiceConfig>
|
|
): T {
|
|
return new ServiceClass({
|
|
basePath,
|
|
enableLogging: import.meta.env.DEV,
|
|
...options,
|
|
});
|
|
}
|