eggjs&sequelize使用教程一(环境搭建)

前言

原来想写express+sequelize的,但是公司现在放弃了express,转战eggjs,所以这个的教程就以egg为基础

安装egg

官方有完整的教程

需要安装的模块 package.js

zengwe@zengwe-PC:egg-example$ cat package.json 
{
  "name": "example",
  "version": "1.0.0",
  "description": "",
  "private": true,
  "dependencies": {
    "egg": "^1.9.0",
    "egg-scripts": "^2.1.0",
    "egg-sequelize": "^3.1.0",
    "mysql2": "^1.5.0"
  },
  "devDependencies": {
    "autod": "^2.10.0",
    "autod-egg": "^1.0.0",
    "egg-bin": "^4.3.5",
    "egg-ci": "^1.8.0",
    "egg-mock": "^3.13.0",
    "eslint": "^4.10.0",
    "eslint-config-egg": "^5.1.0",
    "webstorm-disable-index": "^1.2.0"
  },
  "engines": {
    "node": ">=8.9.0"
  },
  "scripts": {
    "start": "egg-scripts start --daemon",
    "stop": "egg-scripts stop",
    "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": "8"
  },
  "repository": {
    "type": "git",
    "url": ""
  },
  "author": "",
  "license": "MIT"
}

整体的结构目录

zengwe@zengwe-PC:egg-example$ tree ./ -I node_modules
./
├── app
│   ├── controller
│   │   └── home.js
│   ├── model
│   │   └── movie.js
│   ├── public
│   ├── router.js
│   └── service
│       └── test.js
├── appveyor.yml
├── config
│   ├── config.default.js
│   └── plugin.js
├── logs
│   └── example
│       ├── common-error.log
│       ├── egg-agent.log
│       ├── egg-web.log
│       └── example-web.log
├── package.json
├── package-lock.json
├── README.md
├── README.zh-CN.md
├── run
│   ├── agent_config.json
│   ├── agent_config_meta.json
│   ├── application_config.json
│   └── application_config_meta.json
└── test
    └── app
        └── controller
            └── home.test.js

配置sequelize

我在config目录下新建一个config.sequelize.js的文件用来放sequelize的配置,因为这个配置文件可能会有很多内容,包括sequelize全局钩子函数或者读写分离等等,所以单独分出一个文件,配置如下

'use strict';
const equelize = {
  dialect: 'mysql', // support: mysql, mariadb, postgres, mssql
  database: 'douban_test',
  host: 'localhost',
  port: '3306',
  username: 'root',
  password: '123456',
};
module.exports = equelize;

在config.default.js中引入

'use strict';
const sequelizeConfig = require('./config.sequelize');
module.exports = appInfo => {
  const config = exports = {};
  // use for cookie sign key, should change to your own and keep security
  config.keys = appInfo.name + '_1510991679580_9861';
  // add your config here
  config.middleware = [];
  config.sequelize = sequelizeConfig;
  return config;
};

启用sequelize模块

在config文件下的plugin.js中添加这个模块

'use strict';

// had enabled by egg
// exports.static = true;
exports.sequelize = {
  enable: true,
  package: 'egg-sequelize',
};
exports.security = {
  enable: false,
};

ps:这里关闭security的原因是不用每次动态的添加token,开发阶段很麻烦

在app的目录下建一个model的文件并建一个model

'use strict';
module.exports = app => {
  const { INTEGER, STRING } = app.Sequelize;
  const Movie = app.model.define('Movie', {
    id: {
      type: INTEGER,
      autoIncrement: true,
      primaryKey: true,
    },
    name: {
      type: STRING(100),
      allowNull: false,
    },
  }, {
    freezeTableName: true,
    tableName: 'z_movie',
    timestamps: false,
  });
  return Movie;
};

在homeController中试一次

'use strict';

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

class HomeController extends Controller {
  * index() {
    const serviceRes = yield this.ctx.service.test.index();
    const result = yield this.app.model.Movie.findAll();
    console.log(result);
    this.ctx.body = 'hi, egg' + serviceRes;
  }
}

module.exports = HomeController;

上面是现在的controller的写法原来的是

module.exports = app => {
    return class HomeController extends app.Controller {
      * index() {
            const result = yield app.model.Movie.findAll();
            console.log(result);
            this.ctx.body = 'hi, egg' + serviceRes;
      }
}

module.exports = HomeController;

运行

npm run dev

zengwe@zengwe-PC:egg-example$ npm run dev

> example@1.0.0 dev /media/zengwe/Bcode/egg/douban/egg-example
> egg-bin dev

2017-11-19 23:14:54,132 INFO 12666 [master] egg version 1.11.0
sequelize deprecated String based operators are now deprecated. Please use Symbol based operators for better security, read more at http://docs.sequelizejs.com/manual/tutorial/querying.html#operators node_modules/sequelize/lib/sequelize.js:236:13
2017-11-19 23:14:57,327 INFO 12672 [model] SELECT VERSION() as `version` (7ms)
2017-11-19 23:14:57,354 INFO 12672 [model] SELECT 1+1 AS result (3ms)
2017-11-19 23:14:57,371 INFO 12666 [master] agent_worker#1:12672 started (3227ms)

bingo成功

访问 http://127.0.0.1:7001

2017-11-19 23:18:28,744 INFO 12683 [model] SELECT `id`, `name` FROM `z_movie` AS `Movie`; (2ms)
[ Movie {
    dataValues: { id: 1, name: '无间道' },
    _previousDataValues: { id: 1, name: '无间道' },
    _changed: {},
    _modelOptions: 
     { timestamps: false,
       validate: {},
       freezeTableName: true,
       underscored: true,
       underscoredAll: false,
       paranoid: false,
       rejectOnEmpty: false,
       whereCollection: null,
       schema: null,
       schemaDelimiter: '',
       defaultScope: {},
       scopes: [],
       hooks: {},
       indexes: [],
       name: [Object],
       omitNull: false,
       tableName: 'z_movie',
       sequelize: [Object],
       uniqueKeys: {} },
    _options: 
     { isNewRecord: false,
       _schema: null,
       _schemaDelimiter: '',
       raw: true,
       attributes: [Object] },
    __eagerlyLoadedAssociations: [],
    isNewRecord: false } ]

bingo成功

你可能感兴趣的:(后端框架)