Class: ElasticGraph::SchemaDefinition::API

Inherits:
Object
  • Object
show all
Defined in:
lib/elastic_graph/schema_definition/api.rb

Overview

Root API object that provides the schema definition API.

Examples:

ElasticGraph.define_schema do |schema|
  # The `schema` object is an instance of `API`
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(schema_elements, index_document_sizes, extension_modules: [], derived_type_name_formats: {}, type_name_overrides: {}, enum_value_overrides_by_type: {}, output: $stdout) ⇒ API

Returns a new instance of API.



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/elastic_graph/schema_definition/api.rb', line 54

def initialize(
  schema_elements,
  index_document_sizes,
  extension_modules: [],
  derived_type_name_formats: {},
  type_name_overrides: {},
  enum_value_overrides_by_type: {},
  output: $stdout
)
  @state = State.with(
    api: self,
    schema_elements: schema_elements,
    index_document_sizes: index_document_sizes,
    derived_type_name_formats: derived_type_name_formats,
    type_name_overrides: type_name_overrides,
    enum_value_overrides_by_type: enum_value_overrides_by_type,
    output: output
  )

  @factory = @state.factory

  extension_modules.each { |mod| extend(mod) }

  # These lines must come _after_ the extension modules are applied, so that the extension modules
  # have a chance to hook into the factory in order to customize built in types if desired.
  @factory.new_built_in_types(self).register_built_in_types
  @state.initially_registered_built_in_types.merge(@state.types_by_name.keys)
end

Instance Attribute Details

#factoryFactory (readonly)

Returns object responsible for instantiating all schema element classes.

Returns:

  • (Factory)

    object responsible for instantiating all schema element classes



51
52
53
# File 'lib/elastic_graph/schema_definition/api.rb', line 51

def factory
  @factory
end

#stateState (readonly)

Returns object which holds all state for the schema definition.

Returns:

  • (State)

    object which holds all state for the schema definition



48
49
50
# File 'lib/elastic_graph/schema_definition/api.rb', line 48

def state
  @state
end

Instance Method Details

#as_active_instanceObject

While the block executes, makes any ‘ElasticGraph.define_schema` calls operate on this `API` instance.



349
350
351
352
353
354
355
356
# File 'lib/elastic_graph/schema_definition/api.rb', line 349

def as_active_instance
  # @type var old_value: API?
  old_value = ::Thread.current[:ElasticGraph_SchemaDefinition_API_instance]
  ::Thread.current[:ElasticGraph_SchemaDefinition_API_instance] = self
  yield
ensure
  ::Thread.current[:ElasticGraph_SchemaDefinition_API_instance] = old_value
end

#deleted_type(name) ⇒ void

Note:

In situations where this API applies, ElasticGraph will give you an error message indicating that you need to use this API or SchemaElements::TypeWithSubfields#renamed_from. Likewise, when ElasticGraph no longer needs to know about this, it’ll give you a warning indicating the call to this method can be removed.

This method returns an undefined value.

Registers the name of a type that existed in a prior version of the schema but has been deleted.

Examples:

Indicate that ‘Widget` has been deleted

ElasticGraph.define_schema do |schema|
  schema.deleted_type "Widget"
end

Parameters:

  • name (String)

    name of type that used to exist but has been deleted



261
262
263
264
265
266
267
268
# File 'lib/elastic_graph/schema_definition/api.rb', line 261

def deleted_type(name)
  @state.register_deleted_type(
    name,
    defined_at: caller_locations(1, 1).first, # : ::Thread::Backtrace::Location
    defined_via: %(schema.deleted_type "#{name}")
  )
  nil
end

#enum_type(name) {|SchemaElements::EnumType| ... } ⇒ void

This method returns an undefined value.

Defines a [GraphQL enum type](graphql.org/learn/schema/#enumeration-types). The type is restricted to an enumerated set of values, each with a unique name. Use ‘value` or `values` to define the enum values in the passed block.

Note: if required by your configuration, this may generate a pair of Enum types (an input enum and an output enum).

Examples:

Define an enum type

ElasticGraph.define_schema do |schema|
  schema.enum_type "Currency" do |t|
    t.value "USD" do |v|
      v.documentation "US Dollars."
    end

    t.value "JPY" do |v|
      v.documentation "Japanese Yen."
    end

    # You can define multiple values in one call if you don't care about their docs or directives.
    t.values "GBP", "AUD"
  end
end

Parameters:

  • name (String)

    name of the enum type

Yields:



193
194
195
196
# File 'lib/elastic_graph/schema_definition/api.rb', line 193

def enum_type(name, &block)
  @state.register_enum_type @factory.new_enum_type(name.to_s, &block)
  nil
end

#interface_type(name) {|SchemaElements::InterfaceType| ... } ⇒ void

This method returns an undefined value.

Defines a [GraphQL interface](graphql.org/learn/schema/#interfaces). Use it to define an abstract supertype with one or more fields that concrete implementations of the interface must also define. Each implementation can be an SchemaElements::ObjectType or SchemaElements::InterfaceType.

Examples:

Define an interface and implement it

ElasticGraph.define_schema do |schema|
  schema.interface_type "Athlete" do |t|
    t.field "name", "String"
    t.field "team", "String"
  end

  schema.object_type "BaseballPlayer" do |t|
    t.implements "Athlete"
    t.field "name", "String"
    t.field "team", "String"
    t.field "battingAvg", "Float"
  end

  schema.object_type "BasketballPlayer" do |t|
    t.implements "Athlete"
    t.field "name", "String"
    t.field "team", "String"
    t.field "pointsPerGame", "Float"
  end
end

Parameters:

  • name (String)

    name of the interface

Yields:



162
163
164
165
# File 'lib/elastic_graph/schema_definition/api.rb', line 162

def interface_type(name, &block)
  @state.register_object_interface_or_union_type @factory.new_interface_type(name.to_s, &block)
  nil
end

#json_schema_version(version) ⇒ void

Note:

While this is an important part of how ElasticGraph is designed to support schema evolution, it can be annoying constantly have to increment this while rapidly changing the schema during prototyping. You can disable the requirement to increment this on every JSON schema change by setting ‘enforce_json_schema_version` to `false` in your `Rakefile`.

This method returns an undefined value.

Defines the version number of the current JSON schema. Importantly, every time a change is made that impacts the JSON schema artifact, the version number must be incremented to ensure that each different version of the JSON schema is identified by a unique version number. The publisher will then include this version number in published events to identify the version of the schema it was using. This avoids the need to deploy the publisher and ElasticGraph indexer at the same time to keep them in sync.

Examples:

Set the JSON schema version to 1

ElasticGraph.define_schema do |schema|
  schema.json_schema_version 1
end

Parameters:

  • version (Integer)

    current version number of the JSON schema artifact

See Also:

  • Local::RakeTasks#enforce_json_schema_version


315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/elastic_graph/schema_definition/api.rb', line 315

def json_schema_version(version)
  if !version.is_a?(Integer) || version < 1
    raise Errors::SchemaError, "`json_schema_version` must be a positive integer. Specified version: #{version}"
  end

  if @state.json_schema_version
    raise Errors::SchemaError, "`json_schema_version` can only be set once on a schema. Previously-set version: #{@state.json_schema_version}"
  end

  @state.json_schema_version = version
  @state.json_schema_version_setter_location = caller_locations(1, 1).to_a.first
  nil
end

#object_type(name) {|SchemaElements::ObjectType| ... } ⇒ void

This method returns an undefined value.

Defines a [GraphQL object type](graphql.org/learn/schema/#object-types-and-fields) Use it to define a concrete type that has subfields. Object types can either be indexed (e.g. directly indexed in the datastore, and available to query from the root ‘Query` object) or embedded in other indexed types.

Examples:

Define embedded and indexed object types

ElasticGraph.define_schema do |schema|
  # `Money` is an embedded object type
  schema.object_type "Money" do |t|
    t.field "currency", "String"
    t.field "amount", "JsonSafeLong"
  end

  # `Transaction` is an indexed object type
  schema.object_type "Transaction" do |t|
    t.root_query_fields plural: "transactions"
    t.field "id", "ID"
    t.field "cost", "Money"
    t.index "transactions"
  end
end

Parameters:

  • name (String)

    name of the object type

Yields:



128
129
130
131
# File 'lib/elastic_graph/schema_definition/api.rb', line 128

def object_type(name, &block)
  @state.register_object_interface_or_union_type @factory.new_object_type(name.to_s, &block)
  nil
end

#on_built_in_types {|SchemaElements::EnumType, SchemaElements::InputType, SchemaElements::InterfaceType, SchemaElements::ObjectType, SchemaElements::ScalarType, SchemaElements::UnionType| ... } ⇒ void

This method returns an undefined value.

Registers a customization callback that will be applied to every built-in type automatically provided by ElasticGraph. Provides an opportunity to customize the built-in types (e.g. to add directives to them or whatever).

Examples:

Customize documentation of built-in types

ElasticGraph.define_schema do |schema|
  schema.on_built_in_types do |type|
    type.append_to_documentation "This is a built-in ElasticGraph type."
  end
end

Yields:



341
342
343
344
# File 'lib/elastic_graph/schema_definition/api.rb', line 341

def on_built_in_types(&customization_block)
  @state.built_in_types_customization_blocks << customization_block
  nil
end

#raw_sdl(string) ⇒ void

This method returns an undefined value.

Defines a raw GraphQL SDL snippet that will be included in the generated ‘schema.graphql` artifact. Designed to be an escape hatch, for when ElasticGraph doesn’t provide another way to write some type of GraphQL SDL element that you need. Currently, the only known use case is to define custom GraphQL directives.

Examples:

Define a custom directive and use it

ElasticGraph.define_schema do |schema|
  # Define a directive we can use to annotate what system a data type comes from.
  schema.raw_sdl "directive @sourcedFrom(system: String!) on OBJECT"

  schema.object_type "Transaction" do |t|
    t.directive "sourcedFrom", system: "transaction-processor"
  end
end

Parameters:

  • string (String)

    Raw snippet of SDL



99
100
101
102
# File 'lib/elastic_graph/schema_definition/api.rb', line 99

def raw_sdl(string)
  @state.sdl_parts << string
  nil
end

#register_graphql_extension(extension_module, defined_at:, **extension_config) ⇒ void

This method returns an undefined value.

Registers a GraphQL extension module that will be loaded and used by ‘elasticgraph-graphql`. While such extension modules can also be configured in a settings YAML file, it can be useful to register it here when you want to ensure that the extension is used in all environments. For example, an extension library that defines custom schema elements (such as `elasticgraph-apollo`) may need to ensure its corresponding GraphQL extension module is used since the custom schema elements would not work correctly otherwise.

Examples:

Register ‘elasticgraph-query_registry` extension module

require(query_registry_require_path = "elastic_graph/query_registry/graphql_extension")

ElasticGraph.define_schema do |schema|
  schema.register_graphql_extension ElasticGraph::QueryRegistry::GraphQLExtension,
    defined_at: query_registry_require_path
end

Parameters:

  • extension_module (Module)

    GraphQL extension module

  • defined_at (String)

    the ‘require` path of the extension module

  • extension_config (Hash<Symbol, Object>)

    configuration options for the extension module



288
289
290
291
# File 'lib/elastic_graph/schema_definition/api.rb', line 288

def register_graphql_extension(extension_module, defined_at:, **extension_config)
  @state.graphql_extension_modules << SchemaArtifacts::RuntimeMetadata::Extension.new(extension_module, defined_at, extension_config)
  nil
end

#resultsObject

Returns the results of the schema definition.

Returns:

  • the results of the schema definition



294
295
296
# File 'lib/elastic_graph/schema_definition/api.rb', line 294

def results
  @results ||= Results.new(@state)
end

#scalar_type(name) {|SchemaElements::ScalarType| ... } ⇒ void

This method returns an undefined value.

Defines a [GraphQL scalar type](graphql.org/learn/schema/#scalar-types). ElasticGraph itself uses this to define a few common scalar types (e.g. ‘Date` and `DateTime`), but it is also available to you to use to define your own custom scalar types.

Examples:

Define a scalar type

ElasticGraph.define_schema do |schema|
  schema.scalar_type "URL" do |t|
    t.mapping type: "keyword"
    t.json_schema type: "string", format: "uri"
  end
end

Parameters:

  • name (String)

    name of the scalar type

Yields:



243
244
245
246
# File 'lib/elastic_graph/schema_definition/api.rb', line 243

def scalar_type(name, &block)
  @state.register_scalar_type @factory.new_scalar_type(name.to_s, &block)
  nil
end

#union_type(name) {|SchemaElements::UnionType| ... } ⇒ void

This method returns an undefined value.

Defines a [GraphQL union type](graphql.org/learn/schema/#union-types). Use it to define an abstract supertype with one or more concrete subtypes. Each subtype must be an SchemaElements::ObjectType, but they do not have to share any fields in common.

Examples:

Define a union type

ElasticGraph.define_schema do |schema|
  schema.object_type "Card" do |t|
    # ...
  end

  schema.object_type "BankAccount" do |t|
    # ...
  end

  schema.object_type "BitcoinWallet" do |t|
    # ...
  end

  schema.union_type "FundingSource" do |t|
    t.subtype "Card"
    t.subtypes "BankAccount", "BitcoinWallet"
  end
end

Parameters:

  • name (String)

    name of the union type

Yields:



224
225
226
227
# File 'lib/elastic_graph/schema_definition/api.rb', line 224

def union_type(name, &block)
  @state.register_object_interface_or_union_type @factory.new_union_type(name.to_s, &block)
  nil
end