github.com/GuanceCloud/cliutils@v1.1.21/point/json.go (about)

     1  // Unless explicitly stated otherwise all files in this repository are licensed
     2  // under the MIT License.
     3  // This product includes software developed at Guance Cloud (https://www.guance.com/).
     4  // Copyright 2021-present Guance, Inc.
     5  
     6  package point
     7  
     8  import (
     9  	bytes "bytes"
    10  	"encoding/json"
    11  	"time"
    12  
    13  	protojson "github.com/gogo/protobuf/jsonpb"
    14  )
    15  
    16  type JSONPoint struct {
    17  	// Requride
    18  	Measurement string `json:"measurement"`
    19  
    20  	// Optional
    21  	Tags map[string]string `json:"tags,omitempty"`
    22  
    23  	// Requride
    24  	Fields map[string]interface{} `json:"fields"`
    25  
    26  	// Unix nanosecond
    27  	Time int64 `json:"time,omitempty"`
    28  }
    29  
    30  func (jp *JSONPoint) Point(opts ...Option) (*Point, error) {
    31  	// NOTE: preferred in-point time
    32  	if jp.Time != 0 {
    33  		opts = append(opts, WithTime(time.Unix(0, jp.Time)))
    34  	}
    35  	return NewPoint(jp.Measurement, jp.Tags, jp.Fields, opts...)
    36  }
    37  
    38  // MarshalJSON to protobuf json.
    39  func (p *Point) MarshalJSON() ([]byte, error) {
    40  	if p.HasFlag(Ppb) {
    41  		m := &protojson.Marshaler{}
    42  		pb := p.PBPoint()
    43  		buf := bytes.Buffer{}
    44  		if err := m.Marshal(&buf, pb); err != nil {
    45  			return nil, err
    46  		}
    47  		return buf.Bytes(), nil
    48  	}
    49  
    50  	return json.Marshal(&JSONPoint{
    51  		Measurement: p.Name(),
    52  		Tags:        p.MapTags(),
    53  		Fields:      p.InfluxFields(),
    54  		Time:        p.pt.Time,
    55  		// NOTE: warns & debugs skipped.
    56  	})
    57  }
    58  
    59  // UnmarshalJSON unmarshal protobuf json.
    60  func (p *Point) UnmarshalJSON(j []byte) error {
    61  	var x PBPoint
    62  	var pt *Point
    63  
    64  	m := &protojson.Unmarshaler{}
    65  	buf := bytes.NewBuffer(j)
    66  
    67  	// try pb unmarshal.
    68  	if err := m.Unmarshal(buf, &x); err == nil {
    69  		pt = FromPB(&x)
    70  	} else {
    71  		// try JSONPoint unmarshal
    72  		var y JSONPoint
    73  		if err := json.Unmarshal(j, &y); err == nil {
    74  			pt = fromJSONPoint(&y)
    75  		} else {
    76  			return err
    77  		}
    78  	}
    79  
    80  	*p = *pt
    81  
    82  	return nil
    83  }
    84  
    85  func fromJSONPoint(j *JSONPoint) *Point {
    86  	kvs := NewKVs(j.Fields)
    87  
    88  	for k, v := range j.Tags {
    89  		kvs = kvs.MustAddTag(k, v)
    90  	}
    91  
    92  	return NewPointV2(j.Measurement, kvs, WithTimestamp(j.Time))
    93  }