Thứ Ba, 13 tháng 4, 2021

Lucid ORM - Mutators trong AdonisJS




Getters and setters cung cấp rất nhiều lợi ích để format giá trị
trước khi đưa vào DB hoặc xuất kết quả ra bên ngoài.

#### 1. Getters
File app/Models/Post.js
<!-->
'use strict'

const Model = use('Model')

class Post extends Model {
getTitle (title) {
return title.replace(/^(.)|\s(.)/g, ($1) => {
return $1.toUpperCase()
})
}
}
<-->

> const post = await Post.find(postId)

// getters are called automatically
> return post.toJSON()

- Ở bất kì nơi nào sử dụng post.title thì method getTitle() sẽ được gọi và trả về kết quả.
- Khi sử dụng `toJSON()` thì các Getter cũng được tự động gọi.
- Getters bắt đầu với keyword `get` Và method name là dạng camel case
Ví dụ: field field_name thì Getter là getFieldName.
- Getters được gọi theo tuần tự(synchronous).
Nếu muốn sử dụng bất đồng bộ(asynchronous) thì hãy sử dụng hooks.

#### 2. Setter
Thường được sử dụng để tinh chỉnh dữ liệu trước khi lưu.
File app/Models/User.js
<!-->
'use strict'

const Model = use('Model')

class User extends Model {
setAccess (access) {
return access === 'admin' ? 1 : 0
}
}
<-->
kiểm thử ở một controller:
<!-->
const user = new User()
user.access = 'admin'

console.log(user.access) // will return 1
await user.save()
<-->

- Một Setter luôn bắt đầu với từ khóa `set`
    và theo quy tắc `camel case` (field field_name ==> setFieldName())
- Một Setter được thực thi khi thêm hoặc cập nhật dữ liệu
- Thường được sử dụng khi muốn thay đổi giá trị user nhập vào sang giá trị sẽ lưu ở DB.
- Setters được gọi theo tuần tự(synchronous). Nếu muốn sử dụng bất đồng bộ(asynchronous)
thì hãy sử dụng hooks.

## Computed Properties
Computed Properties là một `thuộc tính ảo`, chỉ tồn tại trong model instance’s JSON.
Không tồn tại trong DB.

Ví dụ: Tạo 1 field ảo fullname mà fullname = firstname + lastname
File app/Models/User.js
<!-->
'use strict'

const Model = use('Model')

class User extends Model {
static get computed () {
return ['fullname']
}

getFullname ({ firstname, lastname }) {
return `${firstname} ${lastname}`
}
}
<-->

Sử dụng:
<!-->
const user = await User.find(1)
const json = user.toJSON()
console.log(json.fullname) // firstname + lastname
<-->



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://...