Module: GraphWeaver
- Defined in:
- lib/graph_weaver.rb,
lib/graph_weaver/hints.rb,
lib/graph_weaver/rspec.rb,
lib/graph_weaver/errors.rb,
lib/graph_weaver/inflect.rb,
lib/graph_weaver/logging.rb,
lib/graph_weaver/testing.rb,
lib/graph_weaver/version.rb,
lib/graph_weaver/response.rb,
lib/graph_weaver/selection.rb,
lib/graph_weaver/input_struct.rb,
lib/graph_weaver/transport/http.rb,
lib/graph_weaver/testing/failure.rb,
lib/graph_weaver/testing/cassette.rb,
lib/graph_weaver/codegen/enum_type.rb,
lib/graph_weaver/transport/faraday.rb
Overview
Opt-in test tooling: require "graph_weaver/testing" from your spec helper (never from production code). Configure once, initializer-style:
GraphWeaver::Testing.configure do |config|
config.schema = MySchema # for auto_fake / cassettes
config.seed = 42 # reproducible fakes
config.mode = :faker # or :literal; nil = auto
config.overrides = { "Person.name" => "Daniel" }
config.list_size = 2..4
config.null_chance = 0.1 # nullable fields go nil sometimes
config.cassette_dir = "spec/cassettes"
end
mode picks how values are fabricated: :faker — semantic, field-name matched (requires the faker gem) :literal — plain type-derived values ("name-1", seeded numbers) nil — auto: :faker when the gem is loaded, else :literal
rspec users: require "graph_weaver/rspec" instead — it hooks the suite (seed from rspec, optional auto-faked client per example).
Defined Under Namespace
Modules: ErrorFiltering, Hints, Inflect, InputStruct, SchemaLoader, Selection, Testing, TypeHelpers Classes: Client, Codegen, Error, GraphQLError, QueryError, Railtie, Response, Retry, ServerError, Transport, TransportError, TypeError, ValidationError
Constant Summary collapse
- VERSION =
"0.2.1"
Class Attribute Summary collapse
-
.auto_coerce ⇒ Object
Default input coercion for scalars that don't say coerce: themselves, resolved lazily at generation time (so set it any time before you generate — no reset_scalars! ordering dance):.
-
.client ⇒ Object
The app's default client — how generated modules find their server:.
- .generated_paths ⇒ Object
- .inputs_module(output = generated_path) ⇒ Object
-
.logger ⇒ Object
Where GraphWeaver narrates what it's doing — anything stdlib-Logger-compatible (Logger, Rails.logger, semantic_logger...).
-
.queries_paths ⇒ Object
Entries may be glob patterns — the generated default also matches per-schema layouts (app/graphql/github/generated).
- .schema_path ⇒ Object
Class Method Summary collapse
-
.clear_scalars! ⇒ Object
Empty the scalar registry entirely, built-ins included (see reset_scalars! to restore the defaults).
-
.client! ⇒ Object
the default client, when one is required.
-
.execute(source, query, **variables) ⇒ Object
One-shot dynamic execution — a throwaway client, no build step:.
-
.execute!(source, query, **variables) ⇒ Object
execute + data! — the typed result, or a raised QueryError.
-
.generate!(schema: nil, queries: queries_path, output: generated_path, client: nil, shared_inputs: true, inputs_module: nil) ⇒ Object
Generate every .graphql query in a directory into checked-in Ruby files.
- .generated_path ⇒ Object
- .generated_path=(path) ⇒ Object
-
.generation_plan(queries:, schema:, client:, shared_inputs:, inputs_module: self.inputs_module) ⇒ Object
(filename, source) per artifact: shared_inputs (the default) emits every variable type once into inputs.rb, with query modules aliasing what they use — the difference between hundreds of duplicated bool_exp structs and one copy per schema.
-
.load_generated!(path = nil) ⇒ Object
Load the generated modules — one line in an initializer or spec helper (loading happens only when you call this; skip it and require files yourself if you'd rather):.
-
.locate_schema! ⇒ Object
the conventional schema dump, required.
-
.log(level, &block) ⇒ Object
Internal: level-gated and lazy — the block only runs when a logger is listening.
-
.log_timed(level, label) ⇒ Object
Internal: run the block, logging "
-
.new(source, **options, &middleware) ⇒ Object
A client for one GraphQL server — transport, schema, and scoped scalars in one object (see Client):.
-
.parse(schema:, query:, name: nil, client: nil, scalars: nil, enums: nil, types: nil) ⇒ Object
Parse a query into a typed query module:.
- .queries_path ⇒ Object
- .queries_path=(path) ⇒ Object
-
.register_enum(graphql_name, type, map: nil, fallback: nil, requires: nil) ⇒ Object
Map a GraphQL enum onto an app-owned T::Enum, so generated code speaks YOUR enum — casting wire values in, serializing members out:.
-
.register_enums(mappings) ⇒ Object
Bulk, inference-only form: register_enums("Species" => PetKind, ...).
-
.register_scalar(graphql_name, type, cast: nil, serialize: nil, requires: nil, coerce: nil) ⇒ Object
Teach the generator how a GraphQL custom scalar deserializes into a rich Ruby object (and serializes back onto the wire when used as a variable):.
-
.register_transport_error(*classes) ⇒ Object
Add one or more exception classes to the transport-error set.
-
.register_type(graphql_name, *mixins, requires: nil, &block) ⇒ Object
Include app-owned helper modules into every struct generated from a GraphQL type — derived values live as methods next to the honest wire data, and srb tc checks them against each query's selection:.
-
.reset_scalars! ⇒ Object
Restore the built-in scalars, dropping every custom registration — the clean slate to reach for between tests or to undo overrides.
-
.resolve_transport(target) ⇒ Object
The transport behind a client-or-transport value: a Client resolves to its own transport, anything else already speaks execute.
-
.transport_errors ⇒ Object
The exception classes the bundled transports reclassify as TransportError — network-level failures where the request never reached the server.
-
.verify_generated!(schema: nil, queries: queries_path, output: generated_path, client: nil, shared_inputs: true, inputs_module: nil) ⇒ Object
The freshness guard: raise unless every generated file matches what the current schema + queries + scalar registrations would produce.
Class Attribute Details
.auto_coerce ⇒ Object
Default input coercion for scalars that don't say coerce: themselves, resolved lazily at generation time (so set it any time before you generate — no reset_scalars! ordering dance):
GraphWeaver.auto_coerce = true
Convertible built-ins take their conversion (Int accepts 5/"5"), and any scalar with a full cast/serialize pair (Date, your Money) accepts its raw wire form. An explicit coerce: true/false/Symbol on a registration always wins.
239 240 241 |
# File 'lib/graph_weaver.rb', line 239 def auto_coerce @auto_coerce end |
.client ⇒ Object
The app's default client — how generated modules find their server:
GraphWeaver.client = GraphWeaver.new(url, auth: token)
Accepts a Client or anything satisfying the execute contract (a schema class, a fake — testing's auto_fake swaps one in per example). Generated modules resolve per call -> per module (MyQuery.client=) -> baked constant -> here.
45 46 47 |
# File 'lib/graph_weaver.rb', line 45 def client @client end |
.generated_paths ⇒ Object
76 |
# File 'lib/graph_weaver.rb', line 76 def generated_paths = @generated_paths ||= ["app/graphql/generated", "app/graphql/*/generated"] |
.inputs_module(output = generated_path) ⇒ Object
99 100 101 102 103 104 105 106 107 108 109 110 |
# File 'lib/graph_weaver.rb', line 99 def inputs_module(output = generated_path) return @inputs_module if @inputs_module segments = File.(output.to_s).split(File::SEPARATOR) segments.pop if segments.last == "generated" parent = segments.last.to_s if parent.match?(/\A[a-zA-Z]\w*\z/) && !%w[graphql app lib spec support test].include?(parent) "#{Inflect.camelize(parent)}Inputs" else "GraphQLInputs" end end |
.logger ⇒ Object
Where GraphWeaver narrates what it's doing — anything stdlib-Logger-compatible (Logger, Rails.logger, semantic_logger...). Silent by default; Rails apps get Rails.logger wired by the railtie.
GraphWeaver.logger = Logger.new($stdout, level: Logger::INFO)
What logs where:
debug — full queries + variables on the wire, responses
(status/bytes/ms), connection lifecycle, parsed modules
info — schema introspection and cache decisions, generated files
written, query modules loaded
warn — every GraphWeaver error raised
Queries, variables, and responses appear at debug ONLY — they can carry PII. Auth headers never log.
21 22 23 |
# File 'lib/graph_weaver/logging.rb', line 21 def logger @logger end |
.queries_paths ⇒ Object
Entries may be glob patterns — the generated default also matches per-schema layouts (app/graphql/github/generated). Queries stay single-schema: load_queries! parses everything against one client.
75 |
# File 'lib/graph_weaver.rb', line 75 def queries_paths = @queries_paths ||= ["app/graphql/queries"] |
.schema_path ⇒ Object
89 |
# File 'lib/graph_weaver.rb', line 89 def schema_path = @schema_path || "app/graphql/schema.json" |
Class Method Details
.clear_scalars! ⇒ Object
Empty the scalar registry entirely, built-ins included (see reset_scalars! to restore the defaults).
312 313 314 |
# File 'lib/graph_weaver.rb', line 312 def clear_scalars! Codegen.clear_scalars! end |
.client! ⇒ Object
the default client, when one is required
48 49 50 |
# File 'lib/graph_weaver.rb', line 48 def client! @client or raise Error, "no client configured — set GraphWeaver.client= or pass a client" end |
.execute(source, query, **variables) ⇒ Object
One-shot dynamic execution — a throwaway client, no build step:
GraphWeaver.execute(schema, "query($id: ID!) { ... }", id: "1") # => Response
GraphWeaver.execute!(url, "query { viewer { login } }") # => Result (or raise)
The first argument is a url or schema source, exactly as GraphWeaver.new; this is Client#execute on a client you don't keep. (A url source introspects the schema on every call — keep a client for more than one query.) Variables are plain kwargs, as on a generated module (nothing reserved). execute returns the Response envelope, execute! the typed result, raising QueryError on top-level errors.
346 347 348 349 |
# File 'lib/graph_weaver.rb', line 346 def execute(source, query, **variables) client = source.is_a?(Client) ? source : Client.new(source) client.execute(query, **variables) end |
.execute!(source, query, **variables) ⇒ Object
execute + data! — the typed result, or a raised QueryError. See execute.
352 353 354 |
# File 'lib/graph_weaver.rb', line 352 def execute!(source, query, **variables) execute(source, query, **variables).data! end |
.generate!(schema: nil, queries: queries_path, output: generated_path, client: nil, shared_inputs: true, inputs_module: nil) ⇒ Object
Generate every .graphql query in a directory into checked-in Ruby files. Paths default to the conventions above; schema: defaults to the dump at schema_path (any supported extension):
GraphWeaver.generate! # queries_path -> generated_path
person.graphql => person_query.rb defining PersonQuery. Returns the written paths. Pair with a freshness spec (docs/generated_modules.md).
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 |
# File 'lib/graph_weaver.rb', line 120 def generate!(schema: nil, queries: queries_path, output: generated_path, client: nil, shared_inputs: true, inputs_module: nil) schema ||= locate_schema! inputs_module ||= self.inputs_module(output) plan = generation_plan(queries:, schema:, client:, shared_inputs:, inputs_module:) written = plan.map do |filename, source| target = File.join(output, filename) FileUtils.mkdir_p(File.dirname(target)) File.write(target, source) log(:info) { "generated #{target}" } target end # a type dropped from the schema must not linger as a stale file — # inputs/ is wholly generated, so pruning is safe (Dir[File.join(output, "inputs", "*.rb")] - written).each do |orphan| File.delete(orphan) log(:info) { "pruned #{orphan}" } end written end |
.generated_path ⇒ Object
79 |
# File 'lib/graph_weaver.rb', line 79 def generated_path = generated_paths.first |
.generated_path=(path) ⇒ Object
85 86 87 |
# File 'lib/graph_weaver.rb', line 85 def generated_path=(path) @generated_paths = path.nil? ? nil : [path] end |
.generation_plan(queries:, schema:, client:, shared_inputs:, inputs_module: self.inputs_module) ⇒ Object
(filename, source) per artifact: shared_inputs (the default) emits every variable type once into inputs.rb, with query modules aliasing what they use — the difference between hundreds of duplicated bool_exp structs and one copy per schema.
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 |
# File 'lib/graph_weaver.rb', line 199 def generation_plan(queries:, schema:, client:, shared_inputs:, inputs_module: self.inputs_module) namespace = shared_inputs ? inputs_module : nil used = { inputs: [], enums: [], mapped: [] } plan = Dir[File.join(queries, "*.graphql")].sort.map do |path| base = File.basename(path, ".graphql") codegen = Codegen.new( schema:, query: File.read(path), module_name: "#{Inflect.camelize(base)}Query", client:, inputs_namespace: namespace, ) source = codegen.generate codegen.variable_type_names.each { |kind, names| used[kind] |= names } ["#{base}_query.rb", source] end if namespace && used.values.any?(&:any?) shared = Codegen.generate_inputs( schema:, module_name: namespace, input_types: used[:inputs], enum_types: used[:enums] + used[:mapped], ) plan = shared.to_a + plan end plan end |
.load_generated!(path = nil) ⇒ Object
Load the generated modules — one line in an initializer or spec helper (loading happens only when you call this; skip it and require files yourself if you'd rather):
GraphWeaver.load_generated!
In Rails, prefer this over autoloading: Zeitwerk would expect Generated::PersonQuery from generated/person_query.rb, and generated code only changes on regeneration anyway (restart, like a schema migration).
180 181 182 183 184 185 186 |
# File 'lib/graph_weaver.rb', line 180 def load_generated!(path = nil) paths = path ? [path] : generated_paths files = paths.flat_map { |dir| Dir[File.join(dir, "**/*.rb")].sort }.uniq files.each { |file| require File.(file) } log(:info) { "loaded #{files.size} generated module(s) from #{paths.join(", ")}" } files end |
.locate_schema! ⇒ Object
the conventional schema dump, required
189 190 191 192 |
# File 'lib/graph_weaver.rb', line 189 def locate_schema! SchemaLoader.locate or raise Error, "no schema dump at #{schema_path} (.json/.graphql/.gql) — pass schema:, or cache one: GraphWeaver.new(url, cache: true).schema" end |
.log(level, &block) ⇒ Object
Internal: level-gated and lazy — the block only runs when a logger is listening. Messages carry "graph_weaver" as progname.
25 26 27 |
# File 'lib/graph_weaver/logging.rb', line 25 def log(level, &block) logger&.public_send(level, "graph_weaver", &block) end |
.log_timed(level, label) ⇒ Object
Internal: run the block, logging "
31 32 33 34 35 36 37 38 39 |
# File 'lib/graph_weaver/logging.rb', line 31 def log_timed(level, label) return yield unless logger start = Process.clock_gettime(Process::CLOCK_MONOTONIC) result = yield ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - start) * 1000).round log(level) { "#{label} (#{ms}ms)" } result end |
.new(source, **options, &middleware) ⇒ Object
A client for one GraphQL server — transport, schema, and scoped scalars in one object (see Client):
github = GraphWeaver.new("https://api.github.com/graphql", auth: token, cache: true)
RepoQuery = github.parse("queries/repo.graphql")
The first argument is a url or any schema source (a live schema class, or a path/SDL/introspection dump).
33 34 35 |
# File 'lib/graph_weaver.rb', line 33 def new(source, **, &middleware) Client.new(source, **, &middleware) end |
.parse(schema:, query:, name: nil, client: nil, scalars: nil, enums: nil, types: nil) ⇒ Object
Parse a query into a typed query module:
PersonQuery = GraphWeaver.parse(schema:, query: "queries/person.graphql")
query is a .graphql/.gql path (module name derived from the file name) or a raw query string (name derived from the operation name, falling back to "Query" for anonymous operations — collisions are impossible since each parse gets its own container). Pass name: to override, client: to bake the module's default client/transport.
325 326 327 328 329 330 331 332 |
# File 'lib/graph_weaver.rb', line 325 def parse(schema:, query:, name: nil, client: nil, scalars: nil, enums: nil, types: nil) if query.end_with?(".graphql", ".gql") name ||= "#{Inflect.camelize(File.basename(query, ".*"))}Query" query = File.read(query) end Codegen.parse(schema:, query:, module_name: name, client:, scalars:, enums:, types:) end |
.queries_path ⇒ Object
78 |
# File 'lib/graph_weaver.rb', line 78 def queries_path = queries_paths.first |
.queries_path=(path) ⇒ Object
81 82 83 |
# File 'lib/graph_weaver.rb', line 81 def queries_path=(path) @queries_paths = path.nil? ? nil : [path] end |
.register_enum(graphql_name, type, map: nil, fallback: nil, requires: nil) ⇒ Object
Map a GraphQL enum onto an app-owned T::Enum, so generated code speaks YOUR enum — casting wire values in, serializing members out:
GraphWeaver.register_enum("Species", PetKind)
The mapping is inferred by name ("CAT" <-> PetKind::Cat); map: pins renames, fallback: absorbs unknown wire values on cast (inputs stay strict), requires: names files the generated code should require. Generation fails naming any schema value that doesn't resolve — exhaustiveness checked ahead of runtime. Global; client.register_enum scopes to one client.
275 276 277 |
# File 'lib/graph_weaver.rb', line 275 def register_enum(graphql_name, type, map: nil, fallback: nil, requires: nil) Codegen.register_enum(graphql_name, type, map:, fallback:, requires:) end |
.register_enums(mappings) ⇒ Object
Bulk, inference-only form: register_enums("Species" => PetKind, ...)
280 281 282 |
# File 'lib/graph_weaver.rb', line 280 def register_enums(mappings) Codegen.register_enums(mappings) end |
.register_scalar(graphql_name, type, cast: nil, serialize: nil, requires: nil, coerce: nil) ⇒ Object
Teach the generator how a GraphQL custom scalar deserializes into a rich Ruby object (and serializes back onto the wire when used as a variable):
GraphWeaver.register_scalar("Money", Money, requires: "bigdecimal")
A field typed Money then generates const :price, T.nilable(Money)
and casts with Money.parse(...) in from_h. Pass a real class as
type: and cast:/serialize: are inferred from it — .parse/#to_s, or
.load/.dump — by probing the deserialize side (see ScalarType::CODECS).
Override with a Symbol method name (safest — no string to misspell), a
Proc(expr) => code string, or :itself to force pass-through. requires:
(a String or Array) names files the generated code needs — validated,
and actually required to confirm it resolves when type: is a real class.
coerce: true makes a variable of this scalar accept the value OR its
raw input (e.g. "12.00"), running the latter through the cast before
serializing — it raises on bad input, so some safety survives. Built-in
scalars are pre-registered the same way, so this also overrides them.
Call before generating.
260 261 262 |
# File 'lib/graph_weaver.rb', line 260 def register_scalar(graphql_name, type, cast: nil, serialize: nil, requires: nil, coerce: nil) Codegen.register_scalar(graphql_name, type, cast:, serialize:, requires:, coerce:) end |
.register_transport_error(*classes) ⇒ Object
Add one or more exception classes to the transport-error set.
56 57 58 59 |
# File 'lib/graph_weaver/errors.rb', line 56 def register_transport_error(*classes) transport_errors.merge(classes) classes end |
.register_type(graphql_name, *mixins, requires: nil, &block) ⇒ Object
Include app-owned helper modules into every struct generated from a GraphQL type — derived values live as methods next to the honest wire data, and srb tc checks them against each query's selection:
GraphWeaver.register_type("Pet", PetHelpers)
Or build the mixin inline with a block (module_eval'd into an auto-named module — quick, but invisible to srb tc):
GraphWeaver.register_type("Pet") do
def display_name = "#{name} the pet"
end
Additive (repeated and client-scoped registrations stack). Global; client.register_type scopes to one client.
299 300 301 |
# File 'lib/graph_weaver.rb', line 299 def register_type(graphql_name, *mixins, requires: nil, &block) Codegen.register_type(graphql_name, *mixins, requires:, &block) end |
.reset_scalars! ⇒ Object
Restore the built-in scalars, dropping every custom registration — the clean slate to reach for between tests or to undo overrides. (Coercible built-ins are auto_coerce's job, not a reset flavor.)
306 307 308 |
# File 'lib/graph_weaver.rb', line 306 def reset_scalars! Codegen.reset_scalars! end |
.resolve_transport(target) ⇒ Object
The transport behind a client-or-transport value: a Client resolves to its own transport, anything else already speaks execute. Generated modules call this on every execute, so any slot in the resolution chain can hold either kind.
56 57 58 |
# File 'lib/graph_weaver.rb', line 56 def resolve_transport(target) target.is_a?(Client) ? target.transport! : target end |
.transport_errors ⇒ Object
The exception classes the bundled transports reclassify as TransportError — network-level failures where the request never reached the server. A mutable Set: each transport contributes its own on load (net/http adds Timeout/SSL, Faraday adds its ConnectionFailed, …), and you can add more so they get the same handling:
GraphWeaver.transport_errors << MyPool::TimeoutError
GraphWeaver.register_transport_error(Adapter::ResetError)
SystemCallError covers every Errno::* (connection refused/reset, host unreachable); SocketError covers DNS.
51 52 53 |
# File 'lib/graph_weaver/errors.rb', line 51 def transport_errors @transport_errors ||= Set[SocketError, SystemCallError, IOError] end |
.verify_generated!(schema: nil, queries: queries_path, output: generated_path, client: nil, shared_inputs: true, inputs_module: nil) ⇒ Object
The freshness guard: raise unless every generated file matches what
the current schema + queries + scalar registrations would produce.
One line in a spec, or rake graph_weaver:verify in CI:
it "generated queries are current" do
GraphWeaver.verify_generated!
end
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 |
# File 'lib/graph_weaver.rb', line 151 def verify_generated!(schema: nil, queries: queries_path, output: generated_path, client: nil, shared_inputs: true, inputs_module: nil) schema ||= locate_schema! inputs_module ||= self.inputs_module(output) plan = generation_plan(queries:, schema:, client:, shared_inputs:, inputs_module:) stale = plan.filter_map do |filename, source| target = File.join(output, filename) target unless File.exist?(target) && File.read(target) == source end # strays: a type file the current schema no longer produces stale += Dir[File.join(output, "inputs", "*.rb")] - plan.map { |f, _| File.join(output, f) } unless stale.empty? raise Error, "stale generated queries — regenerate (rake graph_weaver:generate): #{stale.join(", ")}" end true end |