backofshop
This is a back end for an e-commerce website built with the latest technologies, allowing the company to compete with other e-commerce companies. The application uses Express.js API, Sequelize, and MySQL2 to connect to a database and retrieve data for categories, products, and tags. The project includes schema and seed commands to create and populate a development database with test data.
Installation
To install and run on your local machine, follow these steps:
- Clone this repository to your local machine
- Install the necessary dependencies
npm init
npm install mysql2
npm install sequelize
npm install dotenv
Run the Application
mysql -u root -p
Enter PW when promted
source db/schema.sql
quit
npm run seed
npm start
Code Snippets
GET ROUTE for Tags
This route is using the Express Router to define a GET
route that retrieves a single tag by its ID
, and includes associated products. It first calls the Sequelize findOne()
method with the ID
parameter from the request. It then includes the associated model Product
and specifies which attributes to retrieve for it. The retrieved data is returned in JSON format using res.json()
. If an error occurs, it logs the error to the console and returns a 500 status code with the error in JSON format using res.status(500).json()
.
router.get('/:id', (req, res) => {
Tag.findOne({
where: {
id: req.params.id
},
include: {
model: Product,
attributes: ['product_name', 'price', 'stock', 'category_id']
}
})
.then(dbTagData => res.json(dbTagData))
.catch(err => {
console.log(err);
res.status(500).json(err);
});
});
DELETE Route For Category
This is a route in an Express.js API that handles a DELETE
request for a category resource. When a client makes a DELETE
request to the specified endpoint, the server will attempt to delete a category with the ID specified in the request parameters.
First, the Category model's destroy()
method is called with an object that specifies the ID of the category to be deleted. If the deletion is successful, the response will be a JSON object containing information about the deleted category.
If there is no category with the specified ID, the server will respond with a 404 status code and a JSON object containing an error message. If there is a server error during the deletion process, the server will respond with a 500 status code and a JSON object containing the error message.
router.delete('/:id', (req, res) => {
// delete a category by its `id` value
Category.destroy({
where: {
id: req.params.id
}
})
.then(dbCategoryData => {
if (!dbCategoryData) {
res.status(404).json({ message: 'No category found with this id' });
return;
}
res.json(dbCategoryData);
})
.catch(err => {
console.log(err);
res.status(500).json(err);
});
});