82 lines
2.2 KiB
TypeScript
82 lines
2.2 KiB
TypeScript
import express from 'express';
|
|
import { getDatabase, saveDatabase } from './db/database.js';
|
|
import { createRecipeRoutes } from './routes/recipes.js';
|
|
|
|
const app = express();
|
|
const port = 3000;
|
|
const DB_PATH = 'data/recipes.db';
|
|
|
|
// Middleware
|
|
app.use(express.json());
|
|
app.use(express.urlencoded({ extended: true }));
|
|
|
|
// CORS headers for local development
|
|
app.use((req, res, next) => {
|
|
res.header('Access-Control-Allow-Origin', '*');
|
|
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
|
|
res.header('Access-Control-Allow-Headers', 'Content-Type');
|
|
|
|
if (req.method === 'OPTIONS') {
|
|
res.sendStatus(200);
|
|
} else {
|
|
next();
|
|
}
|
|
});
|
|
|
|
// Health check endpoint
|
|
app.get('/', (req, res) => {
|
|
res.json({
|
|
success: true,
|
|
message: 'Recipe Manager API is running',
|
|
version: '0.1.0',
|
|
});
|
|
});
|
|
|
|
// Initialize database and routes
|
|
async function startServer() {
|
|
try {
|
|
const db = await getDatabase(DB_PATH);
|
|
|
|
// Mount recipe routes
|
|
app.use('/api/recipes', createRecipeRoutes(db));
|
|
|
|
// Save database periodically (every 5 seconds)
|
|
setInterval(() => {
|
|
try {
|
|
saveDatabase(DB_PATH);
|
|
} catch (error) {
|
|
console.error('Error saving database:', error);
|
|
}
|
|
}, 5000);
|
|
|
|
// Save database on exit
|
|
process.on('SIGINT', () => {
|
|
console.log('\nSaving database before exit...');
|
|
saveDatabase(DB_PATH);
|
|
process.exit(0);
|
|
});
|
|
|
|
process.on('SIGTERM', () => {
|
|
console.log('\nSaving database before exit...');
|
|
saveDatabase(DB_PATH);
|
|
process.exit(0);
|
|
});
|
|
|
|
app.listen(port, () => {
|
|
console.log(`✓ Recipe Manager API running on http://localhost:${port}`);
|
|
console.log(`✓ Database: ${DB_PATH}`);
|
|
console.log(`✓ Endpoints:`);
|
|
console.log(` GET /api/recipes - List recipes`);
|
|
console.log(` GET /api/recipes/:id - Get recipe by ID`);
|
|
console.log(` POST /api/recipes - Create recipe`);
|
|
console.log(` PUT /api/recipes/:id - Update recipe`);
|
|
console.log(` DELETE /api/recipes/:id - Delete recipe`);
|
|
});
|
|
} catch (error) {
|
|
console.error('Failed to start server:', error);
|
|
process.exit(1);
|
|
}
|
|
}
|
|
|
|
startServer();
|