-
Notifications
You must be signed in to change notification settings - Fork 0
DEVELOPER
This guide provides comprehensive information for developers working on NEXUS Support System.
- Project Architecture
- Development Environment Setup
- Quick Setup with Automated Installers
- Code Structure
- Database Schema
- API Development
- Testing
- Coding Standards
- Git Workflow
- Contributing
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Frontend │◄────►│ Backend │◄────►│ MongoDB │
│ (Static) │ │ (Express) │ │ Database │
└─────────────┘ └─────────────┘ └─────────────┘
│
▼
┌─────────────┐
│ GitHub │
│ API │
└─────────────┘
- Backend Framework: Express.js
- Database: MongoDB with Mongoose ODM
- Authentication: JWT (JSON Web Tokens)
- Security: Helmet, CORS, Rate Limiting, Bcrypt
- GitHub Integration: Axios
- Frontend: Vanilla HTML/CSS/JavaScript
-
Server Layer (
server.js)- Express application setup
- Middleware configuration
- Route registration
- Error handling
-
Controllers Layer (
controllers/)- Business logic
- Request/response handling
- Data validation
-
Models Layer (
models/)- Database schemas
- Data validation
- Pre/post hooks
-
Routes Layer (
routes/)- API endpoint definitions
- Route middleware
- Request routing
-
Middleware Layer (
middleware/)- Authentication
- Request validation
- Error handling
The system includes automated installation scripts for rapid development environment setup:
Linux/macOS:
chmod +x install.sh
./install.shWindows:
.\install.ps1Cross-Platform:
node install.jsDocker:
docker-compose up -dFor detailed automated installer documentation, see AUTOMATED_INSTALL.md.
- Node.js 14+
- MongoDB 4.4+
- Git
- Code editor (VS Code recommended)
- ESLint
- Prettier
- MongoDB for VS Code
- REST Client
- GitLens
-
Clone the repository
git clone <repository-url> cd nexus
-
Install dependencies
npm install
-
Set up environment variables
cp .env.example .env # Edit .env with your configuration -
Start MongoDB
mongod --dbpath /path/to/data
-
Start development server
npm run dev
-
Access the application
http://localhost:3000
nexus/
├── config/
│ └── database.js # MongoDB connection configuration
├── controllers/
│ ├── ticketController.js # Ticket CRUD operations
│ ├── githubController.js # GitHub webhook & sync logic
│ └── userController.js # User authentication logic
├── middleware/
│ ├── auth.js # JWT authentication middleware
│ └── githubWebhook.js # GitHub webhook verification
├── models/
│ ├── Ticket.js # Ticket MongoDB schema
│ └── User.js # User MongoDB schema
├── public/
│ └── index.html # Frontend interface
├── routes/
│ ├── ticketRoutes.js # Ticket API routes
│ ├── githubRoutes.js # GitHub API routes
│ └── userRoutes.js # User API routes
├── docs/ # Documentation
├── .env # Environment variables (not in git)
├── .env.example # Environment variables template
├── .gitignore # Git ignore rules
├── package.json # Project dependencies
├── README.md # Project overview
└── server.js # Main application entry point
Main application entry point. Configures Express, middleware, routes, and starts the server.
MongoDB connection logic using Mongoose. Handles connection errors and logging.
Contains business logic for each resource:
- ticketController.js: Handle ticket CRUD, comments, GitHub linking
- githubController.js: Process GitHub webhooks, sync tickets to GitHub
- userController.js: User registration, login, profile management
Custom middleware functions:
- auth.js: Verify JWT tokens and attach user to request
- githubWebhook.js: Verify GitHub webhook signatures
Mongoose schemas defining data structure:
- Ticket.js: Ticket schema with GitHub integration fields
- User.js: User schema with authentication fields
API endpoint definitions:
- ticketRoutes.js: /api/tickets endpoints
- githubRoutes.js: /api/github endpoints
- userRoutes.js: /api/users endpoints
Static files served by Express:
- index.html: Single-page application interface
{
ticketId: String (unique, required),
title: String (required),
description: String (required),
status: Enum ['open', 'in_progress', 'resolved', 'closed'],
priority: Enum ['low', 'medium', 'high', 'critical'],
category: String,
createdBy: String (required),
createdByEmail: String (required),
assignedTo: String,
githubIssueNumber: Number,
githubIssueUrl: String,
comments: [{
author: String,
authorEmail: String,
content: String,
createdAt: Date
}],
tags: [String],
createdAt: Date,
updatedAt: Date,
resolvedAt: Date
}{
username: String (unique, required),
email: String (unique, required),
password: String (hashed, required),
role: Enum ['admin', 'support_agent', 'user'],
githubUsername: String,
createdAt: Date
}-
Define the controller function in
controllers/:// controllers/ticketController.js const newEndpoint = async (req, res) => { try { // Business logic here res.status(200).json({ success: true, data: result }); } catch (error) { res.status(400).json({ success: false, error: error.message }); } };
-
Export the function:
module.exports = { // existing exports newEndpoint };
-
Add the route in
routes/:// routes/ticketRoutes.js const { newEndpoint } = require('../controllers/ticketController'); router.post('/new-endpoint', newEndpoint);
-
Register the route in
server.js(if new route file):const newRoutes = require('./routes/newRoutes'); app.use('/api/new', newRoutes);
-
Create middleware function in
middleware/:// middleware/custom.js const customMiddleware = (req, res, next) => { // Middleware logic next(); }; module.exports = customMiddleware;
-
Apply to routes:
router.get('/protected', customMiddleware, controllerFunction);
All controllers should follow this error handling pattern:
const controllerFunction = async (req, res) => {
try {
// Business logic
res.status(200).json({ success: true, data: result });
} catch (error) {
console.error('Error:', error);
res.status(400).json({ success: false, error: error.message });
}
};The system has been enhanced with the following improvements:
Security & Validation:
- Comprehensive input validation on all API endpoints
- Environment variable validation checks
- Improved JWT authentication with specific error types
- Enhanced webhook signature verification with logging
- Null safety checks in GitHub webhook handlers
Installation & Deployment:
- Automated installation scripts for Linux/macOS (install.sh)
- Automated installation script for Windows (install.ps1)
- Cross-platform Node.js installer (install.js)
- Docker Compose setup for containerized deployment
- Dockerfile for application containerization
Documentation:
- Quick Start Guide for rapid setup
- Platform-specific setup guides (Windows, Linux, macOS)
- Comprehensive Automated Installation Guide
- Updated API documentation
- Enhanced troubleshooting guides
UI/UX:
- Modern sci-fi theme with neon cyan accents
- Consistent color scheme throughout
- Removed emojis and icons as requested
# Create ticket
curl -X POST http://localhost:3000/api/tickets \
-H "Content-Type: application/json" \
-d '{"title":"Test","description":"Test","createdBy":"User","createdByEmail":"user@test.com"}'
# Get tickets
curl http://localhost:3000/api/tickets
# Get specific ticket
curl http://localhost:3000/api/tickets/TCK-ABC123- Import the API collection (if available)
- Set base URL:
http://localhost:3000/api - For authenticated endpoints, add JWT token to headers:
- Header:
Authorization - Value:
Bearer <your-jwt-token>
- Header:
-
Install ngrok:
# macOS brew install ngrok # Linux snap install ngrok
-
Start ngrok:
ngrok http 3000
-
Use the ngrok URL for GitHub webhook payload URL
-
Test webhook by creating an issue in your GitHub repository
- Use 2 spaces for indentation
- Use single quotes for strings
- Use camelCase for variables and functions
- Use PascalCase for classes and constructors
- Use UPPER_CASE for constants
- Add JSDoc comments for functions
/**
* Create a new ticket
* @param {Object} req - Express request object
* @param {Object} res - Express response object
*/
const createTicket = async (req, res) => {
try {
const { title, description } = req.body;
const ticket = await Ticket.create({ title, description });
res.status(201).json({ success: true, data: ticket });
} catch (error) {
res.status(400).json({ success: false, error: error.message });
}
};-
Files: kebab-case (e.g.,
ticketController.js) -
Variables: camelCase (e.g.,
ticketId) -
Constants: UPPER_SNAKE_CASE (e.g.,
MAX_TICKETS) -
Classes: PascalCase (e.g.,
TicketService) -
Database Collections: PascalCase (e.g.,
Tickets,Users)
- Keep controllers thin - business logic only
- Keep routes simple - just routing
- Use middleware for cross-cutting concerns
- Separate validation logic into validators
- Use async/await for asynchronous operations
-
main- Production branch -
develop- Integration branch -
feature/<name>- Feature branches -
bugfix/<name>- Bug fix branches -
hotfix/<name>- Emergency fixes
<type>(<scope>): <subject>
<body>
<footer>
Types:
-
feat: New feature -
fix: Bug fix -
docs: Documentation changes -
style: Code style changes -
refactor: Code refactoring -
test: Test changes -
chore: Maintenance tasks
Examples:
feat(tickets): add ticket filtering by priority
Add ability to filter tickets by priority level in the
GET /api/tickets endpoint. Accepts priority query parameter.
Closes #123
fix(auth): resolve JWT token expiration issue
Fixed bug where tokens were not expiring correctly.
Updated token generation logic to use proper expiration time.
-
Create feature branch from
developgit checkout develop git pull origin develop git checkout -b feature/new-feature
-
Make changes and commit
git add . git commit -m "feat(scope): description"
-
Push to remote
git push origin feature/new-feature
-
Create pull request to
develop -
After review and merge, delete feature branch
git branch -d feature/new-feature
- Read this developer guide
- Read the API documentation
- Set up local development environment
- Run existing tests (if any)
- Create a new branch for your changes
- Follow coding standards
- Write clear commit messages
- Test your changes thoroughly
- Update documentation if needed
- Submit a pull request
- Code follows project style guidelines
- Commit messages are clear and descriptive
- Changes are tested locally
- Documentation is updated
- No console.log statements left in production code
- Environment variables are documented
- No hardcoded credentials or secrets
- Submit pull request
- Wait for review from maintainers
- Address review comments
- Update PR as needed
- Get approval before merge
Add indexes to frequently queried fields:
// In models/Ticket.js
ticketSchema.index({ ticketId: 1 });
ticketSchema.index({ status: 1 });
ticketSchema.index({ priority: 1 });
ticketSchema.index({ createdAt: -1 });For large datasets, implement pagination:
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 10;
const skip = (page - 1) * limit;
const tickets = await Ticket.find().skip(skip).limit(limit);Consider caching frequently accessed data:
- User sessions
- Ticket lists
- GitHub repository information
-
Never commit sensitive data
- Use
.envfor secrets - Add
.envto.gitignore - Rotate secrets regularly
- Use
-
Validate all inputs
- Use Mongoose validators
- Add custom validation in controllers
- Sanitize user input
-
Use HTTPS in production
- Configure SSL certificates
- Redirect HTTP to HTTPS
-
Implement rate limiting
- Prevent API abuse
- Configure appropriate limits
-
Keep dependencies updated
- Run
npm auditregularly - Update packages to latest secure versions
- Run
Add debug statements to controllers:
console.log('Processing ticket:', ticketId);
console.log('GitHub webhook received:', eventType);Enable MongoDB query logging:
mongoose.set('debug', true);Ticket not saving:
- Check Mongoose validation errors
- Verify database connection
- Check for duplicate ticketId
Webhook not processing:
- Verify webhook signature
- Check GitHub webhook delivery logs
- Review server logs
Authentication failing:
- Verify JWT_SECRET matches
- Check token expiration
- Verify token format
- Check existing documentation
- Review GitHub Issues
- Contact maintainers
- Join developer community (if available)