data mongo server
Published: 2024-01-26 22:37:24

const express = require('express')
const cors = require('cors')

const db = require('./mongoDb/index.js')
const { getAllProducts, createProduct, getProductById, updateProduct, deleteProduct } = require('./mongoDb/index');


const port = 1991
const app = express()

app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

app.get('/api/products', async (req, res) => {
  try { 
          const products = await getAllProducts()
           res.status(200).json(products)
  } 
  catch (error) {
    console.error(error)
    res.status(500).json({ error: 'Internal Server Error' })
  }
})

app.get('/api/products/:id', async (req, res) => {
  try {
          const productId = req.params.id
          const product = await getProductById(productId)

     if (!product) {
      return res.status(404).json({ error: 'Product not found' })
    }

    res.status(200).json(product)
  } catch (error) {
    console.error(error)
    res.status(500).json({ error: 'Internal Server Error' })
  }
})

app.post('/api/products', async (req, res) => {
  try {
    const newProduct = await createProduct(req.body)
    res.status(201).json(newProduct)
  } catch (error) {
    console.error(error)
    res.status(500).json({ error: 'Internal Server Error' })
  }
})


app.put('/api/products/:id', async (req, res) => {
  try {
    const productId = req.params.id
    const updatedProduct = await updateProduct(productId, req.body)

    if (!updatedProduct) {
      return res.status(404).json({ error: 'Product not found' })
    }

    res.status(200).json(updatedProduct)
  } catch (error) {
    console.error(error)
    res.status(500).json({ error: 'Internal Server Error' })
  }
})


app.delete('/api/products/:name', async (req, res) => {
  try {
    const productId = req.params.name
    const deletedProduct = await deleteProduct(productId)

    if (!deletedProduct) {
      return res.status(404).json({ error: 'Product not found' })
    }

    res.status(200).json(deletedProduct)
  } catch (error) {
    console.error(error)
    res.status(500).json({ error: 'Internal Server Error' })
  }
})




app.listen(port, () => {
  console.log(`listening on ${port}`)
})



/////////////mogoose
const mongoose = require('mongoose');

class ProductController {
  constructor() {
    this.mongoUri = 'mongodb://127.0.0.1/namedata';
    this.connectToDatabase();
  }

  async connectToDatabase() {
    try {
      await mongoose.connect(this.mongoUri, { useUnifiedTopology: true, useNewUrlParser: true });
      console.log('MongoDB connected');
    } catch (error) {
      console.error(error);
      throw error;
    }
  }

  getAllProducts = async () => {
    try {
      const products = await this.Product.find();
      return products;
    } catch (error) {
      console.error(error);
      throw error;
    }
  }

  createProduct = async (productData) => {
    try {
      const newProduct = new this.Product(productData);
      const savedProduct = await newProduct.save();
      return savedProduct;
    } catch (error) {
      console.error(error);
      throw error;
    }
  }

  updateProduct = async (productId, updatedData) => {
    try {
      const updatedProduct = await this.Product.findByIdAndUpdate(
        productId,
        updatedData,
        { new: true }
      );
      return updatedProduct;
    } catch (error) {
      console.error(error);
      throw error;
    }
  }

  deleteProduct = async (productId) => {
    try {
      const deletedProduct = await this.Product.findByIdAndDelete(productId);
      return deletedProduct;
    } catch (error) {
      console.error(error);
      throw error;
    }
  }

  getProductById = async (productId) => {
    try {
      const product = await this.Product.findById(productId);
      return product;
    } catch (error) {
      console.error(error);
      throw error;
    }
  }
}

const productSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  price: {
    type: Number,
    required: true,
  },
  description: {
    type: String,
  },
  // Add other fields as needed
});

ProductController.Product = mongoose.model('Product', productSchema);

module.exports = new ProductController();