服务器引擎egg.js

2022-12-05  本文已影响0人  brave_wu

1.安装

npm i egg-bin --save-dev

2.脚手架

mkdir egg-example && cd egg-example
npm init egg --type=simple
npm i

3.安装与链接数据库(MySQL)

首先先安装数据库

brew install mysql

或者直接下载
链接数据有官方插件

npm i --save egg-mysql

找到app/config/plugin.js

 exports.mysql = {
  enable: true,
  package: 'egg-mysql',
};

app/config/config.default.js 中配置数据库

 exports.mysql = {   // 单数据库信息配置   
  client: {
    host: 'mysql.com',
    port: '3306',
    user: 'test_user',
    password: 'test_password',
    database: 'test'
   },   
  // 是否加载到 app 上,默认开启
  app: true,   
  // 是否加载到 agent 上,默认关闭   
  agent: false
};

数据库的增删改查

1.查
const post = await this.app.mysql.get('posts', { id: 12 });
或者
const results = await this.app.mysql.select('posts', { // 搜索 post 表
  where: { status: 'draft', author: ['author1', 'author2'] }, // WHERE 条件
  columns: ['author', 'title'], // 要查询的表字段
  orders: [['created_at','desc'], ['id','desc']], // 排序方式
  limit: 10, // 返回数据量
  offset: 0, // 数据偏移量
});
2.增
const result = await this.app.mysql.insert('posts', { title: 'Hello World' });
3.改
const result = await this.app.mysql.update('posts', ‘hi’);
4.删
const result = await this.app.mysql.delete('posts', {
  author: 'fengmk2',
});

当然,更复杂场景的我们可能需要使用Sequelize,对应的也有插件 egg-sequelize

4.启动项目

npm run dev
open http://localhost:7001

5.文档

相应模块具体文档直接查看文档

上一篇 下一篇

猜你喜欢

热点阅读