blob: e55aa12d9b42a56747bdca6bd446efc43308e6b4 [file] [log] [blame]
Scott Bakere7144bc2019-10-01 14:16:47 -07001/*
2Copyright 2014 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package versioned
18
19import (
20 "encoding/json"
21
22 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
23 "k8s.io/apimachinery/pkg/runtime"
24 "k8s.io/apimachinery/pkg/runtime/serializer/streaming"
25 "k8s.io/apimachinery/pkg/watch"
26)
27
28// Encoder serializes watch.Events into io.Writer. The internal objects
29// are encoded using embedded encoder, and the outer Event is serialized
30// using encoder.
31// TODO: this type is only used by tests
32type Encoder struct {
33 encoder streaming.Encoder
34 embeddedEncoder runtime.Encoder
35}
36
37func NewEncoder(encoder streaming.Encoder, embeddedEncoder runtime.Encoder) *Encoder {
38 return &Encoder{
39 encoder: encoder,
40 embeddedEncoder: embeddedEncoder,
41 }
42}
43
44// Encode writes an event to the writer. Returns an error
45// if the writer is closed or an object can't be encoded.
46func (e *Encoder) Encode(event *watch.Event) error {
47 data, err := runtime.Encode(e.embeddedEncoder, event.Object)
48 if err != nil {
49 return err
50 }
51 // FIXME: get rid of json.RawMessage.
52 return e.encoder.Encode(&metav1.WatchEvent{
53 Type: string(event.Type),
54 Object: runtime.RawExtension{Raw: json.RawMessage(data)},
55 })
56}