github.com/grbit/go-json@v0.11.0/test/example/example_query_test.go (about)

     1  package json_test
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"log"
     7  
     8  	"github.com/grbit/go-json"
     9  )
    10  
    11  type User struct {
    12  	ID      int64
    13  	Name    string
    14  	Age     int
    15  	Address UserAddressResolver
    16  }
    17  
    18  type UserAddress struct {
    19  	UserID   int64
    20  	PostCode string
    21  	City     string
    22  	Address1 string
    23  	Address2 string
    24  }
    25  
    26  type UserRepository struct {
    27  	uaRepo *UserAddressRepository
    28  }
    29  
    30  func NewUserRepository() *UserRepository {
    31  	return &UserRepository{
    32  		uaRepo: NewUserAddressRepository(),
    33  	}
    34  }
    35  
    36  type UserAddressRepository struct{}
    37  
    38  func NewUserAddressRepository() *UserAddressRepository {
    39  	return &UserAddressRepository{}
    40  }
    41  
    42  type UserAddressResolver func(context.Context) (*UserAddress, error)
    43  
    44  func (resolver UserAddressResolver) MarshalJSON(ctx context.Context) ([]byte, error) {
    45  	address, err := resolver(ctx)
    46  	if err != nil {
    47  		return nil, err
    48  	}
    49  	return json.MarshalContext(ctx, address)
    50  }
    51  
    52  func (r *UserRepository) FindByID(ctx context.Context, id int64) (*User, error) {
    53  	user := &User{ID: id, Name: "Ken", Age: 20}
    54  	// resolve relation from User to UserAddress
    55  	user.Address = func(ctx context.Context) (*UserAddress, error) {
    56  		return r.uaRepo.FindByUserID(ctx, user.ID)
    57  	}
    58  	return user, nil
    59  }
    60  
    61  func (*UserAddressRepository) FindByUserID(ctx context.Context, id int64) (*UserAddress, error) {
    62  	return &UserAddress{
    63  		UserID:   id,
    64  		City:     "A",
    65  		Address1: "foo",
    66  		Address2: "bar",
    67  	}, nil
    68  }
    69  
    70  func Example_fieldQuery() {
    71  	ctx := context.Background()
    72  	userRepo := NewUserRepository()
    73  	user, err := userRepo.FindByID(ctx, 1)
    74  	if err != nil {
    75  		log.Fatal(err)
    76  	}
    77  	query, err := json.BuildFieldQuery(
    78  		"Name",
    79  		"Age",
    80  		json.BuildSubFieldQuery("Address").Fields(
    81  			"City",
    82  		),
    83  	)
    84  	if err != nil {
    85  		log.Fatal(err)
    86  	}
    87  	ctx = json.SetFieldQueryToContext(ctx, query)
    88  	b, err := json.MarshalContext(ctx, user)
    89  	if err != nil {
    90  		log.Fatal(err)
    91  	}
    92  	fmt.Println(string(b))
    93  
    94  	// Output:
    95  	// {"Name":"Ken","Age":20,"Address":{"City":"A"}}
    96  }