eggjs项目初始化

0次阅读

共计 2747 个字符,预计需要花费 7 分钟才能阅读完成。

创立我的项目和根底配置

全局配置 npm 源

npm config set registry https://registry,npm.taobao.org

egg.js 初始化

mkdir egg-example && cd egg-example
npm init egg --type=simple --registry https://registry.npm.taobao.org
npm install

启动我的项目

npm run dev

敞开 csrf 开启跨域

// 装置扩大
npm i egg-cors --save

// 启用 egg-cors 插件 /config/plugin.js
cors:{
  enable: true,
  package: 'egg-cors',
},

// 参数配置 config / config.default.js
config.security = {
    // 敞开 csrf
    csrf: {enable: false,},
    // 跨域白名单
    domainWhiteList: ['http://localhost:3000'],
};

// 容许跨域的办法
config.cors = {
    origin: '*',
    allowMethods: 'GET, PUT, POST, DELETE, PATCH'
};

全局异样中间件

中间件 app/middleware/error_handler.js

module.exports = (option, app) => {return async function errorHandler(ctx, next) {
      try {await next(); 
        // 404 解决
        if(ctx.status === 404 && !ctx.body){
           ctx.body = { 
               msg:"fail",
               data:'Not Find'
           };
        }
      } catch (err) {
        const status = err.status || 500;
        // 生产环境时 500 谬误的具体谬误内容不返回给客户端,因为可能蕴含敏感信息
        const error = status === 500 && app.config.env === 'prod'? 'Internal Server Error': err.message;
        ctx.body = { 
            msg:"fail",
            data:error
        };
        ctx.status = status;
      }
    };
  };

注册到全局配置中 config/config.default.js

config.middleware = ['errorHandler'];

接口返回值封装

// app\extend\context.js
module.exports = {success(data = '', msg ='ok', code = 200) {
        this.status = code
        this.body = {
            msg,
            data
        }
    },
    error(data = '', msg ='fail', code = 400) {
        this.status = code;
        this.body = {
            msg,
            data
        }
    }
};

数据库 sequelize

装置配置

// 装置必要的扩大
npm install --save egg-sequelize mysql2

// 启动扩大 config/plugin.js
exports.sequelize = {
  enable: true,
  package: 'egg-sequelize',
};

// 配置 sequelize 扩大 config/config.default.js
config.sequelize = {
    dialect:  'mysql',
    host:  '127.0.0.1',
    username: 'root',
    password:  '123456',
    port:  3306,
    database:  'database_development',
    // 中国时区
    timezone:  '+08:00',
    define: {
        // 勾销数据表名复数
        freezeTableName: true,
        // 主动写入工夫戳 created_at updated_at
        timestamps: true,
        // 字段生成软删除工夫戳 deleted_at
        // paranoid: true,
        createdAt: 'created_at',
        updatedAt: 'updated_at',
        // deletedAt: 'deleted_at',
        // 所有驼峰命名格式化
        underscored: true
    }
};

数据迁徙

// 装置扩大
npm install --save-dev sequelize-cli

// 配置文件 .sequelizerc
'use strict';
const path = require('path');
module.exports = {config: path.join(__dirname, 'database/config.json'),
  'migrations-path': path.join(__dirname, 'database/migrations'),
  'seeders-path': path.join(__dirname, 'database/seeders'),
  'models-path': path.join(__dirname, 'app/model'),
};

// 初始化 Migrations 配置文件和目录
npx sequelize init:config
npx sequelize init:migrations
// npx sequelize init:models

// 创立数据库
npx sequelize db:create

// 降级数据库
npx sequelize db:migrate
// 如果有问题须要回滚,能够通过 `db:migrate:undo` 回退一个变更
npx sequelize db:migrate:undo
// 能够通过 `db:migrate:undo:all` 回退到初始状态
npx sequelize db:migrate:undo:all

模型关联

User.associate = function(models) {
   // 关联用户材料 一对一
   User.hasOne(app.model.Userinfo);
   // 反向一对一关联
   // Userinfo.belongsTo(app.model.User);
   // 一对多关联
   User.hasMany(app.model.Post);
   // 反向一对多关联
   // Post.belongsTo(app.model.User);
   // 多对多
   // User.belongsToMany(Project, { as: 'Tasks', through: 'worker_tasks', foreignKey: 'userId'})
   // 反向多对多
   // Project.belongsToMany(User, { as: 'Workers', through: 'worker_tasks', foreignKey: 'projectId'})
}
正文完
 0