egg 系列之注册登陆接口实现

732 阅读3分钟

egg 系列之注册登陆接口实现

  • 缘起:

最近换了工作,从安放二厂去了一家互联网公司,还是从事的web前端开发,现在发现前端主要就是用react ,vue 以及相关的生态写业务代码 ,基本都一样,想一想如果再一次出去面试找工作的时候,你跟其他的应聘者的优势是什么 ,如果项目上没有亮点,那就应该从别的方面突破,比如说去贡献开源,或者说自己造轮子,node 已经是前端工程师的必备技能之一,所以我出的该系列是使用egg搭建后台,antd pro 搭建前端界面,之前写过一个系列是antd pro , 最近前一段时间面试了一个月,没有及时的更新,现在开始搞起来,还有我发现一点看egg 的文档发现对于我来说新领域还是不少的,这其实是后端的系统知识,看文档也是系统学习某一个领域的好方法,开始搞起来。

五一快乐!!!

  • 配置egg:

background:

文件目录:

文件目录

说一下文件夹的智能: controller 是对外的业务接口; extend 是类似于工具的集合; middleware 是中间件; model 是数据库的api 的封装; public 公共资源 service service 层的东西,model 业务的上一层封装 config 配置文件集合 其余的基本是logs类的东西,熟悉了文件夹的职能,在添加文件的时候才可以按照相同的职能继续添加;

写一个接口首先得设计数据库,用户表的字段: 数据表字段

操作数据库使用的是egg-sequlize orm 框架,看名字就知道是sequlize的一个plugin 封装。 配置的代码首先在config中配置一下:

  config.sequelize = {
    dialect: 'mysql',
    host: '127.0.0.1',
    port: 3306,
    database: 'egg-sequelize-doc-unittest',
  };

使用的是mysql 数据库 。 配置好之后,在model 文件夹中写一下基本的sql 封装语句,

app/model/user.js;

module.exports = app => {
  const { STRING, INTEGER, DATE } = app.Sequelize;
  // user 模型;
  const User = app.model.define('user', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    name: STRING(30),
    age: INTEGER,
    created_at: DATE,
    updated_at: DATE,
    password: STRING(100),
  });

  User.prototype.associate = function() {
    app.model.User.hasMany(app.model.Post, { as: 'posts' });
  };

  return User;
};

model 中是定义一个实体,在service 层封装上层的方法 ,使用的是model方法:

'use strict';

const Service = require('egg').Service;

class User extends Service {
  async list({ offset = 0, limit = 10 }) {
    return this.ctx.model.User.findAndCountAll({
      offset,
      limit,
      order: [[ 'created_at', 'desc' ], [ 'id', 'desc' ]],
    });
  }

  async find(id) {
    const user = await this.ctx.model.User.findByPk(id);
    if (!user) {
      this.ctx.throw(404, 'user not found');
    }
    return user;
  }

  async create(user) {
    return this.ctx.model.User.create(user);
  }

  async update({ id, updates }) {
    const user = await this.ctx.model.User.findByPk(id);
    if (!user) {
      this.ctx.throw(404, 'user not found');
    }
    return user.update(updates);
  }

  async del(id) {
    const user = await this.ctx.model.User.findByPk(id);
    if (!user) {
      this.ctx.throw(404, 'user not found');
    }
    return user.destroy();
  }
}

module.exports = User;

上面的service中调用model api 实现上层业务,之后在controller 中调用输出json 数据;

app/controller/user.js

'use strict';

const Controller = require('egg').Controller;

class UserController extends Controller {

  async login() {
    const ctx = this.ctx;
    // post请求传来的参数
    const { name, password } = ctx.request.body;
    let message = '',
      data = {};
    // 判断数据库里面是否存在该用户
    const user = await ctx.model.User.findOne({
      where: {
        name,
      },
    });
    if (!user) {
      message = '用户不存在';
    } else if (password !== user.password) {
      message = '密码错误';
    } else {
      message = '登录成功';
      data = { id: user.id };
    }

    ctx.body = {
      message,
      data,
    };
  }


  async register() {
    const ctx = this.ctx;
    const { name, password, age } = ctx.request.body;
    let data = {};
    let message = '';
    const res = await ctx.model.User.findOne({
      where: {
        name,
      },
    });
    if (res) {
      message = '用户已存在';
    } else {
      const insertresult = await ctx.service.user.create({ name, password, age });
      if (!insertresult) {
        message = '注册失败';
      } else {
        message = '注册成功';
        data = insertresult;
      }
    }
    ctx.body = {
      message,
      data,
    };
  }

}

module.exports = UserController;

controller 中调用service 方法实现,最后通过

ctx.body = {}

来输出json数据;

上面实现了最基本的注册、登陆功能。 后续计划实现restful api。 最基本的接口搭建好了 ,后面开始使用vue 搭建界面;

about me: yingbin , 微店web前端coder ,前端进击仔。欢迎交流 , personal WeChat :Yingbin192;