Skip to content

Instantly share code, notes, and snippets.

@budasuyasa
Created May 6, 2018 04:01
Show Gist options
  • Save budasuyasa/68afd588b87217d3c511552fa5a0ab44 to your computer and use it in GitHub Desktop.
Save budasuyasa/68afd588b87217d3c511552fa5a0ab44 to your computer and use it in GitHub Desktop.
medium-post-simple-rest-05
app.post('/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 already in use');
}
})
}
),
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() });
}
book.create({
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
}).then(newBook => {
res.json({
"status":"success",
"message":"Book added",
"data": newBook
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment