Module: ElasticGraph::Support::UntypedEncoder

Defined in:
lib/elastic_graph/support/untyped_encoder.rb

Overview

Responsible for encoding ‘Untyped` values into strings. This logic lives here in `elasticgraph-support` so that it can be shared between the `Untyped` indexing preparer (which lives in `elasticgraph-indexer`) and the `Untyped` coercion adapter (which lives in `elasticgraph-graphql`). It is important that these share the same logic so that the string values we attempt to filter on at query time match the string values we indexed when given the semantically equivalent untyped data.

Note: change this class with care. Changing the behavior to make ‘encode` produce different strings may result in breaking queries if the `Untyped`s stored in the index were indexed using previous encoding logic. A backfill into the datastore will likely be required to avoid this issue.

Class Method Summary collapse

Class Method Details

.decode(string) ⇒ Object

Decodes a previously encoded Untyped value, returning its original value.



38
39
40
41
# File 'lib/elastic_graph/support/untyped_encoder.rb', line 38

def self.decode(string)
  return nil if string.nil?
  ::JSON.parse(string)
end

.encode(value) ⇒ Object

Encodes the given untyped value to a String so it can be indexed in a Elasticsearch/OpenSearch ‘keyword` field.



24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/elastic_graph/support/untyped_encoder.rb', line 24

def self.encode(value)
  return nil if value.nil?
  # Note: we use `fast_generate` here instead of `generate`. They basically act the same, except
  # `generate` includes an extra check for self-referential data structures. `value` here ultimately
  # comes out of a parsed JSON document (e.g. either from an ElasticGraph event at indexing time, or
  # as a GraphQL query variable at search time), and JSON cannot express self-referential data
  # structures, so we do not have to worry about that happening.
  #
  # ...but even if it did, we would get an error either way: `JSON.generate` would raise
  # `JSON::NestingError` whereas `:JSON.fast_generate` would give us a `SystemStackError`.
  ::JSON.fast_generate(canonicalize(value))
end