Module: Deimos::Utils::SchemaControllerMixin

Extended by:
ActiveSupport::Concern
Defined in:
lib/deimos/utils/schema_controller_mixin.rb

Overview

Mixin to automatically decode schema-encoded payloads when given the correct content type, and provide the ‘render_schema` method to encode the payload for responses.

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#decode_schemavoid

This method returns an undefined value.

Decode the payload with the parameters.



102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/deimos/utils/schema_controller_mixin.rb', line 102

def decode_schema
  namespace, schema = parse_namespace(:request)
  decoder = Deimos.schema_backend(schema: schema, namespace: namespace)
  @payload = decoder.decode(request.body.read).with_indifferent_access
  @payload.each do |key, value|
    Deimos.config.tracer&.set_tag("body.#{key}", value)
  end
  if Deimos.config.schema.use_schema_classes
    @payload = Utils::SchemaClass.instance(@payload, schema, namespace)
  end
  request.body.rewind if request.body.respond_to?(:rewind)
end

#parse_namespace(type) ⇒ Array<String, String>

Get the namespace from either an existing instance variable, or tease it out of the schema.

Parameters:

  • type (Symbol)

    :request or :response

Returns:

  • (Array<String, String>)

    the namespace and schema.



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/deimos/utils/schema_controller_mixin.rb', line 82

def parse_namespace(type)
  namespace = self.class.namespaces[type]
  schema = self.class.schema_mapping[params['action']][type]
  if schema.nil?
    raise "No #{type} schema defined for #{params[:controller]}##{params[:action]}!"
  end

  if namespace.nil?
    last_period = schema.rindex('.')
    namespace, schema = schema.split(last_period)
  end
  if namespace.nil? || schema.nil?
    raise "No request namespace defined for #{params[:controller]}##{params[:action]}!"
  end

  [namespace, schema]
end

#render_schema(payload, schema: nil, namespace: nil) ⇒ void

This method returns an undefined value.

Render a hash into a payload as specified by the configured schema and namespace.

Parameters:

  • payload (Hash)
  • schema (String) (defaults to: nil)
  • namespace (String) (defaults to: nil)


120
121
122
123
124
125
126
# File 'lib/deimos/utils/schema_controller_mixin.rb', line 120

def render_schema(payload, schema: nil, namespace: nil)
  namespace, schema = parse_namespace(:response) if !schema && !namespace
  encoder = Deimos.schema_backend(schema: schema, namespace: namespace)
  encoded = encoder.encode(payload.to_h, topic: "#{namespace}.#{schema}")
  response.headers['Content-Type'] = encoder.class.content_type
  send_data(encoded)
end

#schema_format?Boolean

Returns:

  • (Boolean)


75
76
77
# File 'lib/deimos/utils/schema_controller_mixin.rb', line 75

def schema_format?
  request.content_type == Deimos.schema_backend_class.content_type
end