初始化工程
$ egg-init
选择 Simple
$ npm i
$ npm run dev
浏览器访问 http://localhost:7001 此时服务已经建立
设计API
egg Rest API 接口规范
Method | URL | File path | Controller name |
---|---|---|---|
GET | /api/{objects}[?per_page={per_page}&page] | app/controller/{objects}.js | index() |
GET | /api/{objects}/:id | app/controller/{objects}.js | show() |
POST | /api/{objects} | app/controller/{objects}.js | create() |
PUT | /api/{objects}/:id | app/controller/{objects}.js | update() |
DELETE | /api/{objects}/:id[s] | app/controller/{objects}.js | destroy() |
数据格式
{
"meta":{"total":3},
"data":[
{"_id":"58d8a899f5f2486f1f6d4236","uid":1,"name":"admin","pass":"123","status":1,"time":"1325472736"},
{"_id":"58db7828a14b14815447cf33","name":"sdf","pass":"123","status":1,"time":"1325472736","uid":3,"__v":0},
{"_id":"58db7d3bcee4d48df6f5bdfd","name":"sdddf","pass":"123","status":1,"time":"1325472736","uid":4,"__v":0}
]
}
api/users/1 GET Single Data
{
"meta":{"total":1},
"data":[
{"_id":"58d8a899f5f2486f1f6d4236","uid":1,"name":"admin","pass":"123","status":1,"time":"1325472736"}
]
}
api/users/2 PUT Update data with uid
{"name":"admin123","pass":"123","status":1,"time":"1325472736"}
api/users POST insert data
{"name":"admin123","pass":"123","status":1,"time":"1325472736"}
数据模型
此处先定义用户 User 对象,在 app 目录下 新建 model 文件夹,然后创建 users.js 文件。
每一个 User 对象需要包含 用户名、密码、邮箱、公司 等信息, users.js 文件内容如下:
// app/model/user.js
module.exports = app => {
const mongoose = app.mongoose;
const UserSchema = new mongoose.Schema({
email : {type: String, required: true},
password: {type: String, required: true},
realname: { type:String },
sex: { type: String },
corp: { type: String },
position: { type: String },
mobile: { type: String },
region: { type: String },
qq: { type: String },
wechat: { type: String },
bcardurl: { type: String },
bcardstate: { type: String }
});
UserSchema.methods.encryptPassword = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(5), null);
};
UserSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.password);
};
return mongoose.model('User', UserSchema);
}