Egg builds the back-end management server
Fast initialization
mkdir egg-example && cd egg-example
npm init egg --type=simple
yarn
Copy the code
Launch project:
yarn dev
open http://localhost:7001
Copy the code
The installationSequelize
1- Install the corresponding plug-in:
yarn add egg-sequelize mysql2
Copy the code
2- Enable plug-ins:
// config/plugin.js module.exports = {// had enabled by egg static: {enable: true}, // database sequelize: {enable: true, package: "egg-sequelize" } };Copy the code
3- Write the sequelize configuration in config/config.default.js
Sequelize = {dialect: "mysql", // mysql host: "127.0.0.1", // database address: port: 3306, // database port number database: "egg-sequelize", // database name username: "root", // username password: Timezone: "+08:00", define: {freezeTableName: true // Force table name equal model name}}Copy the code
Install sequelize – cli
yarn add sequelize-cli --dev
Copy the code
In the Egg project, we want to put all migrations-related content in the Database directory, so we create a new.Sequelizerc configuration file in the project root directory:
'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'),
};
Copy the code
Initializes Migrations configuration files and directories
npx sequelize init:config
npx sequelize init:migrations
Copy the code
Json file and database/migrations directory will be generated after execution. We will modify the contents of database/config.json to the database configuration used in our project:
{ "development": { "username": "root", "password": null, "database": "database_development", "host": "127.0.0.1" and "the dialect", "mysql"}, "test" : {" username ":" root ", "password", null, "database" : "database_test", "the host" : "127.0.0.1", "dialect": "mysql"}, "production": {"username": "root", "password": null, "database": "Database_production", "the host" : "127.0.0.1", "the dialect" : "mysql"}}Copy the code
With sequelize-CLI and associated configuration initialized, we can start writing the project’s first Migration file to create one of our Users tables.
支那
npx sequelize migration:generate --name=init-users
Copy the code
The migration file (${timestamp}-init-users.js) is generated in the database/migrations directory, and we modify it to handle initializing the Users table:
支那
'use strict'; Module.exports = {// creates the users table up when performing database upgrade: async (queryInterface, Sequelize) => { const { INTEGER, DATE, STRING } = Sequelize; await queryInterface.createTable('users', { id: { type: INTEGER, primaryKey: true, autoIncrement: true }, name: STRING(30), age: INTEGER, created_at: DATE, updated_at: DATE, }); }, // Drop the users table down: async queryInterface => {await queryInterface. DropTable ('users'); }};Copy the code
Execute migrate to change the database
支那
# migrate # sequelize db:migrate You can use 'db:migrate:undo' to roll back a change # NPX sequelize db:migrate:undo # NPX sequelize db:migrate:undo:all 'to roll back a change # NPX sequelize db:migrate:undo:allCopy the code
After execution, our database initialization is complete.
Write the code
Now we are ready to write the code to implement the business logic. First, we will write the user model in app/model/ :
支那
'use strict';
module.exports = app => {
const { STRING, INTEGER, DATE } = app.Sequelize;
const User = app.model.define('user', {
id: { type: INTEGER, primaryKey: true, autoIncrement: true },
name: STRING(30),
age: INTEGER,
created_at: DATE,
updated_at: DATE,
});
return User;
};
Copy the code
This Model can be accessed in Controller and Service via app.model.User or ctx.model.User. For example, we write app/ Controller /users.js:
支那
// app/controller/users.js const Controller = require('egg').Controller; function toInt(str) { if (typeof str === 'number') return str; if (! str) return str; return parseInt(str, 10) || 0; } class UserController extends Controller { async index() { const ctx = this.ctx; const query = { limit: toInt(ctx.query.limit), offset: toInt(ctx.query.offset) }; ctx.body = await ctx.model.User.findAll(query); } async show() { const ctx = this.ctx; ctx.body = await ctx.model.User.findByPk(toInt(ctx.params.id)); } async create() { const ctx = this.ctx; const { name, age } = ctx.request.body; const user = await ctx.model.User.create({ name, age }); ctx.status = 201; ctx.body = user; } async update() { const ctx = this.ctx; const id = toInt(ctx.params.id); const user = await ctx.model.User.findByPk(id); if (! user) { ctx.status = 404; return; } const { name, age } = ctx.request.body; await user.update({ name, age }); ctx.body = user; } async destroy() { const ctx = this.ctx; const id = toInt(ctx.params.id); const user = await ctx.model.User.findByPk(id); if (! user) { ctx.status = 404; return; } await user.destroy(); ctx.status = 200; } } module.exports = UserController;Copy the code
Finally we mount the controller to the route:
支那
// app/router.js
module.exports = app => {
const { router, controller } = app;
router.resources('users', '/users', controller.users);
};
Copy the code
Automatically generate model files
yarn add egg-sequelize-auto --dev
Add the command to generate models from the database in the package.json script (-o for path to generate Models, -h for host, -p for port, -d for database, -u for username, -x for password)
支那
"scripts": {
"dbload": "egg-sequelize-auto -o ./app/model -h localhost -p 3306 -d database -u username -x password"
}
Copy the code