Skip to content

Ability to unmarshal query response directly to protobuf struct #8

@lehajam

Description

@lehajam

I would like to know if there is a way to unmarshal a query response directly into a protobuf struct (the same used to insert data). In the code below it will only work if I create a new struct and define contract field as an array.
This was previously possible using client.unmarshal and I believe being able to insert and query data from dgraph via grpc and protobuf (without any additional code) was a great feature of the go client.

// PB definition
//
// message European {
// 	double timestamp = 1;
// 	string ticker = 2;
// 	string undticker = 3;
// 	double strike = 4;
// 	double expiry = 5;
// 	string putcall = 6;
// }
//
// message PriceRequest {
// 	double pricingdate = 1;
// 	European contract = 2;
// 	OptionMarket marketdata = 3;
// }

func Test_contractRequest(t *testing.T) {
	resp := query(
		`query ContractRequest($optionTicker: string){
			contract(func: eq(ticker, $optionTicker)){
				ticker
				strike
				undticker
				expiry
				putcall
			}
		}`,
		map[string]string{
			"$optionTicker": "AAPL DEC2017 PUT",
		})

	priceReq := &pb.PriceRequest{}
	// Fails with error "json: cannot unmarshal array into Go struct field PriceRequest.contract of type pb.European"
	err := json.Unmarshal(resp.GetJson(), priceReq)
	if err != nil {
		type Root struct {
			Contract []pb.European `json:"contract"`
		}

		root := &Root{}
		// Works fine
		err = json.Unmarshal(resp.GetJson(), root)
		if err != nil {
			t.Error(err)
		}
		t.Log(root)
		t.Fail()
	}
	t.Log(priceReq)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions