Golang/ORM

[Entgo] Hooks

GenieLove! 2022. 12. 7. 02:13
728x90
반응형

Hooks 

- 필드를 미리 작성 후 generate 한 뒤 hook을 작성해야 각종 필드에 맞는 Mutatotion이 생성되어 있다.

- 사용을 원할 때 main.go에 import _ "<project>/ent/runtime" 를 작성해야 작동한다.

Mutation

  • Create: 생성될 때 작동
  • UpdateOne: 하나의 데이터가 업데이트 될 때 작동
  • Update: 여러 개의 데이터가 업데이트 될 때 작동
  • DeleteOne: 하나의 데이터를 삭제할 때 작동
  • Delete: 여러 개의 데이터를 삭제할 때 작동

Runtime Hooks

- 로깅 등에 자주 사용

- schema hooks 보다 먼저 실행된다.

- 아래와 같이 모든 Entity에 적용하는 hook을 작성할 수 있다.

- hook.On을 사용하여 원하는 시점에만 작동할 수 있도록 지정할 수 있다.

    if err := client.Schema.Create(ctx); err != nil {
        log.Fatalf("failed creating schema resources: %v", err)
    }
    // Add a global hook that runs on all types and all operations.
    client.Use(func(next ent.Mutator) ent.Mutator {
        return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
            start := time.Now()
            defer func() {
                log.Printf("Op=%s\tType=%s\tTime=%s\tConcreteType=%T\n", m.Op(), m.Type(), time.Since(start), m)
            }()
            return next.Mutate(ctx, m)
        })
    })
    
    
    client.Use(hook.On(Logger(), ent.Create))

Schema Hooks

- 해당 스키마가 변경 시에만 작동한다.

- 원하는 필드만 변경 시에만 작동하게 설정할 수 있다.

- 이전 필드 값, 현재 설정하려는 필드 값 등을 알 수 있다.

func (Card) Hooks() []ent.Hook {
    return []ent.Hook{
        // First hook.
        hook.On(
            func(next ent.Mutator) ent.Mutator {
                return hook.CardFunc(func(ctx context.Context, m *gen.CardMutation) (ent.Value, error) {
                    if num, ok := m.Number(); ok && len(num) < 10 {
                        return nil, fmt.Errorf("card number is too short")
                    }
                    return next.Mutate(ctx, m)
                })
            },
            // Limit the hook only for these operations.
            ent.OpCreate|ent.OpUpdate|ent.OpUpdateOne,
        )
    }
}

- If 등 조건을 걸 수 있다.

- 아래 코드는 update 발생 & status 변경, dirty field가 clear 될 때 HookC함수를 실행한다.

 hook.If(HookC(), hook.And(
 	hook.HasOP(ent.OpUpdate),
 	hook.HasFields("status"), hook.HasClearedFields("dirty")))

https://entgo.io/docs/hooks/

728x90
반응형

'Golang > ORM' 카테고리의 다른 글

[Entgo] Hooks 사용 시 주의  (0) 2023.03.23
[GORM] Query  (0) 2022.09.28
[Entgo] CRUD API(작성 중)  (0) 2022.09.12
[Entgo] About Annotations  (0) 2022.09.03
[Entgo] About Mixin  (0) 2022.09.01