Last active
February 24, 2022 07:05
-
-
Save Fantasim/dde84408323bdcc89d971fe54ca3b45f to your computer and use it in GitHub Desktop.
Populate example on Elzeard
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Model, Joi, Collection } from 'elzeard' | |
export class UserModel extends Model { | |
static schema = Joi.object({ | |
id: Joi.number().autoIncrement().primaryKey() | |
username: Joi.string().min(3).max(20).lowercase().required().unique(), | |
}) | |
constructor(initialState: any, options: any){ | |
super(initialState, UserModel, options) | |
} | |
} | |
export class TodoModel extends Model { | |
static schema = Joi.object({ | |
id: Joi.number().autoIncrement().primaryKey(), | |
content: Joi.string().min(1).max(3000).required(), | |
user: Joi.number().positive().required().foreignKey('users', 'id').deleteCascade() | |
}) | |
constructor(initialState: any, options: any){ | |
super(initialState, TodoModel, options) | |
} | |
} | |
//We suppose this todo is already recorded in the database. | |
const todo = { | |
id: 5, | |
content: 'My todo has a good shape', | |
user: 2 | |
} | |
/* /!\ You never instance a model hardly by yourself in Elzeard, this is just for the example. */ | |
const m = new TodoModel(todo, {table: 'todos') | |
console.log(m.to().plain()) | |
/* | |
{ | |
id: 5, | |
content: 'My todo has a good shape', | |
user: 2 | |
} | |
*/ | |
/* | |
populate() will format the Model by replacing all the values | |
in which the keys carry an extension foreignKey() or populate(), | |
by the reference Model of these last ones. | |
*/ | |
await m.populate() | |
console.log(m.to().plain()) | |
/* | |
{ | |
id: 5, | |
content: 'My todo has a good shape', | |
user: { | |
id: 2, | |
username: 'fantasim' | |
} | |
} | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment