我是表示后端的新手,请原谅我。我想在Statue
路线Post
中创建POST
模型和\statues
模型,如下所示:
router.post('', [
//validate statue fields
body('location').not().isEmpty().withMessage("Please provide location"),
body('title').not().isEmpty().withMessage("Please provide a title"),
body('artist_name').not().isEmpty().withMessage("Please provide the artist's name"),
],function(req,res,next) {
//check form validation before consuming the request
const errors = validationResult(req);
if (!errors.isEmpty()) {
let errorObj = {};
errors.array().forEach(function(err) {
errorObj[err.param] = err.msg;
})
return res.status(422).json({ error:errorObj});
}
const body = req.body;
const location = body.location;
const title = body.title;
const statue_desc = body.statue_desc;
const artist_desc = body.artist_desc;
const artist_name = body.artist_name;
const artist_url = body.artist_url;
let statue = Statue.create({
location: location,
title: title,
statue_desc: statue_desc,
artist_desc: artist_desc,
artist_name: artist_name,
artist_url: artist_url
//image_id: null
})
.then(statue => {
console.log("--STATUE CREATED")
return statue;
})
.catch(err => {
return {status: 500, error: 'Failed to create a statue'}
});
statue = statue.get();
console.log("RETURNED STATUE: ", statue)
if (statue.error) {
console.log('Failed to create statue')
return res.status(statue.status).json({error: statue.error});
}
//TODO - create statue image
//pass statue to next state
res.locals.statue = statue;
next();
}, function(req,res,next) {
const statue = res.locals.statue;
let post = Post.perform_create(user_id, statue.location, statue.id);
if (post.error) {
console.log('Failed to create post')
res.status(post.status).json({error: post.error});
}
console.log("--created post: ", JSON.stringify(post))
//Todo serialize all statue data
//for now...
res.json(statue);
});
我在做什么,因为代码将同时执行.then and .catch
sequalize块的Statue.create
。
谢谢