8000 docs(models): add information about consume & prepare · adonisjs/lucid.adonisjs.com@c781c1d · GitHub
[go: up one dir, main page]

Skip to content

Commit c781c1d

Browse files
committed
docs(models): add information about consume & prepare
1 parent c5af63d commit c781c1d

File tree

1 file changed

+27
-3
lines changed

1 file changed

+27
-3
lines changed

content/docs/models/introduction.md

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -168,8 +168,33 @@ If you are not using the `snake_case` convention in your database, then you can
168168
You can also define the database column names explicitly within the `@column` decorator. This is usually helpful for bypassing the convention in specific use cases.
169169

170170
```ts
171-
@column({ columnName: 'user_id', isPrimary: true })
172-
declare id: number
171+
import { BaseModel, column } from '@adonisjs/lucid/orm'
172+
173+
export default class User extends BaseModel {
174+
@column({ columnName: 'user_id', isPrimary: true })
175+
declare id: number
176+
}
177+
```
178+
179+
### Preparing and consuming columns
180+
181+
Lucid allows you to transform the column values before saving them to the database or after fetching them from the database using the `consume` and `prepare` option.
182+
183+
For example, you are storing a "secret" value in the database, and you want to encrypt it before saving it and decrypt it after fetching it.
184+
185+
```ts
186+
// In this example, we are using the `encryption` module from the `@adonisjs/core` package
187+
// @see https://docs.adonisjs.com/guides/security/encryption
188+
import encryption from '@adonisjs/core/services/encryption'
189+
import { BaseModel, column } from '@adonisjs/lucid/orm'
190+
191+
export default class User extends BaseModel {
192+
@column({
193+
prepare: (value: string | null) => (value ? encryption.encrypt(value) : null),
194+
consume: (value: string | null) => (value ? encryption.decrypt(value) : null),
195+
})
196+
declare token: string | null
197+
}
173198
```
174199

175200
### Date columns
@@ -196,7 +221,6 @@ export default class User extends BaseModel {
196221

197222
Optionally, you can pass the `autoCreate` and `autoUpdate` options to always define the timestamps during the creation and the update operations. **Do note, setting these options doesn't modify the database table or its triggers.**
198223

199-
200224
## Models config
201225

202226
Following are the configuration options to overwrite the conventional defaults.

0 commit comments

Comments
 (0)
0