import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import morgan from 'morgan';
import rateLimit from 'express-rate-limit';
import compression from 'compression';
import { DB } from './database.js';
const app = express();
const port = process.env.PORT || 3000;
const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
message: 'Too many requests from this IP, please try again later'
});
app.use(helmet());
app.use(cors());
app.use(compression());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(morgan('combined'));
app.use('/api/', limiter);
app.get('/api/products', (req, res) => {
const sql = 'SELECT * FROM products ORDER BY created_at DESC';
DB.all(sql, [], (err, rows) => {
if (err) {
return res.status(500).json({
error: 'Failed to fetch products',
details: err.message
});
}
res.status(200).json({
success: true,
count: rows.length,
data: rows
});
});
});
app.get('/api/products/:id', (req, res) => {
const { id } = req.params;
const sql = 'SELECT * FROM products WHERE id = ?';
DB.get(sql, [id], (err, row) => {
if (err) {
return res.status(500).json({
error: 'Database error',
details: err.message
});
}
if (!row) {
return res.status(404).json({
error: 'Product not found'
});
}
res.status(200).json({
success: true,
data: row
});
});
});
app.post('/api/products', (req, res) => {
const { name, description, price, category, stock } = req.body;
if (!name || !price || !category) {
return res.status(400).json({
error: 'Missing required fields: name, price, category'
});
}
if (price < 0) {
return res.status(400).json({
error: 'Price must be a positive number'
});
}
const sql = `INSERT INTO products (name, description, price, category, stock, created_at)
VALUES (?, ?, ?, ?, ?, datetime('now'))`;
DB.run(sql, [name, description, price, category, stock || 0], function(err) {
if (err) {
return res.status(500).json({
error: 'Failed to create product',
details: err.message
});
}
res.status(201).json({
success: true,
message: 'Product created successfully',
data: {
id: this.lastID,
name,
description,
price,
category,
stock: stock || 0
}
});
});
});
app.put('/api/products/:id', (req, res) => {
const { id } = req.params;
const { name, description, price, category, stock } = req.body;
DB.get('SELECT * FROM products WHERE id = ?', [id], (err, row) => {
if (err) {
return res.status(500).json({
error: 'Database error',
details: err.message
});
}
if (!row) {
return res.status(404).json({
error: 'Product not found'
});
}
const updates = [];
const values = [];
if (name !== undefined) {
updates.push('name = ?');
values.push(name);
}
if (description !== undefined) {
updates.push('description = ?');
values.push(description);
}
if (price !== undefined) {
if (price < 0) {
return res.status(400).json({
error: 'Price must be a positive number'
});
}
updates.push('price = ?');
values.push(price);
}
if (category !== undefined) {
updates.push('category = ?');
values.push(category);
}
if (stock !== undefined) {
updates.push('stock = ?');
values.push(stock);
}
if (updates.length === 0) {
return res.status(400).json({
error: 'No fields to update'
});
}
values.push(id);
const sql = `UPDATE products SET ${updates.join(', ')},
updated_at = datetime('now') WHERE id = ?`;
DB.run(sql, values, function(err) {
if (err) {
return res.status(500).json({
error: 'Failed to update product',
details: err.message
});
}
res.status(200).json({
success: true,
message: 'Product updated successfully',
data: { id, ...req.body }
});
});
});
});
app.delete('/api/products/:id', (req, res) => {
const { id } = req.params;
DB.get('SELECT * FROM products WHERE id = ?', [id], (err, row) => {
if (err) {
return res.status(500).json({
error: 'Database error',
details: err.message
});
}
if (!row) {
return res.status(404).json({
error: 'Product not found'
});
}
DB.run('DELETE FROM products WHERE id = ?', [id], (err) => {
if (err) {
return res.status(500).json({
error: 'Failed to delete product',
details: err.message
});
}
res.status(200).json({
success: true,
message: `Product with ID ${id} deleted successfully`
});
});
});
});
app.listen(port, () => {
console.log(`API server running on port ${port}`);
});