PM2 cluster deploy + Redis caching + Nginx gzip + UI polish
- PM2 v6: 2x API cluster + 1x web, zero-downtime reload - Redis cache: 30s TTL on GET /tasks, X-Cache header - Nginx gzip compression - Mobile touch targets 44px - Czech diacritics throughout UI - TaskModal slide-up animation - StatusBadge color dots - GroupSelector emoji icons Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,40 +1,67 @@
|
||||
// Task Team — API Server — 2026-03-29
|
||||
require('dotenv').config();
|
||||
const Fastify = require('fastify');
|
||||
const cors = require('@fastify/cors');
|
||||
const jwt = require('@fastify/jwt');
|
||||
const { Pool } = require('pg');
|
||||
require("dotenv").config();
|
||||
const Fastify = require("fastify");
|
||||
const cors = require("@fastify/cors");
|
||||
const jwt = require("@fastify/jwt");
|
||||
const { Pool } = require("pg");
|
||||
const Redis = require("ioredis");
|
||||
|
||||
const app = Fastify({ logger: true });
|
||||
|
||||
// Database pool
|
||||
const pool = new Pool({
|
||||
connectionString: process.env.DATABASE_URL || 'postgresql://taskteam:TaskTeam2026!@10.10.10.10:5432/taskteam'
|
||||
connectionString: process.env.DATABASE_URL || "postgresql://taskteam:TaskTeam2026!@10.10.10.10:5432/taskteam"
|
||||
});
|
||||
|
||||
// Redis client
|
||||
const redis = new Redis(process.env.REDIS_URL || "redis://:Redis2026!@10.10.10.10:6379");
|
||||
|
||||
redis.on("connect", () => {
|
||||
app.log.info("Redis connected");
|
||||
});
|
||||
redis.on("error", (err) => {
|
||||
app.log.error("Redis error: " + err.message);
|
||||
});
|
||||
|
||||
// Plugins
|
||||
app.register(cors, { origin: true });
|
||||
app.register(jwt, { secret: process.env.JWT_SECRET || 'taskteam-jwt-secret-2026' });
|
||||
app.register(jwt, { secret: process.env.JWT_SECRET || "taskteam-jwt-secret-2026" });
|
||||
|
||||
// Decorate with db
|
||||
app.decorate('db', pool);
|
||||
// Decorate with db and redis
|
||||
app.decorate("db", pool);
|
||||
app.decorate("redis", redis);
|
||||
|
||||
// Health check
|
||||
app.get('/health', async () => ({ status: 'ok', timestamp: new Date().toISOString() }));
|
||||
app.get("/health", async () => ({
|
||||
status: "ok",
|
||||
timestamp: new Date().toISOString(),
|
||||
pid: process.pid,
|
||||
redis: redis.status
|
||||
}));
|
||||
|
||||
// Register routes
|
||||
app.register(require('./routes/tasks'), { prefix: '/api/v1' });
|
||||
app.register(require('./routes/groups'), { prefix: '/api/v1' });
|
||||
app.register(require('./routes/auth'), { prefix: '/api/v1' });
|
||||
app.register(require('./routes/connectors'), { prefix: '/api/v1' });
|
||||
app.register(require('./routes/connectors/odoo'), { prefix: '/api/v1' });
|
||||
app.register(require('./routes/chat'), { prefix: '/api/v1' });
|
||||
app.register(require("./routes/tasks"), { prefix: "/api/v1" });
|
||||
app.register(require("./routes/groups"), { prefix: "/api/v1" });
|
||||
app.register(require("./routes/auth"), { prefix: "/api/v1" });
|
||||
app.register(require("./routes/connectors"), { prefix: "/api/v1" });
|
||||
app.register(require("./routes/connectors/odoo"), { prefix: "/api/v1" });
|
||||
app.register(require("./routes/chat"), { prefix: "/api/v1" });
|
||||
|
||||
// Graceful shutdown
|
||||
const shutdown = async (signal) => {
|
||||
app.log.info(`Received ${signal}, shutting down gracefully...`);
|
||||
await redis.quit();
|
||||
await pool.end();
|
||||
process.exit(0);
|
||||
};
|
||||
process.on("SIGINT", () => shutdown("SIGINT"));
|
||||
process.on("SIGTERM", () => shutdown("SIGTERM"));
|
||||
|
||||
// Start
|
||||
const start = async () => {
|
||||
try {
|
||||
await app.listen({ port: process.env.PORT || 3000, host: '0.0.0.0' });
|
||||
console.log('Task Team API listening on port ' + (process.env.PORT || 3000));
|
||||
await app.listen({ port: process.env.PORT || 3000, host: "0.0.0.0" });
|
||||
console.log("Task Team API listening on port " + (process.env.PORT || 3000) + " (pid: " + process.pid + ")");
|
||||
} catch (err) {
|
||||
app.log.error(err);
|
||||
process.exit(1);
|
||||
|
||||
@@ -1,84 +1,154 @@
|
||||
// Task Team — Tasks CRUD — 2026-03-29
|
||||
// Task Team — Tasks CRUD with Redis Caching — 2026-03-29
|
||||
const CACHE_TTL = 30; // seconds
|
||||
const CACHE_PREFIX = "taskteam:tasks:";
|
||||
|
||||
async function taskRoutes(app) {
|
||||
// List tasks
|
||||
app.get('/tasks', async (req, reply) => {
|
||||
|
||||
// Helper: build cache key from query params
|
||||
function cacheKey(query) {
|
||||
const { status, group_id, limit = 50, offset = 0 } = query;
|
||||
return CACHE_PREFIX + "list:" + [status || "", group_id || "", limit, offset].join(":");
|
||||
}
|
||||
|
||||
// Helper: invalidate all task list caches
|
||||
async function invalidateTaskCaches() {
|
||||
try {
|
||||
const keys = await app.redis.keys(CACHE_PREFIX + "*");
|
||||
if (keys.length > 0) {
|
||||
await app.redis.del(...keys);
|
||||
app.log.info("Invalidated " + keys.length + " task cache keys");
|
||||
}
|
||||
} catch (err) {
|
||||
app.log.warn("Cache invalidation error: " + err.message);
|
||||
}
|
||||
}
|
||||
|
||||
// List tasks (cached)
|
||||
app.get("/tasks", async (req, reply) => {
|
||||
const key = cacheKey(req.query);
|
||||
|
||||
// Try cache first
|
||||
try {
|
||||
const cached = await app.redis.get(key);
|
||||
if (cached) {
|
||||
reply.header("X-Cache", "HIT");
|
||||
return JSON.parse(cached);
|
||||
}
|
||||
} catch (err) {
|
||||
app.log.warn("Cache read error: " + err.message);
|
||||
}
|
||||
|
||||
const { status, group_id, limit = 50, offset = 0 } = req.query;
|
||||
let query = 'SELECT t.*, tg.name as group_name, tg.color as group_color, tg.icon as group_icon FROM tasks t LEFT JOIN task_groups tg ON t.group_id = tg.id WHERE 1=1';
|
||||
let query = "SELECT t.*, tg.name as group_name, tg.color as group_color, tg.icon as group_icon FROM tasks t LEFT JOIN task_groups tg ON t.group_id = tg.id WHERE 1=1";
|
||||
const params = [];
|
||||
if (status) { params.push(status); query += ` AND t.status = $${params.length}`; }
|
||||
if (group_id) { params.push(group_id); query += ` AND t.group_id = $${params.length}`; }
|
||||
query += ' ORDER BY t.scheduled_at ASC NULLS LAST, t.priority DESC, t.created_at DESC';
|
||||
query += " ORDER BY t.scheduled_at ASC NULLS LAST, t.priority DESC, t.created_at DESC";
|
||||
params.push(limit); query += ` LIMIT $${params.length}`;
|
||||
params.push(offset); query += ` OFFSET $${params.length}`;
|
||||
const { rows } = await app.db.query(query, params);
|
||||
return { data: rows, total: rows.length };
|
||||
const result = { data: rows, total: rows.length };
|
||||
|
||||
// Store in cache
|
||||
try {
|
||||
await app.redis.set(key, JSON.stringify(result), "EX", CACHE_TTL);
|
||||
} catch (err) {
|
||||
app.log.warn("Cache write error: " + err.message);
|
||||
}
|
||||
|
||||
reply.header("X-Cache", "MISS");
|
||||
return result;
|
||||
});
|
||||
|
||||
// Get single task
|
||||
app.get('/tasks/:id', async (req) => {
|
||||
// Get single task (cached)
|
||||
app.get("/tasks/:id", async (req, reply) => {
|
||||
const key = CACHE_PREFIX + "detail:" + req.params.id;
|
||||
|
||||
try {
|
||||
const cached = await app.redis.get(key);
|
||||
if (cached) {
|
||||
reply.header("X-Cache", "HIT");
|
||||
return JSON.parse(cached);
|
||||
}
|
||||
} catch (err) {
|
||||
app.log.warn("Cache read error: " + err.message);
|
||||
}
|
||||
|
||||
const { rows } = await app.db.query(
|
||||
'SELECT t.*, tg.name as group_name, tg.color as group_color FROM tasks t LEFT JOIN task_groups tg ON t.group_id = tg.id WHERE t.id = $1',
|
||||
"SELECT t.*, tg.name as group_name, tg.color as group_color FROM tasks t LEFT JOIN task_groups tg ON t.group_id = tg.id WHERE t.id = $1",
|
||||
[req.params.id]
|
||||
);
|
||||
if (!rows.length) throw { statusCode: 404, message: 'Task not found' };
|
||||
return { data: rows[0] };
|
||||
if (!rows.length) throw { statusCode: 404, message: "Task not found" };
|
||||
const result = { data: rows[0] };
|
||||
|
||||
try {
|
||||
await app.redis.set(key, JSON.stringify(result), "EX", CACHE_TTL);
|
||||
} catch (err) {
|
||||
app.log.warn("Cache write error: " + err.message);
|
||||
}
|
||||
|
||||
reply.header("X-Cache", "MISS");
|
||||
return result;
|
||||
});
|
||||
|
||||
// Create task
|
||||
app.post('/tasks', async (req) => {
|
||||
// Create task (invalidates cache)
|
||||
app.post("/tasks", async (req) => {
|
||||
const { title, description, status, group_id, priority, scheduled_at, due_at, assigned_to } = req.body;
|
||||
const { rows } = await app.db.query(
|
||||
`INSERT INTO tasks (title, description, status, group_id, priority, scheduled_at, due_at, assigned_to)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING *`,
|
||||
[title, description || '', status || 'pending', group_id, priority || 'medium', scheduled_at, due_at, assigned_to || []]
|
||||
[title, description || "", status || "pending", group_id, priority || "medium", scheduled_at, due_at, assigned_to || []]
|
||||
);
|
||||
await invalidateTaskCaches();
|
||||
return { data: rows[0] };
|
||||
});
|
||||
|
||||
// Update task
|
||||
app.put('/tasks/:id', async (req) => {
|
||||
// Update task (invalidates cache)
|
||||
app.put("/tasks/:id", async (req) => {
|
||||
const fields = req.body;
|
||||
const sets = [];
|
||||
const params = [];
|
||||
let i = 1;
|
||||
for (const [key, value] of Object.entries(fields)) {
|
||||
if (['title','description','status','group_id','priority','scheduled_at','due_at','assigned_to','completed_at'].includes(key)) {
|
||||
if (["title","description","status","group_id","priority","scheduled_at","due_at","assigned_to","completed_at"].includes(key)) {
|
||||
sets.push(`${key} = $${i}`);
|
||||
params.push(value);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
if (fields.status === 'completed' && !fields.completed_at) {
|
||||
sets.push(`completed_at = NOW()`);
|
||||
if (fields.status === "completed" && !fields.completed_at) {
|
||||
sets.push("completed_at = NOW()");
|
||||
}
|
||||
sets.push(`updated_at = NOW()`);
|
||||
sets.push("updated_at = NOW()");
|
||||
params.push(req.params.id);
|
||||
const { rows } = await app.db.query(
|
||||
`UPDATE tasks SET ${sets.join(', ')} WHERE id = $${i} RETURNING *`, params
|
||||
`UPDATE tasks SET ${sets.join(", ")} WHERE id = $${i} RETURNING *`, params
|
||||
);
|
||||
if (!rows.length) throw { statusCode: 404, message: 'Task not found' };
|
||||
if (!rows.length) throw { statusCode: 404, message: "Task not found" };
|
||||
await invalidateTaskCaches();
|
||||
return { data: rows[0] };
|
||||
});
|
||||
|
||||
// Delete task
|
||||
app.delete('/tasks/:id', async (req) => {
|
||||
const { rowCount } = await app.db.query('DELETE FROM tasks WHERE id = $1', [req.params.id]);
|
||||
if (!rowCount) throw { statusCode: 404, message: 'Task not found' };
|
||||
return { status: 'deleted' };
|
||||
// Delete task (invalidates cache)
|
||||
app.delete("/tasks/:id", async (req) => {
|
||||
const { rowCount } = await app.db.query("DELETE FROM tasks WHERE id = $1", [req.params.id]);
|
||||
if (!rowCount) throw { statusCode: 404, message: "Task not found" };
|
||||
await invalidateTaskCaches();
|
||||
return { status: "deleted" };
|
||||
});
|
||||
|
||||
// Task comments
|
||||
app.get('/tasks/:id/comments', async (req) => {
|
||||
app.get("/tasks/:id/comments", async (req) => {
|
||||
const { rows } = await app.db.query(
|
||||
'SELECT * FROM task_comments WHERE task_id = $1 ORDER BY created_at ASC', [req.params.id]
|
||||
"SELECT * FROM task_comments WHERE task_id = $1 ORDER BY created_at ASC", [req.params.id]
|
||||
);
|
||||
return { data: rows };
|
||||
});
|
||||
|
||||
app.post('/tasks/:id/comments', async (req) => {
|
||||
app.post("/tasks/:id/comments", async (req) => {
|
||||
const { content, is_ai } = req.body;
|
||||
const { rows } = await app.db.query(
|
||||
'INSERT INTO task_comments (task_id, content, is_ai) VALUES ($1, $2, $3) RETURNING *',
|
||||
"INSERT INTO task_comments (task_id, content, is_ai) VALUES ($1, $2, $3) RETURNING *",
|
||||
[req.params.id, content, is_ai || false]
|
||||
);
|
||||
return { data: rows[0] };
|
||||
|
||||
Reference in New Issue
Block a user