egg + nunjucks + sequelize初始化配置

egg 安装运行

        1、初始化:

                npm init egg --type=simple

                        选择 simple boilerplate

        2、下载依赖包:

                npm install

        3、运行项目:

                npm run dev

egg 配置 nunjucks 模板引擎

        1、npm install egg-views-nunjucks -save

        2、打开目录文件 config / config.default.js ,写入配置

config.view = {
    defaultViewEngine: 'nunjucks'
}

        3、打开目录文件 config / plugins ,写入配置

nunjucks: {
    enable: true,
    package: 'egg-view-nunjucks'
}

        4、目录文件的 app 下新建 view 文件夹,里面放置 html 文件(模板引擎默认去找view文件夹)

egg 安装 sequelize(连接、使用数据库)

        1、下载 egg-sequelize:

                npm install --save egg -sequelize mysql2

        2、在 config / plugin.js 中引入插件

sequelize: {
    enable: true,
    package: 'egg-sequelize'
},

        3、在 config / config.default.js 中配置数据库连接

config.sequelize = {
    dialect: 'mysql', // 数据的类型
    database: 'egg_database', // 数据库名称
    host: 'localhost', // 数据库地址
    port: 3306, // 数据库端口
    username: 'root', // 数据库用户名
    password: '666666', // 数据库密码
    timezone: '+08:00', //时区:北京时间
};
MySQL 数据类型与 sequelize数据类型对应如下
    STRING ==> varchar(255)
    INTEGER ==> int
    DOUBLE ==> double
    DATE ==> datetime
    TEXT ==> text

        4、在 app 中新建 model 文件夹, model 中定义表、创建数据模型

                例如:

momodule.exports = app => {

    const { STRING, INTEGER, DATE } = app.Sequelize
    const User = app.model.define('user', {
        // id默认自动生成,默认自增,默认设为主键

        // 用户名
        username: {
            type: STRING,
            allowNull: false,
        },

        // 密码
        password: {
            type: STRING,
            allowNull: false,
        },

        // 电话
        phone: INTEGER,

        // 邮件
        mail: STRING,

        // 创建时间
        createtime: {
            type: DATE,
            allowNull: false,
        },

        // 更新时间
        updatetime: DATE,
    }) 

    return User

}

        5、添加 app.js 文件,初始化数据库

module.exports = app => {

    // 系统启动时执行这个函数
        // sync() model的方法,会根据 app / model 下的模型创建表
    app.beforeStart(async function () {
        // await app.model.sync({ force: true }) // 开发环境使用,会删除数据
        await app.model.sync({})
    })

}

Egg.js 是一个基于 Node.js 和 Koa 的 Web 框架,它提供了很多便捷的功能和插件,让开发者可以快速地构建 Web 应用程序。TypeScript 则是一种静态类型检查的编程语言,可以帮助我们在编写代码时更早地捕获一些错误,提高代码的可维护性和可读性。MySQL 则是一种常用的关系型数据库,用于存储和管理数据。 在 Egg.js 中使用 TypeScript 和 MySQL,我们可以使用 egg-mysql 插件来连接和操作 MySQL 数据库,并使用 TypeScript 的类型检查来保证代码的正确性。具体步骤如下: 1. 创建 Egg.js 项目 ```bash $ npm i egg-init -g $ egg-init egg-typescript-mysql --type=ts $ cd egg-typescript-mysql $ npm i ``` 2. 安装 egg-mysql 插件 ```bash $ npm i egg-mysql ``` 3. 配置 MySQL 数据库连接 在 `config/config.default.ts` 中添加以下配置: ```typescript config.mysql = { client: { host: 'localhost', port: '3306', user: 'root', password: 'password', database: 'test', }, app: true, agent: false, }; ``` 其中,`host`、`port`、`user`、`password`、`database` 分别为你的 MySQL 数据库连接信息。 4. 创建 Model 在 `app/model` 目录下创建一个新的文件 `user.ts`,用于定义操作用户数据的 Model: ```typescript import { Application } from 'egg'; export default (app: Application) => { const { INTEGER, STRING } = app.Sequelize; const User = app.model.define('user', { id: { type: INTEGER, primaryKey: true, autoIncrement: true, }, name: { type: STRING(50), allowNull: false, }, age: { type: INTEGER, allowNull: false, }, }); return User; }; ``` 其中,`app.Sequelize` 是通过 egg-sequelize 插件提供的 Sequelize 实例。 5. 创建 Controller 和 Service 在 `app/controller` 目录下创建一个新的文件 `user.ts`,用于处理用户相关的请求: ```typescript import { Controller } from 'egg'; export default class UserController extends Controller { async index() { const { ctx } = this; const users = await ctx.service.user.list(); ctx.body = { users }; } async show() { const { ctx } = this; const user = await ctx.service.user.get(ctx.params.id); ctx.body = { user }; } async create() { const { ctx } = this; const { name, age } = ctx.request.body; const user = await ctx.service.user.create(name, age); ctx.body = { user }; } async update() { const { ctx } = this; const { id, name, age } = ctx.request.body; const user = await ctx.service.user.update(id, name, age); ctx.body = { user }; } async destroy() { const { ctx } = this; const user = await ctx.service.user.delete(ctx.params.id); ctx.body = { user }; } } ``` 在 `app/service` 目录下创建一个新的文件 `user.ts`,用于实现对用户数据的操作: ```typescript import { Service } from 'egg'; export default class UserService extends Service { async list() { const { ctx } = this; const users = await ctx.model.User.findAll(); return users; } async get(id: number) { const { ctx } = this; const user = await ctx.model.User.findByPk(id); return user; } async create(name: string, age: number) { const { ctx } = this; const user = await ctx.model.User.create({ name, age }); return user; } async update(id: number, name: string, age: number) { const { ctx } = this; const user = await ctx.model.User.findByPk(id); if (!user) { ctx.throw(404, 'user not found'); } await user.update({ name, age }); return user; } async delete(id: number) { const { ctx } = this; const user = await ctx.model.User.findByPk(id); if (!user) { ctx.throw(404, 'user not found'); } await user.destroy(); return user; } } ``` 6. 路由配置 在 `app/router.ts` 中配置路由: ```typescript import { Application } from 'egg'; export default (app: Application) => { const { controller, router } = app; router.get('/users', controller.user.index); router.get('/users/:id', controller.user.show); router.post('/users', controller.user.create); router.put('/users', controller.user.update); router.delete('/users/:id', controller.user.destroy); }; ``` 7. 启动应用 ```bash $ npm run dev ``` 以上就是使用 Egg.js、TypeScript 和 MySQL 开发 Web 应用程序的基本步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值