egg mysql 项目实战,egg.js创建项目,目录介绍,简单使用,sequelize mysql使用

1、egg项目的创建

创建项目 npm init egg --type=simple

安装依赖 npm i

依赖安装完成后运行命令 npm run dev 即可运行项目

参考官方文档 https://eggjs.org/zh-cn/intro/quickstart.html

2、egg目录介绍

egg-project

├── package.json

├── app.js (可选)

├── agent.js (可选)

├── app

| ├── router.js

│ ├── controller // C 控制器,逻辑都在这边实现

│ | └── home.js

│ ├── service (可选) // M 数据库获取数据在这边实现

│ | └── user.js

│ ├── middleware (可选)

│ | └── response_time.js

│ ├── model (可选) // 数据库模型放着

│ ├── schedule (可选)

│ | └── my_task.js

│ ├── public (可选)

│ | └── reset.css

│ ├── view (可选) // V 页面渲染

│ | └── home.tpl

│ └── extend (可选)

│ ├── helper.js (可选)

│ ├── request.js (可选)

│ ├── response.js (可选)

│ ├── context.js (可选)

│ ├── application.js (可选)

│ └── agent.js (可选)

├── config

| ├── plugin.js

| ├── config.default.js

│ ├── config.prod.js

| ├── config.test.js (可选)

| ├── config.local.js (可选)

| └── config.unittest.js (可选)

└── test

├── middleware

| └── response_time.test.js

└── controller

└── home.test.js

如上,由框架约定的目录:

app/router.js 用于配置 URL 路由规则,具体参见 Router。

app/controller/** 用于解析用户的输入,处理后返回相应的结果,具体参见 Controller。

app/service/** 用于编写业务逻辑层,可选,建议使用,具体参见 Service。

app/middleware/** 用于编写中间件,可选,具体参见 Middleware。

app/public/** 用于放置静态资源,可选,具体参见内置插件 egg-static。

app/extend/** 用于框架的扩展,可选,具体参见框架扩展。

config/config.{env}.js 用于编写配置文件,具体参见配置。

config/plugin.js 用于配置需要加载的插件,具体参见插件。

test/** 用于单元测试,具体参见单元测试。

app.js 和 agent.js 用于自定义启动时的初始化工作,可选,具体参见启动自定义。关于agent.js的作用参见Agent机制。

由内置插件约定的目录:

app/public/** 用于放置静态资源,可选,具体参见内置插件 egg-static。

app/schedule/** 用于定时任务,可选,具体参见定时任务。

3、简单的使用

Service 写法

// app/service/user.js

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

class UserService extends Service {

async find(uid) {

// 下面这句就是数据库获取数据

const user = await this.ctx.db.query('select * from user where uid = ?', uid);

return user;

}

}

module.exports = UserService;

Controller 写法

// app/controller/user.js

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

class UserController extends Controller {

async getUserList() {

const { ctx, service } = this;

// 调用 Service 进行业务处理

const res = await service.user.find(ctx.query.uid);

// 设置响应内容和响应状态码

ctx.body = { res };

ctx.status = 201;

}

async delUser() {

// ...............

}

}

module.exports = UserController;

Router 写法

// app/router.js

module.exports = app => {

const { router, controller } = app;

router.get('/user', controller.user.getUserList);

router.post('/user/del', controller.user.delUser);

};

4、sequelize,mysql的使用

安装 npm install --save egg-sequelize mysql2

然后启用插件( 在 config/plugin.js 中引入 egg-sequelize 插件)

// config/plugin.js

exports.sequelize = {

enable: true,

package: 'egg-sequelize',

};

接着配置数据库信息(在 config/config.default.js 中添加 sequelize 配置)

'use strict';

/**

* @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 + '_1595165791967_5765';

// add your middleware config here

config.middleware = [];

config.sequelize = {

dialect: 'mysql',

host: 'localhost',

port: 3306,

database: 'shop',

username: 'root',

password: '123456',

};

// add your user config here

const userConfig = {

// myAppName: 'egg',

};

return {

...config,

...userConfig,

};

};

然后配置数据库模型,在 /app的目录下 建立 model文件夹,然后在 model文件夹建立一个 model文件( 如 /app/model/user.js )

'use strict';

module.exports = app => {

const { STRING, INTEGER, TINYINT } = app.Sequelize;

const User = app.model.define('users',

{

id: {

type: INTEGER(10), // 数据类型

allowNull: false, // 是否为 null

primaryKey: true, // 是否为 主键

autoIncrement: true, // 是否 自动填值

},

username: {

type: STRING(100),

allowNull: false,

defaultValue: '', // 默认值

},

age: {

type: TINYINT,

allowNull: false,

defaultValue: 0, // 默认值

},

password: {

type: STRING(100),

allowNull: false,

defaultValue: '',

},

},

{

freezeTableName: true, // Model 对应的表名将与model名相同

timestamps: false,

}

);

return User;

};

最后就是使用(比如在service/user.js)

'use strict';

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

class userService extends Service {

async getUserAllList() {

const { ctx } = this;

// 注意 ctx.model.User 中的 User 是 model 下 user.js 的文件的首字母大写的名称

return await ctx.model.User.findAll();

}

}

module.exports = userService

表关联参考 https://blog.csdn.net/weixin_39066827/article/details/107106472

本文地址:https://blog.csdn.net/john_xiaoweige/article/details/107499974

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值