Node-express项目--个人简历:搭建个人经历experience接口

Posted 安之ccy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Node-express项目--个人简历:搭建个人经历experience接口相关的知识,希望对你有一定的参考价值。

功能描述:
1.将用户输入的experience存储到数据库
2.验证输入的数据格式并给出提示
3.多次输入,默认是新增;比如有好几个精彩经历,加加加,全都加到简历上去
4.新增经历experience在整个experience的最前面

接口搭建:

  • 由于是个人操作自己的信息,所以需要有token验证身份
  • 通过req.user.id匹配发起请求的用户
  • 使用unshift将新增的experience加到整个experience的最前面,即最新加的经历在最前面
  • 保存数据到数据库
router.post("/experience", passport.authenticate("jwt", { session: false }), (req, res) => {

    // 寻找该用户的profile数据
    Profile.findOne({user:req.user.id})
    .then(profile=>{
        const newExp = {
            current:req.body.current,
            title:req.body.title,
            company:req.body.company,
            location:req.body.location,
            from:req.body.location,
            to:req.body.to,
            description:req.body.description
        }
        // 将此次输入的experience加到整个experience的最前面
        profile.experience.unshift(newExp)
        // 保存用户输入
        profile.save()
        .then(profile=>{
            res.json(profile)
        })
        .catch(err=>console.log(err))
    })
})

创建验证:

在validation文件夹下新建文件experience.js,是experience的验证文件

  • 引入必要模块
  • 由于在数据定义处(Profile.js文件)指定title、company、from三个字段是必填项,因此需要保证这三个字段的值为字符串,且这三个字段为空时给出提示
  • 返回错误提示信息
const Validator = require('validator');
const isEmpty = require("./empty");

module.exports = function validateExperienceInput(data) {
    let errors = {};

    //如果输入空(没有输入),需要将其改为空字符串
    data.title = !isEmpty(data.title) ? data.title : '';
    data.company = !isEmpty(data.company) ? data.company : '';
    data.from = !isEmpty(data.from) ? data.from : '';

    // title不能为空
    if (Validator.isEmpty(data.title)) {
        errors.title = "职位头衔title不能为空";
    }

    // company不能为空
    if (Validator.isEmpty(data.company)) {
        errors.company = "公司company不能为空";
    }

    // from
    if (Validator.isEmpty(data.from)) {
        errors.from = "起始时间from不能为空";
    }

    return {
        errors,
        isValid: isEmpty(errors)
    }
}

使用验证文件:

先引入到profile.js中:

const validateExperienceInput = require("../../validation/experience");

在experience接口中使用:

    // 验证数据格式
    const { errors, isValid } = validateExperienceInput(req.body);
    if (!isValid) {
        return res.status(400).json({ errors })
    }

在这里插入图片描述

postman测试

验证测试

当必填项没有输入时,提示该项不能为空:
在这里插入图片描述

正常测试

第一次使用experience接口:
在这里插入图片描述
第二次提交experience(在同一个用户,测试unshift功能:将新增经历加到最前面)

在这里插入图片描述

以上是关于Node-express项目--个人简历:搭建个人经历experience接口的主要内容,如果未能解决你的问题,请参考以下文章

Node-express项目--个人简历:搭建当前用户的个人信息接口Profile

Node-express项目--个人简历:搭建posts接口并实现评论点赞以及相关功能

Node-express项目--个人简历:搭建posts接口并实现评论点赞以及相关功能

Node-express项目--个人简历:register(注册)接口编写记录

Node-express项目--个人简历:login(登录)接口编写记录

Node-express项目--个人简历:删除某条个人经历experience 删除整个User信息