Write it in front.
Recently learning Egg.js, it is Ali's launch of the KOA-based node development framework for enterprise-class frameworks and applications. Egg.js's official documentation has been perfected, and to learn egg.js, you can view the official documents directly.
Because normal development is a front-end separation of the pattern, you want to use egg to create a background service, write a set of API interface with other projects. The technical stack of the project was used in Egg.js, MongoDB, Mongoose. This article records my registration login module and User Center module process, the purpose is to timely induction of learning process, exercise document ability, and everyone to share exchanges and common progress.
Project Address: Egg-api
The project continues to update, like the Please dim sum, Attention, star, fork, these are my long-held momentum (. _ 。 ) ?_
Here is the text requirement analysis
For registered login module, the requirement analysis is as follows:
- Register as a new user and verify the input data
- Login into the system, you need to check the input data, based on token authentication
- Log out function
- Log in to view personal information in the User Center module
- Modify personal information in the User Center module
Data analysis and Design
Explicit data:
- Username:string User Name
- Userpass:string account password
- Useremail:string User Mailbox
- Telphone:string Mobile phone Number
- avatar:string Avatar
- Age:number Age
- sex:string Sex
- City:string City
Implicit data:
- Userrole:number User roles (1. Normal user, 2. admin, 3. Super Administrator, Default user is normal user, super administrator created when database is created)
- Usercreate:date User creation time
- Lastlogintime:date Last logon time
- Laseloginplace:string Last Login Address
API Analysis Design
The API in the following interface description refers to the interface name, the params refers to the incoming data, the code refers to the response result identification code, the MSG refers to the response result information description, data refers to the response to the successful return
Register interface
api: /api/v1/signup (post)params: { userName: String, // 用户名,具有唯一性 userPass: String, // 用户密码 userEmail: String, // 用户邮箱}code: 1、注册成功 0:输入信息不完善或有误 -1:注册失败,该用户名已存在msg: 响应返回的信息说明data: { _id: _id, userName: 用户名, token: 生成的token,}
Login interface
api: /api/v1/signin (post,请求头带token)params: { userName: String, // 用户名 userPass: String, // 用户密码}code: 1、登录成功 0:输入信息不完善或有误 -1:用户不存在msg: 响应返回的信息说明data: { _id: _id, userName: 用户名, lastLoginTime: 上次登录时间, lastLoginPlace: 上次登录地点,}
Log Out interface
api: /api/v1/signout (get)code: 1、登出成功,前端退出系统并清空tokenmsg: 登出响应返回信息说明data: {}
View personal Information interface
api: /api/v1/user/userName (post,请求头带token)params: { userName: String,}code: 1、查询成功 0、输入信息不完善 -1、查询失败msg: 查找个人信息返回信息说明data: { userName: 用户名, userEmail: 用户邮箱, age: 年龄, city: 城市, ......}
Change the personal information interface
api: /api/v1/user/userName (put,token)params: { ...... // 更改的信息}code: 1、更新成功 0、输入信息不完善或有误 -1、更新失败msg: 更新个人信息返回信息说明data: { userName: 用户名, ......}
Encoding implementation
Note: The code implementation instructions only provide partial, complete content please visit Egg-api
Suppose you have initialized a project, the directory structure of the project is agreed with the official. Because we want to use the MongoDB database, we need to install Egg-mongoose first and write in the configuration file:
// config/plugin.jsexports.mongoose = { enable: true, package: ‘egg-mongoose‘,};// config/config.default.jsconfig.mongoose = { url: ‘mongodb://127.0.0.1/apiExample‘, options: {},};
Define our schema file in the Model folder:
const UserSchema = new Schema({ userName: { type: String, unique: true, required: true, },});
Route definition:
router.post(‘/api/v1/signup‘, controller.user.signup);
Controller writing: Used to parse the user's input, and return the corresponding results after processing. We can put the acquired data into render and then send the rendered result to the viewer, or we can assign the data directly to Ctx.body and return it in JSON.
class UserController extends Controller { // 登录 async signin() { const { ctx } = this; const rule = { userName: { type: ‘string‘, required: true, message: ‘必填项‘ }, userPass: { type: ‘string‘, required: true, message: ‘必填项‘ }, }; const signinMsg = ctx.request.body; await ctx.validate(rule, signinMsg); signinMsg.userPass = ctx.helper.encrypt(signinMsg.userPass); const result = await ctx.service.user.signin(signinMsg); ctx.body = result; }}
Service authoring: Used to write a layer of business logic that can be reused. The processing of complex data, such as the information to be presented needs to be fetched from the database, or a call from a third-party service.
class UserService extends Service { // 更新用户信息 async updateUser(userMsg) { const { ctx } = this; const res = {}; const result = await ctx.model.User.findByIdAndUpdate(userMsg._id, userMsg); res.code = 1; res.msg = ‘用户信息已更改‘; res.data = result; return res; }}
A simple node application structure is this way, so that the implementation of the egg.js is responsible for interface services.
Egg.js Building the Backend service API