Overview
The service layer provides a clean abstraction for all backend communication. Each service module handles a specific domain (posts, users, auth, etc.) and supports dual-mode operation : mock data for development and real API for production.
All services are located in /src/services/ and follow a consistent pattern for easy maintenance.
Service Architecture
Core Principles
Mock/Real API Toggle Switch between mock data and real backend via configuration
Type Safety Full TypeScript coverage with interface definitions
Error Handling Consistent error handling with fallback values
Centralized Config Single source of truth for API endpoints
API Configuration
All services use the centralized API configuration:
export const API_CONFIG = {
// Toggle between mock and real API
USE_REAL_API: false , // Set to true for production
// Backend base URL
BASE_URL: 'http://localhost:3000/api/v1' ,
// All endpoints
ENDPOINTS: {
LOGIN: '/auths/sign-in' ,
POSTS: '/posts' ,
USERS: '/users' ,
// ... 100+ endpoints
},
TIMEOUT: 30000 ,
RETRY: {
MAX_RETRIES: 3 ,
RETRY_DELAY: 1000
}
};
Development Mode
Production Mode
// USE_REAL_API = false
const posts = await getAllPosts ();
// Returns mock data instantly
// USE_REAL_API = true
const posts = await getAllPosts ();
// Fetches from http://localhost:3000/api/v1/posts
Available Services
1. Auth Service
Module: src/services/authService.ts
Functions: 8
Purpose: User authentication and session management
import {
login ,
register ,
logout ,
validateToken ,
forgotPassword ,
resetPassword
} from '@/services/authService' ;
// Login
const { user , token } = await login ({
email: '[email protected] ' ,
password: 'password123'
});
// Register with auto-transformation
const newUser = await register ({
firstName: 'John' , // Transforms to first_name
lastName: 'Doe' , // Transforms to last_name
email: '[email protected] ' ,
password: 'secure123'
});
// Validate token (works with mock and JWT)
const user = validateToken ( token );
// Logout
await logout ();
// Request password reset
await forgotPassword ({ email: '[email protected] ' });
// Reset with token
await resetPassword ({
token: 'reset-token' ,
newPassword: 'newSecure123'
});
The auth service automatically transforms camelCase to snake_case for backend compatibility.
2. Posts Service
Module: src/services/postsService.ts
Functions: 27 (23 new advanced functions)
Purpose: Complete posts management and analytics
Basic CRUD
Advanced Queries
Statistics
Interactions
Keywords & Categories
import {
getAllPosts ,
updatePostStatus ,
deletePost ,
bulkAction
} from '@/services/postsService' ;
// Get all posts
const posts = await getAllPosts ();
// Update status
await updatePostStatus ( '123' , 'published' );
// Delete post
await deletePost ( '123' );
// Bulk actions
await bulkAction ({
ids: [ '1' , '2' , '3' ],
action: 'publish'
});
import {
getPostsPopulares ,
getPostsTrending ,
getPostsConEngagement ,
getPostsSinComentarios ,
getBorradoresAntiguos
} from '@/services/postsService' ;
// Top 10 popular posts
const popular = await getPostsPopulares ( 10 );
// Trending posts
const trending = await getPostsTrending ( 5 );
// High engagement posts
const engaging = await getPostsConEngagement ( 10 );
// Posts without comments
const noComments = await getPostsSinComentarios ();
// Old drafts
const oldDrafts = await getBorradoresAntiguos ();
import {
getDashboardOverview ,
getEstadisticasPorMes ,
getMejorRendimientoPorAutor
} from '@/services/postsService' ;
// Dashboard stats
const stats = await getDashboardOverview ();
// {
// total: 150,
// published: 100,
// drafts: 30,
// pending: 20,
// totalViews: 50000,
// avgEngagement: 12.5
// }
// Monthly statistics
const monthly = await getEstadisticasPorMes ( 6 );
// Author performance
const authorStats = await getMejorRendimientoPorAutor ( 5 , 10 );
import {
incrementarVista ,
darLike ,
quitarLike
} from '@/services/postsService' ;
// Track view (with optional user and IP)
await incrementarVista ( postId , userId , '192.168.1.1' );
// Like post
await darLike ( postId , userId );
// Unlike post
await quitarLike ( postId , userId );
import {
addKeywordsToPost ,
createAndAddKeywords ,
getPostKeywords ,
removeKeywordsFromPost ,
getKeywordsMasUsadas ,
addCategoriasToPost
} from '@/services/postsService' ;
// Add existing keywords
await addKeywordsToPost ( postId , [ 1 , 2 , 3 ]);
// Create new keywords and add
await createAndAddKeywords ( postId , [
{ keyword: 'SEO' },
{ keyword: 'Marketing' }
]);
// Get post keywords
const keywords = await getPostKeywords ( postId );
// Remove keywords
await removeKeywordsFromPost ( postId , [ 1 , 2 ]);
// Most used keywords
const topKeywords = await getKeywordsMasUsadas ( 20 );
// Add categories
await addCategoriasToPost ( postId , [ 1 , 2 , 3 ]);
3. Users Service
Module: src/services/usersService.ts
Functions: 4
Purpose: User management with role mapping
import {
getAllUsers ,
changeUserRole ,
updateUserStatus ,
deleteUser
} from '@/services/usersService' ;
// List all users
const users = await getAllUsers ();
// Change user role (auto-maps to role ID)
await changeUserRole ( userId , 'editor' );
// Maps: creador→1, administrador→2, editor→3,
// escritor→4, autor→5, comentador→6
// Update status
await updateUserStatus ( userId , 'inactive' );
// Delete user
await deleteUser ( userId );
Module: src/services/commentsService.ts
Functions: 12 (4 new advanced)
Purpose: Comment system with moderation and analytics
Basic Operations
Analytics
import {
getAllComments ,
createComment ,
updateCommentStatus ,
deleteComment ,
getCommentsByPost
} from '@/services/commentsService' ;
// List comments
const comments = await getAllComments ();
// Create comment
await createComment ({
postId: '123' ,
userId: 5 ,
content: 'Great post!' ,
parentId: null // or parent comment ID for replies
});
// Moderate comment
await updateCommentStatus ( commentId , 'approved' );
// Get post comments
const postComments = await getCommentsByPost ( postId );
5. Categories Service
Module: src/services/categoriesService.ts
Functions: 10 (4 new advanced)
Purpose: Category management with hierarchical structure
import {
getAllCategories ,
createCategory ,
updateCategory ,
deleteCategory ,
getCategoriesStats ,
getCategoriesEngagement ,
getCategoriesMejorRendimiento ,
getCategoriesJerarquicas
} from '@/services/categoriesService' ;
// CRUD operations
const categories = await getAllCategories ();
await createCategory ({ nombre: 'Technology' , descripcion: 'Tech posts' });
await updateCategory ( 1 , { nombre: 'Tech & Innovation' });
await deleteCategory ( 1 );
// Analytics
const stats = await getCategoriesStats ();
const engagement = await getCategoriesEngagement ();
const topPerforming = await getCategoriesMejorRendimiento ();
const hierarchy = await getCategoriesJerarquicas ();
6. Estados Service (Post States)
Module: src/services/estadosService.ts
Functions: 7 (all new)
Purpose: Post status management
import {
getAllEstados ,
getEstadoById ,
createEstado ,
updateEstado ,
deleteEstado ,
getEstadosStats ,
getPostsByEstado
} from '@/services/estadosService' ;
// List all states
const estados = await getAllEstados ();
// Create custom state
await createEstado ({
nombre: 'En Revisión' ,
descripcion: 'Post being reviewed'
});
// Get statistics
const stats = await getEstadosStats ();
// { total: 100, porEstado: { 'Borrador': 25, 'Publicado': 50 } }
// Get posts by state
const publishedPosts = await getPostsByEstado ( 'Publicado' );
7. RBAC Service (Roles & Permissions)
Module: src/services/rbacService.ts
Functions: 17 (all new)
Purpose: Complete role-based access control
Roles
Permissions
Assignments
import {
getAllRoles ,
createRol ,
deleteRol ,
deleteRoles
} from '@/services/rbacService' ;
// List roles
const roles = await getAllRoles ();
// Create role
await createRol ({
nombre: 'Moderator' ,
descripcion: 'Can moderate content'
});
// Delete role
await deleteRol ( roleId );
// Delete multiple roles
await deleteRoles ([ 1 , 2 , 3 ]);
import {
getAllPermisos ,
createPermiso ,
deletePermiso ,
deletePermisos
} from '@/services/rbacService' ;
// List permissions
const permisos = await getAllPermisos ();
// Create permission
await createPermiso ({
nombre: 'moderar_comentarios' ,
descripcion: 'Can moderate comments'
});
// Delete permission
await deletePermiso ( permisoId );
import {
getPermisosByRole ,
assignPermisoToRole ,
revokePermisoFromRole ,
revokeManyPermisosFromRole ,
roleHasPermiso ,
getPermisosDeRol
} from '@/services/rbacService' ;
// Assign permission to role
await assignPermisoToRole ( editorRolId , moderatePermisoId );
// Check permission
const canModerate = await roleHasPermiso ( 3 , 'moderar_comentarios' );
// Get all permissions for role
const permisos = await getPermisosDeRol ( editorRolId );
// Revoke permission
await revokePermisoFromRole ( roleId , permisoId );
// Revoke multiple
await revokeManyPermisosFromRole ( roleId , [ 1 , 2 , 3 ]);
8. User Activities Service
Module: src/services/userActivitiesService.ts
Functions: 20 (all new)
Purpose: Track and query user actions
Logging Activities
Querying Activities
import {
logPostCreated ,
logPostPublished ,
logCommentAdded ,
logProfileUpdated ,
logUserFollowed ,
logLikeGiven
} from '@/services/userActivitiesService' ;
// Log post creation
await logPostCreated ( userId , postId , 'My New Post' );
// Log publish
await logPostPublished ( userId , postId , 'My New Post' );
// Log comment
await logCommentAdded ( userId , postId , commentId , 'Great post!' );
// Log profile update
await logProfileUpdated ( userId , { bio: true , avatar: true });
// Log follow
await logUserFollowed ( userId , targetUserId , 'johndoe' );
// Log like
await logLikeGiven ( userId , 'post' , postId );
Activity Types:
post_created - Post created
post_published - Post published
comment_added - Comment added
profile_updated - Profile updated
follow - User followed
like_given - Like given
Service Pattern Example
Every service follows this consistent pattern:
import { useRealApi , API_CONFIG } from '../config/api' ;
import { apiClient } from '../lib/apiClient' ;
import { mockData } from '../data/mockData' ;
export async function getResource () : Promise < Resource []> {
// Mock mode
if ( ! useRealApi ()) {
return mockData ;
}
// Real API mode
try {
const response = await apiClient . get ( API_CONFIG . ENDPOINTS . RESOURCE );
return response . data ;
} catch ( error ) {
console . error ( 'Error fetching resource:' , error );
return []; // Fallback
}
}
Common Use Cases
// Combine multiple services for dashboard
import { getDashboardOverview } from '@/services/postsService' ;
import { getCommentsStats } from '@/services/commentsService' ;
import { getCategoriesStats } from '@/services/categoriesService' ;
import { getEstadosStats } from '@/services/estadosService' ;
async function loadDashboard () {
const [ posts , comments , categories , states ] = await Promise . all ([
getDashboardOverview (),
getCommentsStats (),
getCategoriesStats (),
getEstadosStats ()
]);
return { posts , comments , categories , states };
}
// Load post with all related data
import { incrementarVista , getPostKeywords } from '@/services/postsService' ;
import { getCommentsByPost } from '@/services/commentsService' ;
async function loadPost ( postId : string , userId ?: number ) {
// Track view
await incrementarVista ( postId , userId );
// Load data in parallel
const [ keywords , comments ] = await Promise . all ([
getPostKeywords ( postId ),
getCommentsByPost ( postId )
]);
return { keywords , comments };
}
// Display user activity feed
import { getActivitiesByUser } from '@/services/userActivitiesService' ;
async function loadUserTimeline ( userId : number , page = 1 ) {
const activities = await getActivitiesByUser ( userId , {
limit: 20 ,
page
});
return activities ;
}
Error Handling
All services include error handling:
try {
const posts = await getAllPosts ();
} catch ( error ) {
// Services return empty arrays/null on error
// Check error in console
console . error ( 'Failed to load posts:' , error );
}
Services fail gracefully and return fallback values (empty arrays, null) rather than throwing errors in production.
Summary
105+ Functions Comprehensive coverage of all backend features
8 Service Modules Auth, Posts, Users, Comments, Categories, Estados, RBAC, Activities
Type Safe Full TypeScript interfaces for all functions
Mock & Real API Seamless switching via configuration
Next Steps
Architecture Learn about the overall project structure
Components Explore React and Astro components
State Management Understand Zustand stores
API Configuration View the complete API endpoints