user.go 763 B

123456789101112131415161718192021222324252627282930313233343536
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "code.osinet.fr/fgm/go__ent_demo/ent"
  7. "code.osinet.fr/fgm/go__ent_demo/ent/user"
  8. )
  9. func CreateUser(ctx context.Context, client *ent.Client) (*ent.User, error) {
  10. u, err := client.User.
  11. Create().
  12. SetAge(30).
  13. SetName(name).
  14. Save(ctx)
  15. if err != nil {
  16. return nil, fmt.Errorf("failed creating user: %w", err)
  17. }
  18. log.Println("User created ", u)
  19. return u, nil
  20. }
  21. func QueryUser(ctx context.Context, client *ent.Client) (*ent.User, error) {
  22. u, err := client.User.
  23. Query().
  24. Where(user.Name(name)).
  25. // `Only` fails if no user found or more than 1 user returned.
  26. Only(ctx)
  27. if err != nil {
  28. return nil, fmt.Errorf("failed querying user: %w", err)
  29. }
  30. log.Println("user found: ", u)
  31. return u, nil
  32. }