micqil/orderflow-ninjas
0
1 2require('dotenv').config();3const express = require('express');4const cors = require('cors');5const connectDB = require('./config/db');6const Order = require('./models/orderModel');7const app = express();8const PORT = process.env.PORT || 3000;9 10// Connect to database11connectDB();12 13// Middleware14app.use(cors());15app.use(express.json());16 17// Seed initial data if needed18async function seedDatabase() {19 const count = await Order.countDocuments();20 if (count === 0) {21 await Order.create([22 {23 customer: 'John Smith',24 status: 'Processing',25 items: 3,26 total: 149.99,27 image: 'http://static.photos/technology/320x240/1'28 },29 {30 customer: 'Sarah Johnson',31 status: 'Shipped',32 items: 5,33 total: 289.50,34 image: 'http://static.photos/retail/320x240/2'35 }36 ]);37 console.log('Database seeded with initial data');38 }39}40seedDatabase();41// API Routes42app.get('/api/orders', async (req, res) => {43 try {44 const orders = await Order.find().sort({ createdAt: -1 });45 res.json(orders);46 } catch (err) {47 res.status(500).json({ message: err.message });48 }49});50 51app.post('/api/orders', async (req, res) => {52 try {53 const order = new Order({54 customer: req.body.customer,55 items: req.body.items,56 total: req.body.total,57 image: req.body.image || 'http://static.photos/technology/320x240/1',58 status: 'Processing'59 });60 const newOrder = await order.save();61 res.status(201).json(newOrder);62 } catch (err) {63 res.status(400).json({ message: err.message });64 }65});66 67app.put('/api/orders/:id', async (req, res) => {68 try {69 const order = await Order.findByIdAndUpdate(70 req.params.id,71 req.body,72 { new: true, runValidators: true }73 );74 if (!order) {75 return res.status(404).json({ message: 'Order not found' });76 }77 res.json(order);78 } catch (err) {79 res.status(400).json({ message: err.message });80 }81});82 83app.delete('/api/orders/:id', async (req, res) => {84 try {85 const order = await Order.findByIdAndDelete(req.params.id);86 if (!order) {87 return res.status(404).json({ message: 'Order not found' });88 }89 res.status(204).end();90 } catch (err) {91 res.status(500).json({ message: err.message });92 }93});94// Start server95app.listen(PORT, () => {96 console.log(`Server running on port ${PORT}`);97});