GraphQL interop#

Meta: this is the page that justifies the language. Lead with "schema-as-stdlib" — when you import Dagger, every type and root function in the schema becomes part of the language. Import wiring (dang.toml, import) lives in Modules and imports; type machinery in Types and nullability; record/object access in Objects (type).

The examples on this page are live: they share one Dang environment, so later snippets use earlier definitions. Each result is computed and baked in by the docs build — edit a snippet and hit Run ▶ to replay the page in your browser. Blocks that show an error are supposed to fail: the build verifies the failure the same way it verifies the results.

They run against Demo, a small GraphQL schema bundled with the docs and served in-process. Each request it receives is printed as → query …, so you can see exactly what a snippet sends.

Schema-as-stdlib#

import Demo

hello(name: "Dang")
→ query Query {hello(name:"Dang")}
=> "Hello, Dang!"

Calling a field#

Arguments are named as in the schema, or positional in the schema's order:

posts(authorId: "User:2", limit: 1).{{ title }}.map { _.title }
→ query Query {posts(authorId:"User:2", limit:1){title}}
=> ["Second Post"]
posts(null, 2).{{ title }}.map { _.title }
→ query Query {posts(authorId:null, limit:2){title}}
=> ["First Post", "Second Post"]

A field with no required arguments is called without parentheses:

serverInfo.version
→ query Query {serverInfo{version}}
=> "1.0.0"

Multi-field selection#

A selection reads several fields in one GraphQL query:

let ada = user(id: "User:1").{{ name, emails }}

ada.emails
→ query Query {user(id:"User:1"){name emails}}
=> ["john@example.com", "john.doe@work.com"]

A field may be aliased to rename it in the result, GraphQL-style: the alias goes before the colon. A bare field is shorthand for aliasing it to itself, so user.{{ name }} means user.{{ name: name }}, exactly as {{ name }} is shorthand for {{ name: name }} in a record literal (see Objects (type)):

user(id: "User:1").{{ fullName: name }}.fullName
→ query Query {user(id:"User:1"){fullName:name}}
=> "John Doe"

Aliases are sent as real GraphQL aliases, so the same field can be selected more than once with different arguments. Nested fields take arguments like any call:

let pages = user(id: "User:1").{{
  earliest: posts(first: 1).{{ posts.{{ title }} }}
  latest: posts(last: 1).{{ posts.{{ title }} }}
}}

[pages.earliest.posts[0]!.title, pages.latest.posts[0]!.title]
→ query Query {user(id:"User:1"){earliest:posts(first:1){posts{title}} latest:posts(last:1){posts{title}}}}
=> ["First Post", "Sixth Post"]

A selection on a nullable receiver short-circuits: if the receiver is null, the selection is null (not an error), and its type is nullable. maybeUser returns null for an unknown ID:

maybeUser(id: "User:99").{{ name }}
→ query Query {maybeUser(id:"User:99"){name}}
=> null

The result is a record holding only what you selected. Reading a field you didn't select is a compile error, even after a case narrows the type:

user(id: "User:1").{{ name }}.emails
Type error: field "emails" not found in {name: String!}

.{{ }} selection is navigation (it reads fields), so it short-circuits on null; the single-brace dot-block .{ } is block application, so it passes the receiver — null included — into the block. Same .-brace surface, different jobs; see Blocks's Dot-block application (piping).

Inline fragments#

An inline fragment selects fields by concrete type, on unions and interfaces (Interfaces and unions). Fragments are separated by newlines or commas, and the result narrows in case:

let hit = node(id: "Post:1").{{
  ... on User {{ name }}
  ... on Post {{ title }}
}}

case (hit) {
  u: User! => `user ${u.name}`
  p: Post! => `post ${p.title}`
}
→ query Query {node(id:"Post:1"){__typename ... on User { name } ... on Post { title }}}
=> "post First Post"

Lazy inline fragments#

The lazy form ... on Post (no field block) narrows the value to that type without selecting anything. You can keep chaining off the result:

node(id: "Post:1").{{ ... on Post }}.title
→ query Query {node(id:"Post:1"){__typename}} → query Query {node(id:"Post:1"){... on Post{title}}}
=> "First Post"

A narrowing that doesn't match is null, and so is one on a null value:

node(id: "Post:1").{{ ... on User }} == null
→ query Query {node(id:"Post:1"){__typename}}
=> true

The non-null form ... on User! asserts and unwraps instead. A mismatch, or a null value, is a runtime error:

node(id: "Post:1").{{ ... on User! }}.name
→ query Query {node(id:"Post:1"){__typename}}
Runtime error: evaluating receiver: inline fragment type assertion failed: expected one of User, got Post

Lists of objects#

A selection on a list distributes over its elements. This is the shape GraphQL itself produces: users.{{ name }} mirrors the response of { users { name } }, a list of records:

users.{{ name }} == [{{ name: "John Doe" }}, {{ name: "Jane Smith" }}]
→ query Query {users{name}}
=> true

The result records compare by value (Operators), as above. The result is an ordinary list: index it, or chain list methods (see Collections):

users.{{ name }}.map { _.name }
→ query Query {users{name}}
=> ["John Doe", "Jane Smith"]

Nested selections distribute the same way, giving each record its own list:

users.{{ name, posts.{{ posts.{{ title }} }} }}.map { u => `${u.name}: ${u.posts.posts.length}` }
→ query Query {users{name posts{posts{title}}}}
=> ["John Doe: 4", "Jane Smith: 2"]

.{{ … }} and .field do different jobs on a list: .{{ … }} reaches into each element, while .field looks for a list method. List methods like .length and .map aren't available on a list of GraphQL objects until you select the fields you need:

users.length
Type error: cannot call list method "length" directly on a GraphQL object list; select fields on its elements first, e.g. value.{{id}}.length
users.{{ id }}.length
→ query Query {users{id}}
=> 2

Mutations#

Side effects happen when the call executes, which is when its value is forced, and every forced selection off an object-returning mutation sends it again. Demo's touchNode changes nothing, so it's safe to watch: let touched = … sends nothing, and each read of touched.id sends the mutation once more:

let touched = Mutation.touchNode(id: "User:1")

[touched.id, touched.id]
→ mutation Mutation {touchNode(id:"User:1"){id}} → mutation Mutation {touchNode(id:"User:1"){id}}
=> ["User:1", "User:1"]

Select everything you need in one .{{ }} on the call to run it exactly once:

Mutation.touchNode(id: "User:1").{{ id }}.id
→ mutation Mutation {touchNode(id:"User:1"){id}}
=> "User:1"

Laziness: GraphQL field access in Dang is lazy. A GraphQLValue accumulates a query chain (.field, .{{...}} selections, args); no request is sent until the value is forced — i.e. materialized at an expected-type boundary (assertion, print, assignment to a typed field, indexing into a result, etc.). Forcing runs the built-up selection as a single Execute against the endpoint. This is the desugaring that makes user.{{ name, posts.{{ title }} }} one round-trip. Two exceptions send a small query early: a handle that may be null is checked when it escapes the chain (see Nullable object fields), and case asks for the concrete type of an interface or union value it matches type patterns against (see Interfaces and unions). See Mutation and copy-on-write for how forcing interacts with side effects. Showing an object handle (print, toString, interpolation, List.join, the REPL) doesn't force it: it renders the lazy query it is, its type and the chain it holds, <Container: container.from(address: …).withEnv(name: …, value: …)>; a mutation's result shows as <Type: mutation.field(…)>. Argument values are never shown, only their names, since any of them could be a secret. Select .id for the ID.

Nullable object fields#

A field returning a nullable object, interface or union (manager: User, not User!) may be null. So a handle to it is checked when it escapes the chain: when it's bound with let, passed as an argument, returned, compared, and so on. The check is one small query, so the value is either null or a handle known to be non-null, and == null, ??, !, null patterns in case, and flow narrowing (Flow-sensitive narrowing) all behave as written:

let boss = user(id: "User:2").manager
if (boss == null) {
  raise "no manager"
}

boss.name
→ query Query {user(id:"User:2"){manager{id __typename}}} → query Query {node(id:"User:1"){... on User{name}}}
=> "John Doe"

The check fetched the manager's id, and boss.name then started from node(id:) rather than re-running the chain.

A field that is only selected through isn't checked: whatever runs the chain reveals the null itself. User 1 has no manager, so this is null, in one round trip:

user(id: "User:1").manager.name
→ query Query {user(id:"User:1"){manager{name}}}
=> null

Object equality#

== and != compare GraphQL objects by reference identity. The comparison itself sends nothing (though a nullable operand is checked for null first, as above). A GraphQL object's identity is the query that produced it, so the same handle equals itself, but two independent queries don't, even when they denote the same server object. To ask whether two objects are the same server entity, compare an identifying field, which runs the fetch where you can see it. primaryUser is a non-null User!, so only the id reads send anything here:

let first = primaryUser

[first == first, first == primaryUser, first.id == user(id: "User:1").id]
→ query Query {primaryUser{id}} → query Query {user(id:"User:1"){id}}
=> [true, false, true]

A .{{ }} selection is different: it makes an anonymous record, which compares by value (see Operators):

primaryUser.{{ name }} == user(id: "User:1").{{ name }}
→ query Query {primaryUser{name}} → query Query {user(id:"User:1"){name}}
=> true

Errors from the server#

Non-null violations and GraphQL errors raise, and rescue can recover from them (see Errors: raise and rescue):

user(id: "User:99").name
→ query Query {user(id:"User:99"){name}}
Runtime error: executing GraphQL query for User.user.name: input: user user not found
user(id: "User:1").alwaysFails rescue { e: GraphQLError! => e.message }
→ query Query {user(id:"User:1"){alwaysFails}}
=> "this field always fails"

Talking to multiple endpoints#

The qualified name always works, even with only one import:

let viewer: Demo.User! = primaryUser
viewer.name
→ query Query {primaryUser{name}}
=> "John Doe"