Created
May 6, 2018 04:32
-
-
Save budasuyasa/1ecbcb49018ed492550b5d7a6932eaa5 to your computer and use it in GitHub Desktop.
medium-post-simple-rest-06
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app.put('/book/', [ | |
//File upload (karena pakai multer, tempatkan di posisi pertama agar membaca multipar form-data) | |
upload.single('image'), | |
//Set form validation rule | |
check('isbn') | |
.isLength({ min: 5 }) | |
.isNumeric() | |
.custom(value => { | |
return book.findOne({where: {isbn: value}}).then(b => { | |
if(!b){ | |
throw new Error('ISBN not found'); | |
} | |
}) | |
} | |
), | |
check('name') | |
.isLength({min: 2}), | |
check('year') | |
.isLength({min: 4, max: 4}) | |
.isNumeric(), | |
check('author') | |
.isLength({min: 2}), | |
check('description') | |
.isLength({min: 10}) | |
],(req, res) => { | |
const errors = validationResult(req); | |
if (!errors.isEmpty()) { | |
return res.status(422).json({ errors: errors.mapped() }); | |
} | |
const update = { | |
name: req.body.name, | |
isbn: req.body.isbn, | |
year: req.body.year, | |
author: req.body.author, | |
description: req.body.description, | |
image: req.file === undefined ? "" : req.file.filename | |
} | |
book.update(update,{where: {isbn: req.body.isbn}}) | |
.then(affectedRow => { | |
return book.findOne({where: {isbn: req.body.isbn}}) | |
}) | |
.then(b => { | |
res.json({ | |
"status": "success", | |
"message": "Book updated", | |
"data": b | |
}) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment