1. 程式人生 > >egg-sequelize --- nodejs

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;
}

 

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))
        })

    }
}

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 或者 其他測試軟體自己跑一下...