In the previous tutorial, you learn to create /products route with get method of router in Express with Mysql to fetch and filter data using findAndCountAll method.
Now we move on creating APIs to allow client apps to upload form data files using POST and PUT method, and delete rows from database using DELETE method. To upload form data with files, we use Multer library. By using Multer, you can easily upload files to local storage or cloud storage like amazon s3. Execute the following command to install Multer in to ExpressJs app.
npm install multer
To use Multer, you have to import it into routes/product.routes.js file:
.......
const {Op } = require("sequelize");
const multer = require('multer');
Write the following code to configure Multer to use public folder of the local storage:
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './public');
},
filename: function (req, file, callback) {
callback(null, Date.now().toString() + '-' + file.originalname);
}
});
const upload = multer({ storage : storage }).array('file',2);
Add more three routes using POST, PUT, and DELETE methods. The post route is to insert data to database, put route to update data, and the delete route to remove data from the database. Sequelize provides convenient methods - create, update, and destroy methods to perform the tasks.
// upload file to local storage - public folder
router.post("/products", function(req,res){
upload(req,res,function(err) {
if(err) {
return res.end("Error uploading file."+err);
}
// save upload product data to database
const { body } = req;
db.Product.create(
{
title:body.title,
description:body.description,
price:body.price,
}
).then(Product =>{
// save upload image files to database
let values=[];
for(const file of req.files) {
if(file.filename!==undefined){
values.push({fileUrl:file.filename,product_id:Product.id});
}
}
db.Image.bulkCreate(values);
// return success result
return res.status(200).json({
message: 'success',
data: Product,
});
}).catch(err => { // return err result
res.status(500).send({
message:
err.message || "Some error occurred while inserting new product"
});
});
});
});
// update product in database
router.put("/products", function(req,res){
upload(req,res,function(err) {
if(err) {
return res.end("Error uploading file."+err);
}
const { body } = req;
//console.log("body",body);
db.Product.update(
{
title:body.title,
description:body.description,
price:body.price,
},
{
where: { id: body.id },
}
).then(async data =>{
// also update images of the product
let values=[];
for(const file of req.files) {
if(file.filename!==undefined){
values.push({fileUrl:file.filename,product_id:body.id});
}
}
db.Image.bulkCreate(values);
//
return res.status(200).json({
message: 'success',
data: data,
});
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while update the product"
});
});
});
});
// delete product by id from database
router.delete("/products/:id/", function(req,res){
let pid = [req.params.id];
console.log("pid=",pid);
db.Product.destroy({
where: { id: pid },
}).then(data =>{
return res.status(200).json({
message: 'success',
data: data,
});
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while deleting the product"
});
});
});
Finally run node app.js to start development server.
Now it is ready to test the APIs. There are various tools to test the APIs to insert, update, and delete data against Mysql database. In this article, we are going to use ARC chrome extension. Thus, you need to add the ARC extension to chrome browser.
From chrome://apps open ARC.
To update a specific record in the database, simply change from method POST to PUT and make sure you include id of the record in text part in the body tab.
To delete a record, you have to choose method DELETE and append slash and id of the record to the Request Url. For example, to delete id-1 record, the Request Url must be written as below:
http://localhost:5000/products/1
Comments
Post a Comment