zoukankan      html  css  js  c++  java
  • Node.Js 搭建简单的 EggJs 示例项目

    本项目包含 MVC 功能示例

    项目目录结构约定规范

    egg-project
    ├── package.json
    ├── app.js (可选)
    ├── agent.js (可选)
    ├── app
    |   ├── router.js
    │   ├── controller
    │   |   └── home.js
    │   ├── service (可选)
    │   |   └── user.js
    │   ├── model (可选)
    │   |   └── UserModel.js
    │   ├── middleware (可选)
    │   |   └── response_time.js
    │   ├── schedule (可选)
    │   |   └── my_task.js
    │   ├── public (可选)
    │   |   └── reset.css
    │   ├── view (可选)
    │   |   └── 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
    

    文件命名规则

    1、控制器名称:PsUserController.js(等效于ps_user_controller.js),调用方式:this.ctx.controller.psUserController.index,即文件名首字母改小写就可以。与导出的类名无关。

    controller file class name
    user.js app.controller.user
    person.js app.controller.person
    user_group.js app.controller.userGroup
    user/profile.js app.controller.user.profile
    UserController.js app.controller.userController

    2、模型名称:PsUserModel.js,调用方式:this.ctx.model.PsUserModel.findAll(),首字母一定是大写,与导出的类名无关。

    model file class name
    user.js app.model.User
    person.js app.model.Person
    user_group.js app.model.UserGroup
    user/profile.js app.model.User.Profile
    UserModel.js app.model.UserModel

    数据表包含时间戳字段: created_at datetime, updated_at datetime。
    字段名使用小写下划线的蛇形命名法,例如:user_id, comments_count。

    安装

    # 初始化 Eggjs 骨架
    npm init egg --type=simple
    # 安装基础包
    npm install
    # 启动(生产环境,日志较少) / 调试(推荐,调试环境,日志丰富,自动重启) / 测试
    # npm start / npm run dev / npm test
    npm run dev
    

    在浏览器打开:http://127.0.0.1:7001/

    安装依赖包

    npm install --save egg-sequelize mysql2 sequelize-auto egg-view-nunjucks
    

    配置模板引擎视图层

    配置插件文件(/config/plugin.js)

    'use strict';
    
    /** @type Egg.EggPlugin */
    module.exports = {
      // had enabled by egg
      // 静态资源目录
      static: {
        enable: true,
      },
      // 配置模板引擎插件
      nunjucks: {
        enable: true,
        package: 'egg-view-nunjucks',
      }
    };
    

    配置默认配置文件(/config/config.default.js)

    /* eslint valid-jsdoc: "off" */
    
    'use strict';
    const NmPath=require('path')
    /**
     * @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 + '_1611978775015_4782';
    
      // add your middleware config here
      config.middleware = [];
      // 视图层模板引擎配置内容
      config.view={
        root:NmPath.join(appInfo.baseDir,'app/view'),
        defaultViewEngine: 'nunjucks',
        defaultExtension: '.html',
      }
    
      // add your user config here
      const userConfig = {
        // myAppName: 'egg',
      };
    
      return {
        ...config,
        ...userConfig,
      };
    };
    

    修改控制器文件(/app/controller/home.js)

    'use strict';
    
    const Controller = require('egg').Controller;
    
    class HomeController extends Controller {
      async index() {
        const { ctx } = this;
        // ctx.body = 'hi, egg';
        await ctx.render('index',{name:'view page...'})
      }
    }
    
    module.exports = HomeController;
    

    新建视图文件(/app/view/index.html)

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Home</title>
    </head>
    <body>
        hello {{name}}
    </body>
    </html>
    

    运行调试:

    npm run dev
    

    至此,模板引擎配置完成。刷新浏览器,即可看到模板引擎的是否生效

    配置数据库模型层

    创建数据库和数据表

    -- 创建数据库
    CREATE DATABASE IF NOT EXISTS db_test DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_general_ci;
    use db_test;
    
    SET NAMES utf8mb4;
    SET FOREIGN_KEY_CHECKS = 0;
    
    -- 创建数据表: 用户表
    -- DROP TABLE IF EXISTS `tbl_user`;
    CREATE TABLE `tbl_user`  (
      `id` INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
      `user_name` VARCHAR(60) NOT NULL COMMENT '用户账号',
      `password` VARCHAR(32) NOT NULL COMMENT '用户密码',
      `created_at` INT UNSIGNED NOT NULL COMMENT '注册时间',
      `status` TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态(1=正常,0=禁止)',
      PRIMARY KEY (`id`),
      KEY `idx_user_name`(`user_name`),
      KEY `idx_status`(`status`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户表';
    

    从数据库自动生成对应的模型文件(ES6类的内容格式)

    # npx sequelize-auto -h 数据库的IP地址 -d 数据库名 -u 用户名 -x 密码 -p 端口 -t 表名
    npx sequelize-auto -h 127.0.0.1 -d db_test -u root -x 123456 -p 3306 -t tbl_user -l es6
    

    可以在 package.json 增加一个快捷的脚本命令

      "scripts": {
        "db2model":"sequelize-auto -h 127.0.0.1 -d db_test -u root -x 123456 -p 3306  --dialect mysql",
        "dev": "egg-bin dev"
      },
    

    运行从数据库生成模型类的命令

    npm run db2model
    

    配置插件文件(/config/plugin.js)

    'use strict';
    
    /** @type Egg.EggPlugin */
    module.exports = {
      // had enabled by egg
      // 静态资源目录
      static: {
        enable: true,
      },
      // 配置模板引擎插件
      nunjucks: {
        enable: true,
        package: 'egg-view-nunjucks',
      },
      // 配置数据库模型插件
      sequelize: {
        enable: true,
        package: 'egg-sequelize',
      },
    };
    

    配置默认配置文件(/config/config.default.js)

    /* eslint valid-jsdoc: "off" */
    
    'use strict';
    const NmPath=require('path')
    /**
     * @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 + '_1611978775015_4782';
    
      // add your middleware config here
      config.middleware = [];
      // 视图层模板引擎配置内容
      config.view = {
        root:NmPath.join(appInfo.baseDir,'app/view'),
        defaultViewEngine: 'nunjucks',
        defaultExtension: '.html',
      };
      // 模型层数据库连接配置内容
      config.sequelize = {
        dialect: 'mysql',
        host: '127.0.0.1',
        password:'000000',
        port: 3306,
        database: 'db_test',
      };
    
      // add your user config here
      const userConfig = {
        // myAppName: 'egg',
      };
    
      return {
        ...config,
        ...userConfig,
      };
    };
    

    创建新的模型文件(/app/model/TblUserModel.js)

    'use strict';
    
    module.exports = app => {
      const { DataTypes } = app.Sequelize;
    
      const UserModel = app.model.define('tbl_user', {
        id: {
          autoIncrement: true,
          type: DataTypes.INTEGER.UNSIGNED,
          allowNull: false,
          primaryKey: true,
          comment: "主键ID"
        },
        user_name: {
          type: DataTypes.STRING(60),
          allowNull: false,
          comment: "用户账号"
        },
        password: {
          type: DataTypes.STRING(32),
          allowNull: false,
          comment: "用户密码"
        },
        created_at: {
          type: DataTypes.INTEGER.UNSIGNED,
          allowNull: false,
          defaultValue: Math.round(new Date().getTime() / 1000),
          comment: "注册时间"
        },
        status: {
          type: DataTypes.TINYINT.UNSIGNED,
          allowNull: false,
          defaultValue: 1,
          comment: "状态(1=正常,0=禁止)"
        }
      }, { timestamps: true, createdAt: 'created_at', updatedAt: false, freezeTableName: true });
    
      UserModel.findById = async function (id) {
        return await this.findOne({ where: { id: id } })
      }
    
      return UserModel;
    };
    

    修改控制器文件

    'use strict';
    
    const Controller = require('egg').Controller;
    
    class HomeController extends Controller {
      async index() {
        const { ctx } = this;
        // ctx.body = 'hi, egg';
        // 创建记录
        await ctx.model.TblUserModel.create({ user_name: 'test-02', password: '123456' })
        // 读取记录
        const user = await ctx.model.TblUserModel.findByPk(1);
        console.log('==user==', user);
        // 渲染视图文件(admin/home/index)
        await ctx.render('index', { name: user.user_name })
      }
    }
    
    module.exports = HomeController;
    

    运行调试:

    npm run dev
    

    至此,数据库模型配置完成。刷新浏览器,即可看到数据库模型的是否生效

  • 相关阅读:
    leetcode 279. Perfect Squares
    leetcode 546. Remove Boxes
    leetcode 312. Burst Balloons
    leetcode 160. Intersection of Two Linked Lists
    leetcode 55. Jump Game
    剑指offer 滑动窗口的最大值
    剑指offer 剪绳子
    剑指offer 字符流中第一个不重复的字符
    leetcode 673. Number of Longest Increasing Subsequence
    leetcode 75. Sort Colors (荷兰三色旗问题)
  • 原文地址:https://www.cnblogs.com/sochishun/p/14337564.html
Copyright © 2011-2022 走看看