cnpm i egg-init -g
egg-init zhufengpeixunblog-api --type simple
cd zhufengpeixunblog-api
cnpm i
cnpm run dev
opoen localhost:7001
cnpm i egg-mongoose --save
// {app_root}config\plugin.js
exports.mongoose = {
enable: true,
package: 'egg-mongoose'
}
// {app_root}/config/config.default.js
exports.mongoose = {
client: {
url: 'mongodb://127.0.0.1/zhufengpeixunblog',
options: {},
},
};
// {app_root}/app/model/user.js
module.exports = app => {
const mongoose = app.mongoose;
const Schema = mongoose.Schema;
const ObjectId = Schema.Types.ObjectId;
const UserSchema = new Schema({
username: { type: String, required: true },
password: { type: String, required: true },
email: String
});
return mongoose.model('User', UserSchema);
}
const BaseControler = require('./base');
class UserController extends BaseControler {
//用户注册
async signup() {
let { ctx, app } = this;
let user = ctx.request.body;
try {
user = await ctx.model.User.create(user);
this.success(user);
} catch (error) {
this.error(error);
}
}
}
module.exports = app => {
const { router, controller } = app;
router.post('/api/users/signup', controller.users.signup);
};
config\config.default.js
config.security = {
csrf: false
}
//用户登录
async signin() {
let { ctx, app } = this;
let user = ctx.request.body;
try {
user = await ctx.model.User.findOne(user);
if (user) {
ctx.session.user = user;//保持会话
this.success({ user });
} else {
this.error('用户名或密码错误');
}
} catch (error) {
this.error(error);
}
}
router.post('/api/users/signin', controller.users.signin);
async signout() {
let { ctx } = this;
ctx.session.user = null;
this.success('success');
}
router.get('/api/users/signout', controller.users.signout);
| Method | Path | Controller.Action |
|---|---|---|
| POST | /posts | app.controllers.posts.create |
| GET | /posts | app.controllers.posts.index |
| PUT | /posts/:id | app.controllers.posts.update |
| DELETE | /posts/:id | app.controllers.posts.destroy |
\app\router.js
router.resources('categories', '/api/categories', controller.categories);
app\model\category.js
module.exports = app => {
const mongoose = app.mongoose;
const Schema = mongoose.Schema;
const ObjectId = Schema.Types.ObjectId;
const CategorySchema = new Schema({
name: { type: String, required: true }
});
return mongoose.model('Category', CategorySchema);
}
async create() {
let { ctx } = this;
let category = ctx.request.body;
try {
let doc = await ctx.model.Category.create(category);
this.success('success');
} catch (err) {
this.error(error);
}
}
//查询分类列表
async index() {
let { ctx } = this;
let { pageNum = 1, pageSize = 10, keyword } = ctx.query;
pageNum = isNaN(pageNum) ? 1 : parseInt(pageNum);
pageSize = isNaN(pageSize) ? 1 : parseInt(pageSize);
let query = {};
if (keyword) {
query.name = new RegExp(keyword);
}
let total = await ctx.model.Category.count(query);
let items = await ctx.model.Category.find(query).skip((pageNum - 1) * pageSize).limit(pageSize);
this.success({
items,
pageNum,
pageSize,
total,
pageCount: Math.ceil(total / pageSize)
});
}
//修改分类
async update() {
let { ctx } = this;
let id = ctx.params.id;
let category = ctx.request.body;
try {
let result = await ctx.model.Category.findByIdAndUpdate(id, category);
this.success('success');
} catch (err) {
this.error(error);
}
}
//删除分类
async destroy() {
let { ctx } = this;
let id = ctx.params.id;
let { ids = [] } = ctx.request.body;
ids.push(id);
try {
await ctx.model.Category.remove({ _id: { $in: ids } });
this.success('success');
} catch (error) {
this.error(error);
}
}
\app\router.js
router.resources('articles', '/api/articles', controller.articles);
router.get('/api/articles/pv/:id', controller.articles.updatePv);
router.post('/api/articles/comment/:id', controller.articles.comment);
app\model\article.js
module.exports=app => {
const mongoose=app.mongoose;
const Schema=mongoose.Schema;
const ObjectId=Schema.Types.ObjectId;
const ArticleSchema=new Schema({
user: {type: ObjectId,ref: 'User'},
category: { type: ObjectId, ref: 'Category' },
title: String,
content: String,
pv: { type: Number, default: 0 },
comments: [{ user: { type: ObjectId, ref: 'User' }, content: String, createAt: { type: Date, default: Date.now } }],
createAt: { type: Date, default: Date.now }
});
return mongoose.model('Article',ArticleSchema);
}
async create() {
let { ctx } = this;
let article = ctx.request.body;
article.user = this.user._id;
try {
let doc = await ctx.model.Article.create(article);
this.success('success');
} catch (error) {
this.error(error);
}
}
async index() {
let { ctx } = this;
let { pageNum = 1, pageSize = 10, keyword } = ctx.query;
pageNum = isNaN(pageNum) ? 1 : parseInt(pageNum);
pageSize = isNaN(pageSize) ? 1 : parseInt(pageSize);
let query = {};
if (keyword) {
query.title = new RegExp(keyword);
}
let total = await ctx.model.Article.count(query);
let items = await ctx.model.Article.find(query).populate('category').populate('comments').skip((pageNum - 1) * pageSize).limit(pageSize);
this.success({
items,
pageNum,
pageSize,
total,
pageCount: Math.ceil(total / pageSize)
});
}
async update() {
let { ctx } = this;
let id = ctx.params.id;
let article = ctx.request.body;
try {
let result = await ctx.model.Article.findByIdAndUpdate(id, article);
this.success('success');
} catch (err) {
this.error(error);
}
}
async destroy() {
let { ctx } = this;
let { ids } = ctx.request.body;
try {
await ctx.model.Article.remove({ _id: { $in: ids } });
this.success('success');
} catch (error) {
this.error(error);
}
}
async updatePv() {
let { ctx } = this;
let id = ctx.params.id;
try {
let result = await ctx.model.Article.findByIdAndUpdate(id, { $inc: { pv: 1 } });
this.success('success');
} catch (error) {
this.error(error);
}
}
async comment() {
let { ctx } = this;
let id = ctx.params.id;
let comment = ctx.request.body;
comment.user = this.user._id;;
try {
let result = await ctx.model.Article.findByIdAndUpdate(id, { $push: { comments: comment } });
this.success('success');
} catch (err) {
this.error(error);
}
}
$ npm i egg-cors --save
// {app_root}/config/plugin.js
exports.cors = {
enable: true,
package: 'egg-cors',
};
//{app_root}/config/config.default.jsexports.security = {
domainWhiteList: [ 'http://localhost:4200' ],
};
cnpm i egg-session-redis egg-redis -S
// {app_root}/config/plugin.js
exports.sessionRedis = {
enable: true,
package: 'egg-session-redis',
};
exports.redis = {
enable: true,
package: 'egg-redis',
}
// {app_root}/config/config.default.js
exports.redis = {
client: {
host: '127.0.0.1',
port: '6379',
password: 'zfpx',
db: '0',
},
agent:true
};
EGG_SERVER_ENV=prod
app.config.env
config
|- config.default.js
|- config.test.js
|- config.prod.js
|- config.unittest.js
`- config.local.js