メインコンテンツへスキップする

Optional Fields

Protobufに共通する問題は、nilの表現方法です。ゼロ値のプリミティブ・フィールドはバイナリ表現にエンコードされていないため、アプリケーションはプリミティブ・フィールドのゼロ値とnot-setを区別することができません。

これをサポートするために、Protobufプロジェクトでは「ラッパー型」と呼ばれるいくつかのWell-Known typesをサポートしています。 例えば、boolのラッパー型は、google.protobuf.BoolValueと呼ばれ、次のように定義されています:

ent/proto/entpb/entpb.proto
// Wrapper message for `bool`.
//
// The JSON representation for `BoolValue` is JSON `true` and `false`.
message BoolValue {
// The bool value.
bool value = 1;
}

entprotoがProtobufメッセージ定義を生成するとき、これらのラッパー型を使用してOptionalなentフィールドを表現します。

実際に、Optionalなフィールドを含むようにentスキーマを変更して見ましょう:

ent/schema/user.go
// Fields of the User.
func (User) Fields() []ent.Field {
return []ent.Field{
field.String("name").
Unique().
Annotations(
entproto.Field(2),
),
field.String("email_address").
Unique().
Annotations(
entproto.Field(3),
),
field.String("alias").
Optional().
Annotations(entproto.Field(4)),
}
}

go generate ./...を再実行して、UserのProtobuf定義が次のようになったことを確認します:

ent/proto/entpb/entpb.proto
message User {
int32 id = 1;

string name = 2;

string email_address = 3;

google.protobuf.StringValue alias = 4; // <-- this is new

repeated Category administered = 5;
}

生成されたサービスの実装もこのフィールドを利用します。 entpb_user_service.go を見てみましょう:

ent/proto/entpb/entpb_user_service.go
func (svc *UserService) createBuilder(user *User) (*ent.UserCreate, error) {
m := svc.client.User.Create()
if user.GetAlias() != nil {
userAlias := user.GetAlias().GetValue()
m.SetAlias(userAlias)
}
userEmailAddress := user.GetEmailAddress()
m.SetEmailAddress(userEmailAddress)
userName := user.GetName()
m.SetName(userName)
for _, item := range user.GetAdministered() {
administered := int(item.GetId())
m.AddAdministeredIDs(administered)
}
return m, nil
}

クライアントコードでラッパー型を利用するには、 wrapperspbパッケージが提供するヘルパー・メソッドを利用して、 ラッパー型のインスタンスを簡単に構築することができます。 例 cmd/client/main.go

func randomUser() *entpb.User {
return &entpb.User{
Name: fmt.Sprintf("user_%d", rand.Int()),
EmailAddress: fmt.Sprintf("user_%d@example.com", rand.Int()),
Alias: wrapperspb.String("John Doe"),
}
}