8.2 KiB
8.2 KiB
Development Guide
🚀 Quick Start for Developers
Prerequisites
- Node.js 14+
- PostgreSQL 12+
- VS Code (recommended) with extensions:
- ES7+ React/Redux/React-Native snippets
- Tailwind CSS IntelliSense
- PostgreSQL Explorer
Initial Setup
# 1. Clone repository
git clone <repo-url>
cd pg-admin
# 2. Install dependencies
npm install
# 3. Create .env from example
cp .env.example .env
# 4. Configure your database
# Edit .env with your PostgreSQL credentials
# 5. Start development server
npm run dev
📝 Coding Standards
JavaScript/Frontend
// Use const by default, let for loops
const config = { ... };
let accumulator = 0;
// Arrow functions for callbacks
const handleClick = (e) => { ... };
// Use template literals
const message = `Hello ${name}`;
// Async/await instead of .then()
const data = await api.fetchUsers();
// Error handling
try {
await api.call();
} catch (error) {
console.error('Error:', error);
showError(error.message);
}
CSS
/* Use Tailwind classes */
<button class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
/* Create custom utility classes in main.css */
.card {
@apply bg-white dark:bg-slate-900 border border-slate-200 rounded-xl shadow-sm;
}
/* Use CSS custom properties for theming */
:root {
--color-primary: #3b82f6;
--color-success: #10b981;
}
.dark {
--color-primary: #60a5fa;
}
SQL
-- Use parameterized queries to prevent SQL injection
pool.query('SELECT * FROM users WHERE id = $1', [userId]);
-- Use clear naming conventions
SELECT user_id, created_at FROM activity_logs ORDER BY created_at DESC;
-- Create indexes for frequently queried columns
CREATE INDEX idx_activity_logs_user_id ON activity_logs(user_id);
🏗️ Adding New Features
Adding a New Module
- Create module structure
public/modules/new-feature/
├── new-feature.html # UI template
├── styles/
│ └── new-feature.css # Styles (optional)
└── js/
└── new-feature.js # Logic (optional)
- Update router.js
routes: {
'new-feature': {
module: 'newFeatureModule',
requireAuth: true,
handler: this.handleNewFeature.bind(this)
}
}
- Add navigation item
<a href="#new-feature" class="nav-item">
<i data-lucide="icon" class="w-5 h-5"></i>
<span>New Feature</span>
</a>
Adding a New API Endpoint
- Create route file in
src/routes/
module.exports = (pool) => {
const router = express.Router();
const requireAuth = (req, res, next) => {
if (req.session && req.session.userId) {
next();
} else {
res.status(401).json({ success: false });
}
};
// GET endpoint
router.get('/', requireAuth, async (req, res) => {
try {
const result = await pool.query('SELECT * FROM table');
res.json({ success: true, data: result.rows });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});
return router;
};
- Register in server.js
app.use('/api/endpoint', require('./src/routes/endpoint')(pool));
- Add API method in
public/js/api.js
async getEndpoint() {
return this.request('/endpoint', { method: 'GET' });
}
🐛 Debugging
Frontend Debugging
// Use Chrome DevTools
// F12 → Sources tab for breakpoints
// Use console methods
console.log('Value:', value); // Info
console.error('Error:', error); // Error
console.warn('Warning:', warning); // Warning
console.table(array); // Table view
// Use debugger statement
debugger; // Pauses execution when DevTools open
Backend Debugging
// Use node --inspect for debugging
node --inspect server.js
// Or use VS Code debugger with .vscode/launch.json
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"program": "${workspaceFolder}/server.js",
"restart": true,
"console": "integratedTerminal"
}
]
}
Database Debugging
# Connect to PostgreSQL
psql -U postgres -d postgres -h localhost
# Useful queries
\dt # List tables
\d users # Describe table
SELECT COUNT(*) FROM table_name;
EXPLAIN ANALYZE SELECT ...;
📊 Testing API
Using curl
# Register
curl -X POST http://localhost:3000/api/auth/register \
-H "Content-Type: application/json" \
-d '{"name":"Test","email":"test@example.com","password":"pass123"}'
# Login
curl -X POST http://localhost:3000/api/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"test@example.com","password":"pass123"}'
# Get data
curl http://localhost:3000/api/db/tables
# Execute query
curl -X POST http://localhost:3000/api/db/query \
-H "Content-Type: application/json" \
-d '{"sql":"SELECT COUNT(*) FROM users"}'
Using Postman
- Import requests from
postman_collection.json(если имеется) - Set base URL:
http://localhost:3000 - Save responses in collection
🗂️ File Organization
Keep related files together:
- HTML structure
- CSS styling
- JavaScript logic
Example - Auth Module:
modules/auth/
├── login.html # Structure + CSS
└── (js in main app.js or auth.js)
Avoid:
- Mixing concerns (HTML with business logic)
- Creating orphaned files
- Dead code without comments
📚 Best Practices
General
-
DRY (Don't Repeat Yourself)
- Extract common functions to utilities
- Create reusable components
-
KISS (Keep It Simple, Stupid)
- Write clear, readable code
- Avoid over-engineering
-
SOLID Principles
- Single responsibility
- Open/closed (open for extension, closed for modification)
Frontend
-
Performance
- Lazy load modules when possible
- Minimize DOM manipulation
- Use event delegation for dynamic elements
-
Accessibility
- Use semantic HTML
- Add ARIA labels where needed
- Test with keyboard navigation
-
Responsive Design
- Mobile-first approach
- Test on multiple devices
- Use relative units (rem, %, vw)
Backend
-
Database
- Always use parameterized queries
- Create appropriate indexes
- Regular backups
-
Security
- Validate all inputs
- Hash passwords properly
- Use HTTPS in production
- Implement rate limiting
-
Error Handling
- Provide meaningful error messages
- Log errors server-side
- Don't expose sensitive information
🔑 Environment Variables
Never commit .env! Use .env.example template.
# Required for all environments
PORT=3000
DB_HOST=localhost
DB_USER=postgres
# Development only
NODE_ENV=development
DEBUG=*
# Production only (set via deployment system)
SESSION_SECRET=production-secret
SSL_CERT=/path/to/cert.pem
📦 Dependencies
Why we use them
- express - Web framework
- pg - PostgreSQL driver
- bcryptjs - Password hashing
- express-session - Session management
- cors - Cross-origin requests
- dotenv - Environment variables
Keeping dependencies updated:
npm outdated # Check for updates
npm update # Update to latest
npm audit # Check for vulnerabilities
npm audit fix # Auto-fix vulnerabilities
🚀 Performance Tips
-
Frontend
- Use production builds
- Minify CSS/JS
- Lazy load images
- Use CSS containment for heavy animations
-
Backend
- Use connection pooling
- Add database indexes
- Cache frequently accessed data
- Optimize queries with EXPLAIN
-
Deployment
- Use CDN for static files
- Enable gzip compression
- Set appropriate cache headers
- Use monitoring tools
📖 Further Reading
Last updated: January 2024