egg-sequelize --- nodejs


項目

egg + sequelize + mysql2


 

 

項目結構

 

配置


 

 

安裝模塊

npm install --save egg-sequelize

npm install --save egg-cors

npm install --save mysql2

 

config/pulgin.js

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

 

config/config.default.js

   //mysql配置開始
   config.sequelize = {
    dialect: 'mysql', // support: mysql, mariadb, postgres, mssql
    dialectOptions: {
      charset: 'utf8mb4',
    },
    database: 'nodejs',
    host: 'localhost',
    port: '3306',
    username: 'root',
    password: 'root',
    timezone: '+08:00',
  };
  //mysql配置結束
  //cors配置開始
  config.security = {
    csrf: {
      enable: false,
    },
    domainWhiteList: [ 'http://localhost:8080' ],
  };
  config.cors = {
    credentials: true,
  };
  //cors配置結束

 

數據建模


 

mysql 建表

CREATE TABLE `collect` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '收藏id',
  `author` varchar(255) DEFAULT NULL COMMENT '作者',
  `date` varchar(255) DEFAULT NULL COMMENT '日期',
  `link` varchar(255) DEFAULT NULL COMMENT '鏈接',
  `title` varchar(255) DEFAULT NULL COMMENT '標題',
  `created_at` datetime DEFAULT NULL COMMENT '創建時間',
  `updated_at` datetime DEFAULT NULL COMMENT '更改時間',
  PRIMARY KEY (`id`),
  UNIQUE KEY `title` (`title`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='收藏表';

 

model/collect.js

'use strict';
module.exports = app => {
    const {
        INTEGER,
        STRING,
        DATE
    } = app.Sequelize;
    const Collect = app.model.define('collect',{
        id:{
            type:INTEGER,
            primaryKey:true,
            autoIncrement:true
        },
        author:STRING,
        date:STRING,
        link:STRING,
        title:STRING,
        created_at:DATE,
        updated_at:DATE
    },{
        freezeTableName: true, //使用默認表名,不會變以collects
    })
    return Collect;
}

 

選配)啟動時創建數據庫表

// {work_dir}/app.js
module.exports = app => {
    app.beforeStart(async function () {
        await app.model.sync({ force: true });
    });
};

 

 

service


 

 

service/collect.js

 

'use strict';

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

class CollectService extends Service {

    // 查詢所有數據
    async findAll() {
        let ret = await this.ctx.model.Collect.findAll()

        console.log(ret)
        return ret
    }

    // 增加數據
    async create(data) {
        await this.ctx.model.Collect.create(data)
        .then(res => {
            console.log('res: '+ JSON.stringify(res))
        }).catch(err => {
            console.log('err: '+ JSON.stringify(err))
        })

        // try{  
        //     let a= await this.ctx.model.Collect.create(data)
        //     console.log(a)
        // }catch(err){
        //     console.log(err)
        // }
    }

    // 修改數據
    async update() {
        const ret = await this.ctx.model.Collect.update({
            author: '新作者'
        }, {
            where: {
                id: 2
            }
        }).then(ok => {
            console.log('ok')
            console.log(ok)
        }).catch(e => {
            console.log('message:' + e)
        })
    }

    // 刪除數據
    async delete(callback){
        await this.ctx.model.Collect.destroy({
            where: {
                id: 20
            }
        }).then(res => {
            console.log('res:' + JSON.stringify(res))
            return callback(JSON.stringify(res))
        })

    }


    // 自定義查詢
    async query(callback){
        let sql = 'SELECT COUNT(1) FROM collect'
        let ret = await this.ctx.model.query(sql, {type: 'SELECT'})
        return ret
    }
}

module.exports = CollectService;

 

 

 

 

controller


 

 

controller/collect.js

'use strict';

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

class CollectController extends Controller {
    async findAll(){
        const {ctx} = this;
        ctx.body = await ctx.service.collect.findAll()
    }

    async create(){
        const ctx = this.ctx
        const body = ctx.request.body

        const ret = await ctx.service.collect.create(body)

        ctx.body = '<h1>添加數據</h1>'
    }

    async update() {
         await this.ctx.service.collect.update()
        this.ctx.body = '<h1>修改數據</h1>'
    }

    async delete() {
        await this.ctx.service.collect.delete(function(res, err) {
            console.log('ret: ' + res)
        })
        console.log('哈哈哈哈')
        this.ctx.body = '<h1>刪除數據</h1>'
    }
}

module.exports = CollectController;

 

 

router.js


 

 

  router.get('/collect',controller.collect.findAll)
  router.post('/create', controller.collect.create)
  router.get('/update', controller.collect.update)
  router.get('/delete', controller.collect.delete)

 

 

接下來,用postman 或者 其他測試軟件自己跑一下...

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM