Middleware Functions
The middleware functions provide the core business logic interface between your UI components and backend services. These functions handle authentication, data management, real-time communication, and application workflows for job matching platforms.
📋 Table of Contents
- 🔐 Authentication & Session Management
- 👤 User Management
- 🏢 Organization Management
- 💼 Job Posting & Catalog Management
- 📝 Application & Order Management
- 💬 Real-time Communication
- 🔍 Search & Filtering
- 🧭 Navigation & UI Control
- 📄 Pagination
🔐 Authentication & Session Management
Function | Description | Usage Example |
---|---|---|
onActionLogin | Authenticate user with email/password credentials | Login forms, authentication flows |
onActionLogout | Process user logout and clear session data | Logout buttons, session termination |
onActionSignUp | Register new job seeker or employer account | Registration forms, user onboarding |
onSuccessLogin | Handle post-login redirect and initialization | Login success handling |
onSuccessLogout | Handle post-logout cleanup and redirect | Logout success handling |
onActionResendVerificationEmail | Resend email verification to user | Email verification workflows |
onRequestPasswordChange | Initiate password reset process | Forgot password forms |
onResetPasswordSubmit | Complete password reset with token validation | Password reset completion |
onSessionStateUpdate | Handle session state changes and updates | Session management, token refresh |
isLoggedIn | Check if user is currently authenticated | Conditional rendering, route guards |
isNotLoggedIn | Check if user is not authenticated | Authentication prompts, access control |
👤 User Management
Function | Description | Usage Example |
---|---|---|
onUpdateUser | Update job seeker or employer profile information | Profile editing forms |
onLockUser | Lock/suspend user account (admin functionality) | Admin user management panel |
onUnlockUser | Unlock/restore user account (admin functionality) | Admin user management panel |
onDeactivateAccount | Deactivate current user account | Account deletion flows |
onCreateInvitation | Create team member invitation for organization | Team member invitations |
onDeleteInvitation | Remove/cancel pending user invitation | Invitation management |
onAcceptInvitation | Accept organization team invitation | Invitation acceptance workflow |
onChangePassword | Update user's current password | Password change forms |
onChangeEmail | Update user's email address | Email change forms |
🏢 Organization Management
Function | Description | Usage Example |
---|---|---|
onCreateOrganization | Create new employer organization | Organization setup forms |
onUpdateOrganization | Update organization profile and details | Organization profile editing |
onFilterOrganizations | Filter and search organization listings | Organization directory |
onGetMoreOrganizationProducts | Load more job postings for organization | Organization job listings pagination |
💼 Job Posting & Catalog Management
Function | Description | Usage Example |
---|---|---|
onCreateProduct | Create new job posting | Job posting creation forms |
onUpdateProduct | Update existing job posting | Job posting editing forms |
onFilterProducts | Filter and search job listings | Job search and filtering |
onGetMoreProducts | Load more job postings (pagination) | Job listings pagination |
onGetAttributes | Fetch job skills and attributes | Skill selection, job filtering |
onGetCategories | Load job categories | Category-based navigation |
onCreateProductAttachment | Upload job-related file attachment | Job description attachments |
onDeleteProductAttachment | Remove job posting attachment | Attachment management |
📝 Application & Order Management
Function | Description | Usage Example |
---|---|---|
onCreateOrder | Create new job application | Job application submission |
onActionUpdateOrder | Update application status and details | Application management, status updates |
onFilterOrders | Filter and search job applications | Application search and filtering |
onGetMoreOrders | Load more applications (pagination) | Application history pagination |
💬 Real-time Communication
Function | Description | Usage Example |
---|---|---|
onCreateTopic | Create new chat conversation between employer and candidate | Application-based chat initialization |
onSubscribeToTopic | Subscribe to chat topic for real-time updates | Real-time messaging setup |
onSendMessage | Send message in employer-candidate conversation | Message sending interface |
onGetMoreMessages | Load previous message history | Chat history pagination |
onGetMoreTopics | Load more conversation topics | Chat topics list pagination |
onUpdateMessageReadStatus | Mark messages as read | Read status tracking |
appendMessagesToState | Add new messages to application state | Real-time message updates |
onSocketSubscribeToUserId | Subscribe to user-specific real-time updates | User notification system |
onSocketUnSubscribeToUserId | Unsubscribe from user real-time updates | Cleanup on logout/unmount |
onSocketSubscribeToOrganizationId | Subscribe to organization real-time updates | Employer notification system |
onSocketUnSubscribeToOrganizationId | Unsubscribe from organization updates | Cleanup on navigation |
🔍 Search & Filtering
Function | Description | Usage Example |
---|---|---|
onChangeSearchFilter | Update job search criteria | Search input handling |
onSelectFilter | Add filter to job search selection | Filter selection UI |
onRemoveSelectedFilter | Remove specific filter from selection | Individual filter removal |
🧭 Navigation & UI Control
Function | Description | Usage Example |
---|---|---|
onActionToggleMenu | Toggle mobile/sidebar menu | Menu button handling |
redirect | Programmatic navigation | Route changes, redirects |
📄 Pagination
All pagination functions handle loading additional items for their respective data types:
Function | Description | Usage Example |
---|---|---|
onGetMoreProducts | Load additional job postings | Job listings infinite scroll |
onGetMoreOrders | Load additional applications | Application history pagination |
onGetMoreOrganizationProducts | Load more organization job postings | Organization job catalog pagination |
onGetMoreMessages | Load additional chat messages | Chat history loading |
onGetMoreTopics | Load additional conversation topics | Chat topics list pagination |
🚀 Usage Patterns
Basic Authentication Usage
function LoginForm({ middleware }) {
const handleLogin = async (email, password) => {
const result = await middleware.onActionLogin({ email, password });
if (result.ok) {
// Login successful - redirect to dashboard
console.log('User logged in:', result.value);
} else {
// Handle authentication error
console.error('Login failed:', result.error);
}
};
return (
<form onSubmit={handleLogin}>
{/* Email and password fields */}
</form>
);
}
Job Posting Creation Pattern
const handleCreateJobPosting = async (organizationId, jobData) => {
try {
const result = await middleware.onCreateProduct(organizationId, jobData);
if (result.ok) {
// Success - redirect to job posting
middleware.redirect('/jobs/' + result.value.id);
} else {
// Handle business logic errors
setError(result.error.message);
}
} catch (error) {
// Handle network/unexpected errors
setError('Something went wrong');
}
};
Job Application Flow
function JobApplicationButton({ middleware, state, jobId, organizationId }) {
const handleApply = () => {
if (middleware.isLoggedIn()) {
// User is authenticated - create application
const applicationData = { jobId, coverLetter: state.coverLetter };
middleware.onCreateOrder(organizationId, applicationData);
} else {
// Redirect to login
middleware.redirect('/login');
}
};
return (
<button onClick={handleApply}>
Apply for Job
</button>
);
}
Real-time Messaging Setup
useEffect(() => {
if (middleware.isLoggedIn() && currentUserId) {
// Subscribe to real-time notifications and messages
middleware.onSocketSubscribeToUserId(
currentUserId,
(error) => console.error('Socket error:', error),
(message) => {
// Handle incoming message
console.log('New message:', message);
}
);
// Cleanup on unmount
return () => {
middleware.onSocketUnSubscribeToUserId(currentUserId);
};
}
}, [currentUserId]);
💡 Best Practices
Async/Await Pattern
- Always use async/await with middleware functions that return promises
- Handle both success and error cases explicitly
- Use try/catch blocks for unexpected errors
Result Pattern
- Check the
ok
property before accessingresult.value
- Handle
result.error
appropriately for user feedback - Never assume success without checking the result status
State Management
- Use middleware functions instead of direct API calls
- Allow middleware to handle state updates automatically
- Use
updateState
sparingly for custom state modifications
Error Handling
- Provide user-friendly error messages for UI feedback
- Log detailed errors for debugging purposes
- Implement retry mechanisms for network-related errors
Real-time Communication
- Always provide error and message handlers for socket subscriptions
- Clean up subscriptions on component unmount to prevent memory leaks
- Handle connection state changes gracefully