[AdonisJS]Node.js back-end development framework - using ORM function and connecting to MySQL database

Posted by sebajom on Wed, 05 Jan 2022 12:17:34 +0100

The versions of the framework involved in this article are as follows:
1,Node.js:8.1.2
2,Vue.js:2.0
3,AdonisJS: AdonisJS 5
Official website: https://docs.adonisjs.com/guides/models/introduction

1, ORM

Lucid's data model layer makes it easy to perform CRUD operations, manage relationships between models, and define hook functions for the life cycle

1. Create Model

First, cmd enters the root directory of the project and enters the command node ace make:model User to create app / Models / user ts; If node ace make:model User -m is used, database / migrations / 1618903673925 will be created_ users. TS is used as a script to create a database.

2. Then write the database entity class

The code is as follows:

Click to view the code
import { DateTime } from 'luxon'
import { v4 as uuidv4 } from 'uuid';

import { beforeSave,beforeCreate,BaseModel, column } from '@ioc:Adonis/Lucid/Orm'
import Hash from '@ioc:Adonis/Core/Hash'


export default class User extends BaseModel {
  @column({ isPrimary: true })
  public id: string

  @column()
  public nickName: string

  @column()
  public phone: string

  @column({ serializeAs: null })
  public pass: string
  public token :string
  @column()
  public address: string | null

@beforeSave()
  public static async hashPassword(user: User) {
    if (user.$dirty.pass) {
      user.pass = await Hash.make(user.pass)
    }
     if (user.id == null || user.id ==undefined){
       user.id = uuidv4();
     }
     
  }


  @beforeCreate()
    public static assignUuid(user: User) {
      user.id = uuidv4();
    }

 // @column.dateTime({ autoCreate: true})
 //  public updatedAt: DateTime



}

1. @ Column: used to decorate the Column of the database. If there is no decoration, it will not be serialized into the result. Any options defined in the model will not change / affect the database.
2. isPrimary: used to identify whether it is a primary key
3. serializeAs: used to control whether to serialize
4. @ beforeCreate(), @ beforeSave(): hook function. It performs some operations before instantiating and saving to the database. I use it to generate id and encryption password (installation related packages are required)
5,@column. Datetime ({autocreate: true, AutoUpdate: true}): date. The parameter is whether to generate and update automatically

3. Install the package of Hash and uuid

(1) npm i Hash
(2) npm i uuid
Then import the package import {V4 as uuidv4} from 'UUID';, import Hash from '@ioc:Adonis/Core/Hash';
Use the following:

Click to view the code
 user.id = uuidv4();
 user.pass = await Hash.make(user.pass)
	

4. Add, delete, modify query

These codes are written in the data ORM layer you want to write. For simplicity, I write them in the Controller layer irregularly, APP / Controllers / HTTP / usercontroller Write under TS

(1)create

Click to view the code
// demo1
import User from 'App/Models/User'
const user = new User()
user.username = 'virk'
user.email = 'virk@adonisjs.com'
await user.save()
	
	
// demo2
import User from 'App/Models/User'

const user = await User.create({
  username: 'virk',
  email: 'virk@adonisjs.com',
})

// demo3
const user = await User.createMany([
  {
    email: 'virk@adonisjs.com',
    password: 'secret',
  },
  {
    email: 'romain@adonisjs.com',
    password: 'secret',
  },
])

(2)read Click to view the code
// demo1
const user = await User.all()
// SQL: SELECT * from "users" ORDER BY "id" DESC;
	
// demo2
const user = await User.find(1)
// SQL: SELECT * from "users" WHERE "id" = 1 LIMIT 1;

// demo3
const user = await User.findBy('email', 'virk@adonisjs.com')
// SQL: SELECT * from "users" WHERE "email" = 'virk@adonisjs.com' LIMIT 1;

// demo4
const user = await User.first()
// SQL: SELECT * from "users" LIMIT 1;

// demo5
const users = await User
  .query()
  .where('country_code', 'IN')
  .orWhereNull('country_code')

	
// demo6
const users = await User
  .query()
  .where('country_code', 'IN')
  .orWhereNull('country_code')
  .first()

(3)update Click to view the code
// demo1
const user = await User.findOrFail(1)
user.last_login_at = DateTime.local() 
await user.save()

// demo2
await user
  .merge({ last_login_at: DateTime.local() })
  .save()

// demo3
await User
  .query()
  .where('id', 1)
  .update({ last_login_at: new Date() })

	
(4)delete Click to view the code
// demo1
const user = await User.findOrFail(1)
await user.delete()

// demo2
await User.query().where('is_verified', false).delete()

A special issue of joint table query will be issued later. You are welcome to pay attention to learning

2, Install and configure MySQL driver

1. Install the drive

Enter the project root directory and execute the command:
(1)npm i @adonisjs/lucid
(2)node ace configure @adonisjs/lucid

Then move the cursor from the keypad, select the corresponding database, press the spacebar, and enter

Then select the document viewing method, select the first browser, and press enter
Configure according to the document, first in Env Env. Under TS file Add dB in rules_ CONNECTION: Env. schema. String (),, and the following
MYSQL_HOST: Env.schema.string({ format: 'host' }), MYSQL_PORT: Env.schema.number(), MYSQL_USER: Env.schema.string(), MYSQL_PASSWORD: Env.schema.string.optional(), MYSQL_DB_NAME: Env.schema.string(),
As follows:

Then in config / database Check whether there are the following under ts, if not, it needs to be supplemented

Finally, in the project root directory Fill in the information related to database connection under env file, as follows

3, Test effect

At start / routes Write a simple interface under the TS file. The code is as follows:

Click to view the code
import Database from '@ioc:Adonis/Lucid/Database'
import User from 'App/Models/User'
	
Route.get('/1', async () => {

  return User.all()
  // Or use database queries
  // return Database.from("users")
})
The effects are as follows: