Introduction to the
The reason for using EggJS goes without saying. Front-end developers want to work on server interfaces and the lowest learning cost is NodeJS. In addition, KOA is a wrapper library for NodeJS, which makes nodeJS easier to use. However, under the premise that eggJS convention is greater than configuration, KOA is encapsulated, which makes the cost of getting started lower. Of course, EGGJS is chosen as the framework of the write interface. The reason for using sequelize in databases goes without saying, making it easier for multiple developers to collaborate!!
Eggjs is quick to get started
Generating project
To quickly generate basic projects to improve development efficiency, scaffolding is recommended to quickly generate projects. Specific commands are as follows:
Mkdir egg-example && CD egg-example NPM init egg --type=simple NPM I NPM run devCopy the code
Project Catalog Introduction
An egg - project ├ ─ ─ package. Json ├ ─ ─ app. Js (optional) ├ ─ ─ agent. The js (optional) ├ ─ ─ app | ├ ─ ─ the router. The js │ ├ ─ ─ controller │ | └ ─ ─ home. Js │ │ ├ ─ ─ service (optional) | └ ─ ─ the user. The js │ ├ ─ ─ middleware (optional) │ | └ ─ ─ response_time. Js │ ├ ─ ─ the schedule (optional) │ | └ ─ ─ my_task. Js │ │ ├ ─ ─ public (optional) | └ ─ ─ reset. CSS │ ├ ─ ─ the view (optional) │ | └ ─ ─ home. TPL │ └ ─ ─ the extend (optional) │ ├ ─ ─ helper. Js (optional) │ ├ ─ ─ Request. Js (optional) │ ├ ─ ─ the response. The js (optional) │ ├ ─ ─ the context, js (optional) │ ├ ─ ─ application. Js (optional) │ └ ─ ─ agent. The js (optional) ├ ─ ─ the config | ├ ─ ─ plugin. Js | ├ ─ ─ config. The default. The js │ ├ ─ ─ config. Prod. Js | ├ ─ ─ config. The test. The js (optional) | ├ ─ ─ config. Local, js (optional) | └ ─ ─ Config. Unittest. Js (optional) └ ─ ─ the test ├ ─ ─ middleware | └ ─ ─ response_time. Test. The js └ ─ ─ controller └ ─ ─ home. Test. JsCopy the code
As above, the directory agreed by the framework:
app/router.js
This parameter is used to configure URL routing rules. For details, seeRouter.app/controller/**
Parses user input and returns the corresponding result. For details, seeController.app/service/**
Write the business logic layer. This layer is optional and recommended. For details, seeService.app/middleware/**
For writing middleware, see optionalMiddleware.app/public/**
Used to place static resources, optionally, see built-in plug-insegg-static.app/extend/**
An optional extension to the framework, seeFramework extension.config/config.{env}.js
For details about how to write configuration files, seeconfiguration.config/plugin.js
Used to configure plug-ins to be loaded. For details, seeThe plug-in.test/**
For unit testing, seeUnit testing.app.js
和agent.js
This parameter is used to customize initialization at startup. For details, seeEnabling Customization. aboutagent.js
See Synonyms atThe Agent mechanism.
Directories agreed by the built-in plug-in:
app/public/**
Used to place static resources, optionally, see built-in plug-insegg-static.app/schedule/**
This parameter is optional for scheduled tasks. For details, seeTiming task.
To customize your own directory specifications, seeLoader API
app/view/**
This is used to place template files, as specified by the template plug-in, for detailsTemplate rendering.app/model/**
Used to place domain models, optionally, by domain class-related plug-in conventions, such asegg-sequelize.
A basic project has been created. Details of how eggJS is used can be found in the official documentation eggjs.org/zh-cn/
Use eggjs sequelize
- Install and configure the egg-Sequelize plugin (which will assist us in loading defined Model objects into app and CTX) and mysql2 modules:
- The installation
npm install --save egg-sequelize mysql2
Copy the code
- in
config/plugin.js
To introduce the egg-Sequelize plug-in
exports.sequelize = {
enable: true,
package: 'egg-sequelize',
};
Copy the code
- in
config/config.default.js
To write the Sequelize configuration
Config. sequelize = {dialect: 'mysql', host: '127.0.0.1', port: 3306, database: 'egg-sequelize-doc-default',};Copy the code
We can configure different data sources in different environment configuration address, used to distinguish between different environment using the database, for example, we can create a new config/config. The unittest. Js configuration file, write the following configuration, Point the database connected in single test to egg-sequelize-doc-unittest.
Exports. sequelize = {dialect: 'mysql', host: '127.0.0.1', port: 3306, database: 'egg-sequelize-doc-unittest',};Copy the code
Once the above configuration is complete, a project using Sequelize is initialized. Egg-sequelize and Sequelize also support additional configuration items, which can be found in their documentation.
- Sequelize provides the sequelize-CLI tool for management, and we can also introduce sequelize-CLI in egg projects.
- Install sequelize – cli
npm install --save-dev sequelize-cli
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
Then view all the sequelize -CLI commands
Sequelize < command > Command: sequelize db:migrate Run pending migrations sequelize db:migrate:schema:timestamps:add Update migration table to have timestamps sequelize db:migrate:status List the status of all migrations sequelize db:migrate:undo Reverts a migration sequelize db:migrate:undo:all Revert all migrations ran sequelize db:seed Run specified seeder sequelize db:seed:undo Deletes data from the database sequelize db:seed:all Run every seeder sequelize db:seed:undo:all Deletes data from the database sequelize db:create Create database specified by configuration sequelize db:drop Drop database specified by configuration sequelize init Initializes project sequelize init:config Initializes configuration sequelize init:migrations Initializes migrations sequelize init:models Initializes models sequelize init:seeders Initializes seeders sequelize migration:generate Generates a new migration file [aliases: migration:create] sequelize model:generate Generates a model and its migration [aliases: model:create] sequelize seed:generate Generates a new seed file [aliases: seed:create]Copy the code
The following is a brief introduction to the way of use
Use commands to operate the database
- Initialize the database
npx sequelize init
Copy the code
This will create the following folders:
- Config, which contains the configuration file that tells the CLI how to connect to the database
- Models, which contains all the models for your project
- Migrations, which contains all migrated files
- Seeders, which contains all the seed files
Before building the model, modify the database/config.json to tell the CLI how to connect to the database. The database/config.json content is as follows:
{" development ": {" username" : "root", "password" : "12345678", "database" : "egg_test", "the host" : "127.0.0.1", "the dialect" : "mysql" }, "test": { "username": "root", "password": "23456789", "database": "database_test", "host": "127.0.0.1", "dialect": "mysql"}, "production": {"username": "root", "password": "12345679", "database": "Database_production", "the host" : "127.0.0.1", "the dialect" : "mysql"}}Copy the code
- Use the following command to create the database:
npx sequelize db:create
Copy the code
- Use the following command to delete the database:
npx sequelize db:drop
Copy the code
Create the model
We will use the model:generate command. This command requires two options:
- Name, the name of the model
- Attributes, a list of attributes for the model
Create a model named User:
npx sequelize model:generate --name User --attributes firstName:string,lastName:string,email:string
Copy the code
This will create the following file:
- A User model file is created in the Models folder
- A migration file with a name like XXXXXXXXxxxx-create-user.js was created in the migrations folder
Note: _Sequelize will only use the model file, which is the table description. On the other hand, migrating files are changes to the model, or more specifically the tables used by the CLI. Handles migrations, such as commits or logging, to make certain changes to the database.
I think it’s a little bit cumbersome to create a model using commands like this, mainly because if there are too many fields, the command line will have to write a lot. I don’t know of any other good way to do this.
I created the Migrations file first and then created the model file manually. Specific as follows
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
NPX 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.
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
You can then combine the EGGJS schema for database processing.
Tell me the CLI commands you can use
NPX sequelize db: Migrate :statusCopy the code
Revocation of the migration
Db :migrate:undo – Undoes the last migration
Db :migrate:undo:all – Deletes all migration operations
Db :migrate:undo –name Migration script
We will now add a field lastName and create a new migration file
npx sequelize migration:create --name addLastname
Copy the code
QueryInterface document: sequelize.org/master/clas…
Seed file
Seed file
Migration files are used to build databases and table structures, while seed files are used to build data
Seed :generate –name demo-user
The seed script is similar to the migration script in that it consists of up and down functions and the parameters passed in are the same
The seed file name is followed by a custom name
npx sequelize seed:generate --name userseed
Copy the code
A seed file ending in userseed is created under Database/SEEDers and then manually modified to add point test data
module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.bulkInsert('users', [{ id: 1, name: 'man', age: 18, }], {}); }, down: (queryInterface, Sequelize) => { return queryInterface.bulkDelete('users', null, {}); }};Copy the code
Perform the seed
Db :seed Specifies the seed file to run the specified seed file
Db :seed:all Runs all seed files
npx sequelize db:seed:all
Copy the code
Then look at the database and add a piece of data
Undo seed execution
Db :seed:undo –seed specifies the seed file to undo the specified seed file
Db :seed:undo:all Undoes all seed files
npx sequelize db:seed:undo:all
Copy the code
Please check the official document for details
summary
The initial use of eggJS if wrong welcome to comment, feel useful old iron welcome to give a thumbs up!!