Thứ Ba, 13 tháng 4, 2021

Seeds và Factories trong AdonisJS




## Seeds
1. Tạo mới file Seeds
> adonis make:seed User

2. Chạy tất cả các file seed
> adonis seed

Cần kết hợp với Factory để mở rộng tính năng

3. Chỉ chạy 1 file seed
> Ex: adonis seed --files UserSeeder.js --force


## Factories
Tạo nhanh dữ liệu test cho các bảng.

Ở file database/factory.js tạo kết nối với Model User
<!-->
const Factory = use('Factory')
const Hash = use('Hash')

Factory.blueprint('App/Models/User', async (faker) => {
return {
username: faker.username(),
email: faker.email(),
password: await Hash.make(faker.password())
}
})
<-->

==>
Ở file seeds/UserSeeder.js
Thêm vào `const user = await Factory.model('App/Models/User').create()`
để tạo ra 1 user ngẫu nhiên

Tạo nhanh 5 users:
> const usersArray = await Factory.model('App/Models/User').createMany(5)


## Tạo liên kết giữa các bảng
1. Tạo file app/Models/Post.js
<!-->
'use strict'

/** @type {typeof import('@adonisjs/lucid/src/Lucid/Model')} */
const Model = use('Model')

class Post extends Model {
static boot () {
super.boot()
}
}

module.exports = Post
<-->

2. Tạo file migration for Post
> adonis make:migration post
==> Output: 1616983081702_post_schema.js
Chỉnh sửa thêm như bên dưới:
<!-->
'use strict'

/** @type {import('@adonisjs/lucid/src/Schema')} */
const Schema = use('Schema')

class PostSchema extends Schema {
up () {
this.drop('posts')
this.create('posts', (table) => {
table.increments()
table.string('title', 250).notNullable()
table.text('body').notNullable()
table.timestamps(),
table.integer('user_id')
})
}

down () {
this.drop('posts')
}
}

module.exports = PostSchema
<-->

3. Chỉnh sửa file database/factory.js
<!-->
// User blueprint
Factory.blueprint('App/Models/User', (faker) => {
return {
username: faker.username(),
password: faker.password()
}
})

// Post blueprint
Factory.blueprint('App/Models/Post', (faker) => {
return {
title: faker.sentence(),
body: faker.paragraph()
}
})
<-->

4. Chỉnh sửa ở file UserSeeder.js
<!-->
/** @type {import('@adonisjs/lucid/src/Factory')} */
const Factory = use('Factory')

class UserSeeder {
async run () {
// const users = await Database.table('users')
// console.log(users)

// const user = await Factory.model('App/Models/User').create()
// const usersArray = await Factory.model('App/Models/User').createMany(5)

const user = await Factory.model('App/Models/User').create()
const post = await Factory.model('App/Models/Post').make()
await user.posts().save(post)
}
}

module.exports = UserSeeder
<-->

5. Run command chạy tất cả các file seeds
> adonis seed


## Model Factory API
Bên dưới là danh sách các method sẵn có khi sử dụng `Lucid model` factories.

1. `create()`
> await Factory.model('App/Models/User').create()

2. `createMany(n)`
> await Factory.model('App/Models/User').createMany(3)

3. `make`
Trả về một liên kết của 1 model(`model instance`), chứ không tạo dữ liệu vào DB
> await Factory.model('App/Models/User').make()

4. `makeMany(n)`
> await Factory.model('App/Models/User').makeMany(3)


## Không sử dụng Lucid models
Lucid liên kết với DB thông qua các model.
Nếu dự án của bạn không sử dụng `Lucid models`, thì vẫn có thể sử dụng `Database Provider`.

1. blueprint
<!-->
Factory.blueprint('users', (faker) => {
return {
username: faker.username(),
password: faker.password()
}
})
<-->

2. create
<!-->
run () {
await Factory.get('users').create()
}
<-->

3. table
Đổi tên table trong lúc chạy
> await Factory.get('users').table('my_users').create()

4. returning
Đối với PostgreSQL, có thể định nghĩa column sẽ trả về
> await Factory.get('users').returning('id').create()

5. connection
Đổi kết nối DB trong lúc chạy
> await Factory.get('users').connection('mysql').returning('id').create()

6. createMany
> await Factory.get('users').createMany(3)


## Custom Data
methods make, makeMany, create và createMany chấp nhận các filter.
<!-->
const user = await Factory
.model('App/Models/User')
.create({ status: 'admin' })
-->

<!-->
Factory.blueprint('App/Models/User', async (faker, i, data) => {
return {
username: faker.username(),
status: data.status
}
})
<-->



Không có nhận xét nào:

Đăng nhận xét

Học lập trình web căn bản với PHP

Bài 1: Các kiến thức căn bản Part 1:  https://jimmyvan88.blogspot.com/2012/05/can-ban-lap-trinh-web-voi-php-bai-1-cac.html Part 2:  https://...