Module: Twirp::Encoding

Defined in:
lib/twirp/encoding.rb

Constant Summary collapse

JSON =
"application/json"
JSON_STRICT =

An opt-in content type useful when curling or manually testing a twirp service. This will fail if unknown fields are encountered. The return content type will be application/json.

"application/json; strict=true"
PROTO =
"application/protobuf"

Class Method Summary collapse

Class Method Details

.decode(bytes, msg_class, content_type) ⇒ Object



28
29
30
31
32
33
34
35
# File 'lib/twirp/encoding.rb', line 28

def decode(bytes, msg_class, content_type)
  case content_type
  when JSON then msg_class.decode_json(bytes, ignore_unknown_fields: true)
  when JSON_STRICT then msg_class.decode_json(bytes, ignore_unknown_fields: false)
  when PROTO then msg_class.decode(bytes)
  else raise ArgumentError.new("Invalid content_type")
  end
end

.decode_json(bytes) ⇒ Object



49
50
51
# File 'lib/twirp/encoding.rb', line 49

def decode_json(bytes)
  ::JSON.parse(bytes)
end

.encode(msg_obj, msg_class, content_type) ⇒ Object



37
38
39
40
41
42
43
# File 'lib/twirp/encoding.rb', line 37

def encode(msg_obj, msg_class, content_type)
  case content_type
  when JSON, JSON_STRICT then msg_class.encode_json(msg_obj, emit_defaults: true)
  when PROTO then msg_class.encode(msg_obj)
  else raise ArgumentError.new("Invalid content_type")
  end
end

.encode_json(attrs) ⇒ Object



45
46
47
# File 'lib/twirp/encoding.rb', line 45

def encode_json(attrs)
  ::JSON.generate(attrs)
end

.valid_content_type?(content_type) ⇒ Boolean

Returns:

  • (Boolean)


53
54
55
# File 'lib/twirp/encoding.rb', line 53

def valid_content_type?(content_type)
  content_type == JSON || content_type == PROTO || content_type == JSON_STRICT
end

.valid_content_typesObject



57
58
59
# File 'lib/twirp/encoding.rb', line 57

def valid_content_types
  [JSON, PROTO]
end