Ent: how to add custom methods to entities?

Created on 22 Dec 2020  路  3Comments  路  Source: ent/ent

I was wondering if it's a good idea to add some custom methods to entities, or would this be discouraged?
using external templates seems quite cumbersome to add things like this, would it be a bad idea to just add a ent/user_custom.go and define them there?

ie. simple helpers like

func (u *User) IsActiveUser() bool {
    return !u.IsBot && user.LastActiveAt != nil
}

and for updating?

func (u *User) Deactivate(ctx context.Context) error {
    u.IsActive = false
    return u.Update().Save(ctx)
}

and same for querying?

func (uq *UserQuery) AllActiveForCompany(company *Company) *UserQuery {
    ...
}

or?

func (u *User) AllChibiPets(ctx context.Context) ([]*Pet, error) {
    return u.PetsQuery().Where(pets.SizeEQ("chibi")).All(ctx)
}
Question

Most helpful comment

func (u *User) Deactivate(ctx context.Context) error {
u.IsActive = false
return u.Update().Save(ctx)
}

Just note that this will _not_ work, see docs on how to perform updates.

All 3 comments

Hey @rubensayshi!
Both options are fine. I usually suggest using custom templates when the custom logic has to be generated for more than one entity type, or it's based on code-generation information.

func (u *User) Deactivate(ctx context.Context) error {
u.IsActive = false
return u.Update().Save(ctx)
}

Just note that this will _not_ work, see docs on how to perform updates.

awesome, thx for both replies!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

a8m picture a8m  路  5Comments

HarikiRito picture HarikiRito  路  3Comments

sno6 picture sno6  路  4Comments

satriahrh picture satriahrh  路  3Comments

DeedleFake picture DeedleFake  路  5Comments