首页 > 其他分享 >egg.js. demo

egg.js. demo

时间:2023-02-19 10:32:16浏览次数:66  
标签:body const sender demo ctx js mongoose egg


丑团git
前端 expo ​​​https://gitee.com/honbingitee/ugly-tuan-expo​​​ 后端 egg.js ​​https://gitee.com/honbingitee/ugly-tuan-egg​

egg.js. demo_nodejs

/* eslint-disable indent */
'use strict';

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

class CommentController extends Controller {
/**
* 创建评论
* @param {string} content
* @param {number} type
* @param {ObjectId} sender
*/
async createComment() {
const { ctx } = this;
console.log("body:", ctx.request.body);
const { body } = ctx.request;
const { content, type = 0, sender: senderIdStr = "61793fcd45c2dbfa30e709c1" } = body;
if (!content || !senderIdStr)
ctx.body = { code: -1, message: "检查参数" };
else {
const senderId = mongoose.Types.ObjectId(senderIdStr);
const comment = { content, type, sender: senderId, thumbsUp: 0 };
const sender = await ctx.model.User.find({ _id: senderId });
if (!sender.length) ctx.body = { code: -2, message: "查无此人" };
else {
console.log("sender:", sender);
console.log("comment:", comment);
const item = await ctx.model.Comment.create(comment);
console.log("result:", item);
if (item) {
const payload = { ...comment, sender, _id: item._id };
console.log("payload:", payload);
ctx.body = { code: 0, payload };
} else ctx.body = { code: -3, message: '创建失败' };
}
}
}
async queryComment() {
const { ctx } = this;
let { limit } = ctx.query;
limit = Number(limit);

// const comments = await ctx.model.Comment.find().limit(isNaN(limit) ? 20 : limit);
const comments = await ctx.model.Comment.aggregate([
{
$lookup: {
from: 'user',
localField: 'sender',
foreignField: '_id',
as: 'sender'
}
},
{ $limit: isNaN(limit) ? 20 : limit },
{ $sort: { _id: -1 } }
]);
console.log("comments:", comments);
ctx.body = { comments };
}
async thumbsUp() {
const { ctx } = this;
const { _id } = ctx.request.body;
const item = await ctx.model.Comment.update({ _id }, {
$inc: { thumbsUp: 1 }
});
console.log(item);
if (item.ok) {
ctx.body = { code: 0, message: '点赞成功' }
} else ctx.body = { code: -1, message: '这都能失败' }
}
}

module.exports = CommentController;

egg.js. demo_git_02

module.exports = app => {
const mongoose = app.mongoose;
const Schema = mongoose.Schema;

const CommentSchema = new Schema({
content: { type: String },
type: { type: Number },
sender: { type: mongoose.Types.ObjectId },
thumbsUp: { type: Number }
});

return mongoose.model('Comment', CommentSchema, 'comment');
}

egg.js. demo_前端_03

'use strict';

/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const { router, controller } = app;
router.get('/', controller.home.index);
router.post('/createComment', controller.comment.createComment);
router.get('/queryComment', controller.comment.queryComment);
router.post('/thumbsUp', controller.comment.thumbsUp);
};

egg.js. demo_git_04

/* eslint valid-jsdoc: "off" */

'use strict';

const options = {
host: "159.75.22.82",
port: "27017",
db_name: "uglyTuan",
user: "hongbin",
pass: "Hongbin",
};

const url = `mongodb://${options.user}:${options.pass}@${options.host}:${options.port}/${options.db_name}`;

/**
* @param {Egg.EggAppInfo} appInfo app info
*/
module.exports = appInfo => {
/**
* built-in config
* @type {Egg.EggAppConfig}
**/
const config = exports = {};

// use for cookie sign key, should change to your own and keep security
config.keys = appInfo.name + '_1635295023359_9413';

// add your middleware config here
config.middleware = [];

// add your user config here
const userConfig = {
// myAppName: 'egg',
};

config.security = {
csrf: {
enable: false,
},
};

config.cluster = {
https: {
key: '../../Nginx_SSL/2_hongbin.xyz.key',
cert: '../../Nginx_SSL/1_hongbin.xyz_bundle.crt'
}
};

return {
...config,
...userConfig,
mongoose: {
url,
options: {
useUnifiedTopology: true
}
}
};
};

egg.js. demo_ci_05

/** @type Egg.EggPlugin */
module.exports = {
// had enabled by egg
// static: {
// enable: true,
// }
mongoose: {
enable: true,
package: 'egg-mongoose',
}
};

​package.json​

{
"name": "uglyTuan",
"version": "1.0.0",
"description": "",
"private": true,
"egg": {
"declarations": true
},
"dependencies": {
"egg": "^2.15.1",
"egg-mongoose": "^3.3.1",
"egg-scripts": "^2.11.0"
},
"devDependencies": {
"autod": "^3.0.1",
"autod-egg": "^1.1.0",
"egg-bin": "^4.11.0",
"egg-ci": "^1.11.0",
"egg-mock": "^3.21.0",
"eslint": "^5.13.0",
"eslint-config-egg": "^7.1.0"
},
"engines": {
"node": ">=10.0.0"
},
"scripts": {
"start": "egg-scripts start --daemon --title=egg-server-uglyTuan",
"stop": "egg-scripts stop --title=egg-server-uglyTuan",
"dev": "egg-bin dev",
"debug": "egg-bin debug",
"test": "npm run lint -- --fix && npm run test-local",
"test-local": "egg-bin test",
"cov": "egg-bin cov",
"lint": "eslint .",
"ci": "npm run lint && npm run cov",
"autod": "autod"
},
"ci": {
"version": "10"
},
"repository": {
"type": "git",
"url": ""
},
"author": "hongbin",
"license": "MIT"
}


标签:body,const,sender,demo,ctx,js,mongoose,egg
From: https://blog.51cto.com/u_15964288/6066506

相关文章

  • NodeJS安装(Mac版本)
    nvm,node,npm之间的区别nvm:nodejs版本管理工具。也就是说:一个nvm可以管理很多node版本和npm版本。nodejs:在项目开发时的所需要的代码库npm:nodejs包管理工具。......
  • [State Machine] Zag-js
    import{createMachine}from"@zag-js/core";typeMachineState={value:"idle"|"focused";};typeMachineContext={value:string[];focusedIndex......
  • 【JS 】SharedWorker 优化前端轮询请求(续)
    1.书接上回【JS】SharedWorker优化前端轮询请求经过一顿改造,性能是上去了,但是代码却还是不够简洁,所以继续封装2.思路目标:使用一个js文件完成所有轮询请求,封装调用......
  • 【JS 】SharedWorker 优化前端轮询请求
    1.背景目前公司系统首页存在一个定时的轮询请求/Admin/Dashboard/GetAppRelaseNotice,包含一些需要实时反映在前端的操作(如:页面版本,站内信,页面配置更新等)问题很明显,单......
  • 为了实现客服系统关键词分隔符切分,封装js实现根据多个分隔符分隔字符串为数组
    需求用户可以设置关键词回复,默认是以英文逗号分隔,但是很多人会打成中文逗号,需要能兼容处理解决为了实现客服系统关键词分隔符切分,封装js实现根据多个分隔符分隔字符串为......
  • 从零入门Vue.js!六步学习路线和知识体系盘点详解!
    Vue.js是一款流行的JavaScript前端框架,它允许开发者轻松地构建交互性强的用户界面。学习这个阶段的时候有一定门槛,并不是属于零基础就能入门学习的,在学习vue.js的时候可以......
  • 【JS】简单复习及ES6
    一、JavaScript基础及ES6视频链接:https://www.bilibili.com/video/BV1Y84y1L7Nn 10.变量的声明var与let首先说结论,放弃var,使用let。let为了解决var的一些......
  • Spring IOC官方文档学习笔记(十一)之使用JSR 330标准注解
    1.使用@Inject和@Named进行依赖注入(1)Spring提供了对JSR330标准注解的支持,因此我们也可以使用JSR330标准注解来进行依赖注入,不过,在此之前,我们得先使用maven添加相关依......
  • uni-app:template、js、css中判断平台(hbuilderx 3.6.18)
    一,代码:<template><viewstyle=""><viewstyle="margin-top:30rpx;width:710rpx;margin-left:20rpx;text-align:center;font-size:50rpx;"><......
  • 【JS】Pug调用自定义JS函数
    当我用node.js从数据库中查询datetime类型的日期字段,并输出到网页上时,发现JS自动进行了类型转换:由2023-01-0721:47:00变成了 SatJan07202321:47:00GMT+0800......