快速路由成功与失败

时间:2018-06-29 03:00:44

标签: javascript express promise sequelize.js

我是表示后端的新手,请原谅我。我想在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。 谢谢

0 个答案:

没有答案