392 lines
8.2 KiB
Markdown
392 lines
8.2 KiB
Markdown
# 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
|
|
|
|
```bash
|
|
# 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
|
|
```
|
|
|
|
Open http://localhost:3000
|
|
|
|
## 📝 Coding Standards
|
|
|
|
### JavaScript/Frontend
|
|
|
|
```javascript
|
|
// 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
|
|
|
|
```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
|
|
|
|
```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
|
|
|
|
1. **Create module structure**
|
|
```
|
|
public/modules/new-feature/
|
|
├── new-feature.html # UI template
|
|
├── styles/
|
|
│ └── new-feature.css # Styles (optional)
|
|
└── js/
|
|
└── new-feature.js # Logic (optional)
|
|
```
|
|
|
|
2. **Update router.js**
|
|
```javascript
|
|
routes: {
|
|
'new-feature': {
|
|
module: 'newFeatureModule',
|
|
requireAuth: true,
|
|
handler: this.handleNewFeature.bind(this)
|
|
}
|
|
}
|
|
```
|
|
|
|
3. **Add navigation item**
|
|
```html
|
|
<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
|
|
|
|
1. **Create route file** in `src/routes/`
|
|
|
|
```javascript
|
|
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;
|
|
};
|
|
```
|
|
|
|
2. **Register in server.js**
|
|
```javascript
|
|
app.use('/api/endpoint', require('./src/routes/endpoint')(pool));
|
|
```
|
|
|
|
3. **Add API method** in `public/js/api.js`
|
|
```javascript
|
|
async getEndpoint() {
|
|
return this.request('/endpoint', { method: 'GET' });
|
|
}
|
|
```
|
|
|
|
## 🐛 Debugging
|
|
|
|
### Frontend Debugging
|
|
|
|
```javascript
|
|
// 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
|
|
|
|
```javascript
|
|
// 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
|
|
|
|
```bash
|
|
# 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
|
|
|
|
```bash
|
|
# 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
|
|
|
|
1. Import requests from `postman_collection.json` (если имеется)
|
|
2. Set base URL: `http://localhost:3000`
|
|
3. 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
|
|
|
|
1. **DRY (Don't Repeat Yourself)**
|
|
- Extract common functions to utilities
|
|
- Create reusable components
|
|
|
|
2. **KISS (Keep It Simple, Stupid)**
|
|
- Write clear, readable code
|
|
- Avoid over-engineering
|
|
|
|
3. **SOLID Principles**
|
|
- Single responsibility
|
|
- Open/closed (open for extension, closed for modification)
|
|
|
|
### Frontend
|
|
|
|
1. **Performance**
|
|
- Lazy load modules when possible
|
|
- Minimize DOM manipulation
|
|
- Use event delegation for dynamic elements
|
|
|
|
2. **Accessibility**
|
|
- Use semantic HTML
|
|
- Add ARIA labels where needed
|
|
- Test with keyboard navigation
|
|
|
|
3. **Responsive Design**
|
|
- Mobile-first approach
|
|
- Test on multiple devices
|
|
- Use relative units (rem, %, vw)
|
|
|
|
### Backend
|
|
|
|
1. **Database**
|
|
- Always use parameterized queries
|
|
- Create appropriate indexes
|
|
- Regular backups
|
|
|
|
2. **Security**
|
|
- Validate all inputs
|
|
- Hash passwords properly
|
|
- Use HTTPS in production
|
|
- Implement rate limiting
|
|
|
|
3. **Error Handling**
|
|
- Provide meaningful error messages
|
|
- Log errors server-side
|
|
- Don't expose sensitive information
|
|
|
|
## 🔑 Environment Variables
|
|
|
|
Never commit `.env`! Use `.env.example` template.
|
|
|
|
```bash
|
|
# 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:**
|
|
```bash
|
|
npm outdated # Check for updates
|
|
npm update # Update to latest
|
|
npm audit # Check for vulnerabilities
|
|
npm audit fix # Auto-fix vulnerabilities
|
|
```
|
|
|
|
## 🚀 Performance Tips
|
|
|
|
1. **Frontend**
|
|
- Use production builds
|
|
- Minify CSS/JS
|
|
- Lazy load images
|
|
- Use CSS containment for heavy animations
|
|
|
|
2. **Backend**
|
|
- Use connection pooling
|
|
- Add database indexes
|
|
- Cache frequently accessed data
|
|
- Optimize queries with EXPLAIN
|
|
|
|
3. **Deployment**
|
|
- Use CDN for static files
|
|
- Enable gzip compression
|
|
- Set appropriate cache headers
|
|
- Use monitoring tools
|
|
|
|
## 📖 Further Reading
|
|
|
|
- [Express.js Documentation](https://expressjs.com/)
|
|
- [PostgreSQL Documentation](https://www.postgresql.org/docs/)
|
|
- [MDN Web Docs](https://developer.mozilla.org/)
|
|
- [Node.js Best Practices](https://github.com/goldbergyoni/nodebestpractices)
|
|
|
|
---
|
|
|
|
Last updated: January 2024
|