egg实战 数据库操作

455 阅读1分钟

先写个简单的增删改查,在service中创建个user.js文件,添加查询信息和插入信息的代码

image.png

调用queryUserName方法时返回了个空对象,ok没问题

image.png

调用 insertUser方法时报错了,提示是没有jacktest.user这个表,ok,那我们新建个表,百度一番之后,发现是需要先在mysql中建一个表

create table users(
  user_id int(10) unsigned NOT NULL auto_increment,
  username varchar(30),
  password varchar(30),
  created_at timestamp,
  primary key (user_id)
)engine=InnoDB AUTO_INCREMENT=1 comment '用户表'

此时我们再运行代码,成功。 然后对代码进行简单的修改,登录注册的逻辑就通了

// 登录逻辑
  async login() {
    const body = this.ctx.request.body;
    const { username, password } = body;
    const { user } = this.ctx.service;
    let postBody = {
      code: 0,
      msg: '',
      data: {},
    };
    // 先判断是否已存在
    const userData = await user.queryUserName(username);
    if (userData && Object.keys(userData).length) { // 已存在
      if (password === userData.password) {
        postBody = {
          ...postBody,
          code: 1,
          msg: '登录成功',
          data: { userData },
        };
        this.ctx.cookies.set('token', userData.user_id);
      } else {
        postBody.msg = '账号或密码错误';
        postBody.code = 0;
      }
      // 判断密码是否正确
      this.ctx.body = postBody;
      return;
    }
    this.ctx.body = {
      ...postBody,
      msg: '用户不存在',
    };
  }
  // 注册逻辑
  async register() {
    const body = this.ctx.request.body;
    const { username, password } = body;
    const { user } = this.ctx.service;
    const postBody = {
      code: 0,
      msg: '',
      data: {},
    };
    // 先判断是否已存在
    const userIsExists = await user.queryUserName(username);
    if (userIsExists && Object.keys(userIsExists).length) { // 已存在
      this.ctx.body = {
        ...postBody,
        msg: '用户已存在',
      };
      return;
    }
    // 创建用户
    const newUser = await user.insertUser({ username, password });
    if (newUser.affectedRows === 1) {
      const userData = await user.queryUserName(username);
      postBody.data = {
        userData,
      };
    }

    this.ctx.body = {
      ...postBody,
      msg: '注册成功',
    };
  }