← Writing
boxlang bx-express coldbox

bx-graphql 0.2: A GraphQL API from the Classes You Already Have

bx-graphql 0.2 adds a code-first way to build GraphQL APIs in BoxLang: annotate the beans and services you already have, and the module generates the schema and wires each field to its function. This post builds a small bookshelf app that uses every new feature: types and inputs from beans, queries and mutations from services, enums, interfaces and unions, custom scalars, authorization, batch loading and structured errors. Schema-first apps keep working unchanged.

bx-graphql wraps graphql-java for BoxLang. Until now it worked one way: you wrote the schema in .graphqls files and a resolver class per type. That's how Feedhouse's admin API is built, and it still works exactly as it did.

Version 0.2.0 adds a second way. You annotate the beans and services your app already has, and the module generates the schema and wires each field to the function it came from. The two ways mix, so you can adopt it one type at a time.

Here's what's new:

  • Types and inputs from beans, a field per property, doc comments as descriptions.
  • Queries and mutations from service functions, with inputs arriving as populated beans.
  • Functions as fields, for values that are worked out rather than stored.
  • Enums, interfaces and unions.
  • Custom scalars, with DateTime and Long built in.
  • Authorization by annotation.
  • Batch loading, so a list of 50 books doesn't make 50 author lookups.
  • Structured errors, which replaces the regex I complained about in the last post.
  • An instance factory, so services can be built by your own DI.

The rest of this post builds one small app that uses all of them: a bookshelf. Every file is here in full, and every response below was copied from the running app.

The app

bookshelf/
  app.bxs               builds the engine, serves POST /graphql
  box.json
  models/
    Book.bx             type + input
    BookChanges.bx      input only
    Review.bx           type + input
    Author.bx           type
    Status.bx           enum
  services/
    BookService.bx      queries and mutations
    AdminService.bx     guarded queries
    Library.bx          the data, in memory
  schema/
    shared.graphqls     the parts written by hand
  resolvers/
    BookResolver.bx     one hand-written field

box.json installs the two modules into the app's own boxlang_modules folder:

{
	"name": "bookshelf",
	"version": "0.1.0",
	"private": true,
	"dependencies": {
		"boxlang-express": "^0.2.29",
		"bx-graphql": "^0.2.0"
	},
	"installPaths": {
		"boxlang-express": "boxlang_modules/boxexpress/",
		"bx-graphql": "boxlang_modules/bxgraphql/"
	}
}
box install

A bean becomes a type and an input

This is models/Book.bx. It's an ordinary class with accessors. The annotations are the only part that knows about GraphQL.

/** A book on the shelf. */
@graphqlType
@graphqlInput
@graphqlImplements( "Named" )
class accessors="true" {

	@graphqlId
	@graphqlReadOnly
	property name="id" type="numeric";

	/** The title. */
	property name="name" type="string" required="true";

	@graphqlField( "Isbn" )
	property name="isbn" type="string";

	property name="pages" type="integer";

	@graphqlField( "Status" )
	property name="status" type="string";

	@graphqlReadOnly
	property name="addedAt" type="date";

	/** Who wrote it. Given when adding a book; read back through `author`. */
	@graphqlWriteOnly
	@graphqlInputField( "ID!" )
	property name="authorId" type="numeric";

	@graphqlField( "[Review!]!" )
	@graphqlInputField( "[ReviewInput!]" )
	property name="reviews" type="array";

	@graphqlIgnore
	property name="privateNote" type="string";

	/** Who wrote it. */
	@graphqlField( "Author" )
	function author( any env ){
		return arguments.env.getDataLoader( "authors" ).load( variables.authorId );
	}

	/** The mean of its reviews' ratings; null with none. */
	@graphqlField
	numeric function averageRating(){
		if( !arrayLen( variables.reviews ?: [] ) ){
			return javaCast( "null", "" );
		}
		return variables.reviews.reduce( ( total, review ) => total + review.getRating(), 0 ) / arrayLen( variables.reviews );
	}

	/**
	 * How long it takes to read.
	 *
	 * @pagesPerHour How fast you read.
	 */
	@graphqlField
	numeric function hoursToRead( numeric pagesPerHour = 40 ){
		return isNull( variables.pages ) ? javaCast( "null", "" ) : round( variables.pages / arguments.pagesPerHour * 10 ) / 10;
	}

	@graphqlField
	@graphqlRequires( "admin" )
	string function note(){
		return variables.privateNote ?: "";
	}

}

From that one file the module generates both of these:

"""A book on the shelf."""
type Book implements Named {
	id: ID
	"""The title."""
	name: String!
	isbn: Isbn
	pages: Int
	status: Status
	addedAt: DateTime
	reviews: [Review!]!
	"""Who wrote it."""
	author: Author
	"""The mean of its reviews' ratings; null with none."""
	averageRating: Float
	"""How long it takes to read."""
	hoursToRead(
		"""How fast you read."""
		pagesPerHour: Float! = 40
	): Float
	note: String
}

"""A book on the shelf."""
input BookInput {
	"""The title."""
	name: String!
	isbn: Isbn
	pages: Int
	status: Status
	"""Who wrote it. Given when adding a book; read back through `author`."""
	authorId: ID!
	reviews: [ReviewInput!]
}

Only annotated classes are exposed. @graphqlType makes the output type and @graphqlInput the input. A class with neither is invisible to the API, however many properties it has.

Property types map themselves where they can. string, boolean, integer, numeric and date become String, Boolean, Int, Float and DateTime. Another annotated class maps to its type, or to its input when it's used inside an input. required="true" adds the !.

Where they can't, you say. An array could hold anything, so reviews states its type in both directions: @graphqlField( "[Review!]!" ) going out and @graphqlInputField( "[ReviewInput!]" ) coming in. Leave that off and the app won't start. The error names the property and the annotation it wants.

Four annotations decide where a property appears:

AnnotationIn the typeIn the input
noneyesyes
@graphqlReadOnlyyesno
@graphqlWriteOnlynoyes
@graphqlIgnorenono

id and addedAt are set by the app, so they're read-only. authorId is something you send, and read back as a whole Author, so it's write-only. privateNote never appears at all.

Doc comments are the documentation. The class's comment becomes the type's description, a property's comment its field's, and a @pagesPerHour line the argument's. Tools like GraphiQL show them, and they're written once, next to the code.

Review is the same idea at its smallest:

/** What a reader thought. */
@graphqlType
@graphqlInput
class accessors="true" {

	/** One to five. */
	property name="rating" type="integer" required="true";

	property name="text" type="string";

}

And Author, which is only ever read:

/** Someone who wrote a book on the shelf. */
@graphqlType
@graphqlImplements( "Named" )
class accessors="true" {

	@graphqlId
	property name="id" type="numeric";

	property name="name" type="string" required="true";

}

Enums

BoxLang has no enum type, so an enum is a class with nothing in it but its values:

/** Where a book is in your reading. */
@graphqlEnum( "WANT, READING, FINISHED" )
class {
}

The values are strings on the BoxLang side. That's why Book.status is typed string and names the enum with @graphqlField( "Status" ). If you type the property as the class (type="Status"), BoxLang would refuse the string "READING" at runtime, so the module refuses it at startup instead and tells you what to write.

GraphQL does the checking from then on. This never reaches your code:

{ books( status: LOST ) { name } }
{ "errors": [ { "message": "Validation error (WrongType@[books]) : argument 'status' with value 'EnumValue{name='LOST'}' is not a valid 'Status' - Literal value not in allowable values for enum 'Status' - 'EnumValue{name='LOST'}'" } ] }

Functions become fields

Three of Book's fields aren't stored anywhere. @graphqlField on a public function makes it a field of the type, called on the bean when a query asks for it.

Parameters become arguments. hoursToRead( numeric pagesPerHour = 40 ) generates hoursToRead( pagesPerHour: Float! = 40 ): Float, default included:

{ book( id: 2 ) { name hoursToRead fast: hoursToRead( pagesPerHour: 80 ) } }
{ "data": { "book": { "name": "Dune", "hoursToRead": 15.3, "fast": 7.7 } } }

The return type comes from the function, or from the annotation's value when the function can't say. author() returns a promise (more on that below), so it states @graphqlField( "Author" ).

These functions stay out of BookInput. An input only ever has properties.

Services become queries and mutations

services/BookService.bx is the whole public API:

class accessors="true" {

	property name="library";

	/** One book by id. */
	@graphqlQuery
	Book function book( required numeric id graphqlType="ID!" ){
		return variables.library.book( arguments.id );
	}

	/**
	 * The shelf, newest first.
	 *
	 * @status Only books in this state.
	 * @limit How many at most.
	 */
	@graphqlQuery
	@graphqlReturns( "[Book!]!" )
	array function books( string status graphqlType="Status", integer limit = 20 ){
		var wanted = arguments.status ?: "";
		var found  = variables.library.books().filter( ( book ) => !len( wanted ) || book.getStatus() == wanted );
		found = found.reverse();
		return arrayLen( found ) > arguments.limit ? found.slice( 1, arguments.limit ) : found;
	}

	/** Books and authors whose name contains the text. */
	@graphqlQuery
	@graphqlReturns( "[SearchResult!]!" )
	array function search( required string text ){
		var text  = arguments.text;
		var found = variables.library.books().filter( ( book ) => findNoCase( text, book.getName() ) > 0 );
		return found.append( variables.library.authors().filter( ( author ) => findNoCase( text, author.getName() ) > 0 ), true );
	}

	/** Everything with a name, in one list. */
	@graphqlQuery
	@graphqlReturns( "[Named!]!" )
	array function everything(){
		return [].append( variables.library.authors(), true ).append( variables.library.books(), true );
	}

	@graphqlMutation
	Book function addBook( required Book input ){
		if( !variables.library.hasAuthor( arguments.input.getAuthorId() ) ){
			throw( type = "Bookshelf.Invalid", message = "Author #arguments.input.getAuthorId()# not found" );
		}
		return variables.library.addBook( arguments.input );
	}

	/** Changes only what `changes` holds. */
	@graphqlMutation
	Book function updateBook( required numeric id graphqlType="ID!", required BookChanges changes, struct args ){
		var book  = variables.library.book( arguments.id );
		var given = structKeyArray( arguments.args.changes );
		if( arrayContainsNoCase( given, "name" ) ){
			if( isNull( arguments.changes.getName() ) ){
				throw( type = "Bookshelf.Invalid", message = "A book needs a name" );
			}
			book.setName( arguments.changes.getName() );
		}
		if( arrayContainsNoCase( given, "pages" ) ){
			book.setPages( arguments.changes.getPages() ?: javaCast( "null", "" ) );
		}
		if( arrayContainsNoCase( given, "status" ) ){
			book.setStatus( arguments.changes.getStatus() ?: "WANT" );
		}
		return book;
	}

	@graphqlMutation
	Book function review( required numeric id graphqlType="ID!", required Review review ){
		if( arguments.review.getRating() < 1 || arguments.review.getRating() > 5 ){
			throw( type = "Bookshelf.Invalid", message = "A rating is 1 to 5" );
		}
		var book = variables.library.book( arguments.id );
		book.getReviews().append( arguments.review );
		return book;
	}

	@graphqlMutation
	@graphqlRequires( "admin" )
	@graphqlReturns( "Boolean!" )
	boolean function removeBook( required numeric id graphqlType="ID!" ){
		variables.library.removeBook( arguments.id );
		return true;
	}

}

It generates:

type Query {
	"""One book by id."""
	book( id: ID! ): Book
	"""The shelf, newest first."""
	books(
		"""Only books in this state."""
		status: Status
		"""How many at most."""
		limit: Int! = 20
	): [Book!]!
	"""Books and authors whose name contains the text."""
	search( text: String! ): [SearchResult!]!
	"""Everything with a name, in one list."""
	everything: [Named!]!
}

type Mutation {
	addBook( input: BookInput! ): Book
	"""Changes only what `changes` holds."""
	updateBook( id: ID!, changes: BookChangesInput! ): Book
	review( id: ID!, review: ReviewInput! ): Book
	removeBook( id: ID! ): Boolean!
}

The signature is the schema. The function's name is the field's name. Each parameter is an argument, required adds !, and the declared return type becomes the field's type. Nothing is registered anywhere else: a public function without an annotation, like a helper, isn't part of the API.

Two escape hatches for types BoxLang can't express. graphqlType="ID!" on a parameter states that argument's type word for word. @graphqlReturns( "[Book!]!" ) does the same for the return, which a function returning array always needs.

Nothing is generated from a bean alone. There's no automatic createBook or deleteBook. A bean says what a book looks like, not how it's saved, and I'd rather write addBook than have the module guess.

Inputs arrive as beans

addBook takes required Book input. By the time the function runs, input is a real Book: the module made one and called a setter for each key the caller sent. That includes the nested list. reviews arrives as an array of Review instances, because @graphqlInputField( "[ReviewInput!]" ) says what's in it.

mutation( $book: BookInput! ) {
	addBook( input: $book ) { id name isbn status author { name } link }
}
{ "book": {
	"name": "The Dispossessed", "isbn": "978-0-06-051275-5", "pages": 387, "authorId": 1,
	"reviews": [ { "rating": 5, "text": "Still thinking about it." } ]
} }
{ "data": { "addBook": {
	"id": "1",
	"name": "The Dispossessed",
	"isbn": "9780060512755",
	"status": "WANT",
	"author": { "name": "Ursula K. Le Guin" },
	"link": "https://openlibrary.org/isbn/9780060512755"
} } }

So the service gets to call arguments.input.getAuthorId() instead of digging through a struct, and hands the same object to the store.

Partial updates: null versus left out

An update needs to tell "set pages to nothing" from "don't touch pages". On the bean both read as null. For that there's a third injected parameter, args, which holds the arguments as plain structs exactly as the caller sent them.

BookChanges is an input-only bean with every field optional:

/** The parts of a book to change. Leave one out to keep it; give null to clear it. */
@graphqlInput
class accessors="true" {

	property name="name" type="string";
	property name="pages" type="integer";

	@graphqlField( "Status" )
	property name="status" type="string";

}

updateBook reads the keys of args.changes to see what was sent, and the bean for the values. One BoxLang trap to know: structKeyExists() is false for a key whose value is null, so the function looks in structKeyArray() instead.

mutation( $c: BookChangesInput! ) { updateBook( id: 3, changes: $c ) { name pages status } }
{ "c": { "status": "FINISHED", "pages": null } }
{ "data": { "updateBook": { "name": "The Lathe of Heaven", "pages": null, "status": "FINISHED" } } }

The name wasn't sent, so it was kept. Pages was sent as null, so it was cleared.

Defaults, and one rule about null

A default that's a plain string, number or boolean is written into the schema: integer limit = 20 becomes limit: Int! = 20.

Notice the !. BoxLang gives a parameter its default whenever it receives null, however the null is passed. So books( limit: null ) could never mean "no limit": the function would quietly get 20. Rather than let that happen, an argument with a default is non-null. You can leave it out, but you can't null it:

{ "errors": [ { "message": "Validation error (WrongType@[books]) : argument 'limit' with value 'NullValue{}' must not be null" } ] }

status has no default, so it stays nullable, and a null reaches the function as null.

context and env

A parameter named context receives whatever the route passed to execute(), and one named env receives graphql-java's DataFetchingEnvironment. Neither shows up in the schema. Book.author( any env ) uses the second one to reach a loader.

Batch loading

Ask for ten books and each one's author, and the obvious code looks up an author ten times. Book.author() doesn't look anything up. It asks a loader for one key and returns the promise it gets back:

@graphqlField( "Author" )
function author( any env ){
	return arguments.env.getDataLoader( "authors" ).load( variables.authorId );
}

graphql-java collects every key asked for across that level of the query, drops the repeats, and calls the loader once. The loader is one line in the settings (shown in full below):

"loaders" : {
	"authors" : ( ids, context ) => library.authorsByIds( ids )
}

It returns a struct of values by key, or an array in the same order as the keys. The app counts its lookups so you can check: after one mutation and this query over three books by two authors, the count was 2, one per request.

{ books { name status averageRating hoursToRead author { name } } }
{ "data": { "books": [
	{ "name": "The Lathe of Heaven", "status": "WANT", "averageRating": null, "hoursToRead": 4.6, "author": { "name": "Ursula K. Le Guin" } },
	{ "name": "Dune", "status": "READING", "averageRating": null, "hoursToRead": 15.3, "author": { "name": "Frank Herbert" } },
	{ "name": "The Dispossessed", "status": "WANT", "averageRating": 5, "hoursToRead": 9.7, "author": { "name": "Ursula K. Le Guin" } }
] } }

Loaded values last for one request, so nothing stale carries over.

The parts written by hand

Not everything is worth generating. schema/shared.graphqls holds what's easier to write directly, and the module merges it with the generated schema:

"Anything with a name."
interface Named {
	name: String!
}

union SearchResult = Book | Author

"An ISBN-10 or ISBN-13, hyphens optional."
scalar Isbn

type Stats {
	books: Int!
	authors: Int!
	authorLookups: Int!
	asOf: DateTime!
}

extend type Book {
	"Where to find it on Open Library."
	link: String
}

Interfaces and unions

Interfaces and unions are declared here, in SDL. A generated type joins an interface with @graphqlImplements( "Named" ), and joins a union by being listed in it.

When a field returns one, something has to say which concrete type each value is. For a bean, the module answers from its class, so search() just returns a mixed array of Book and Author instances:

{ search( text: "he" ) {
	__typename
	... on Book { name pages }
	... on Author { id name }
} }
{ "data": { "search": [
	{ "__typename": "Book", "name": "The Dispossessed", "pages": 387 },
	{ "__typename": "Book", "name": "The Lathe of Heaven", "pages": 184 },
	{ "__typename": "Author", "id": "2", "name": "Frank Herbert" }
] } }

If you return structs instead, add a __typename key. For anything cleverer, a SearchResultResolver.bx with a resolveType( value ) function gets the final say.

A type with no class

Stats is plain SDL, and AdminService.stats() returns a plain struct with matching keys. That's the original bx-graphql behaviour, and it's still the least code when there's no bean to annotate.

A hand-written field on a generated type

extend type Book { link: String } adds a field to the generated Book, and resolvers/BookResolver.bx resolves it by the old convention:

class {

	function link( required any source ){
		return isNull( arguments.source.getIsbn() ) ? javaCast( "null", "" ) : "https://openlibrary.org/isbn/" & arguments.source.getIsbn();
	}

}

In this app I could have made link a @graphqlField function on the bean. The point is that you don't have to convert everything: an existing schema and its resolvers keep working while new types are generated beside them.

Custom scalars

A scalar in the schema needs to know how to read and write its values. Isbn accepts hyphens and spaces, checks the length, and hands the service a clean string:

"scalars" : {
	"Isbn" : {
		"serialize"  : ( value ) => value,
		"parseValue" : ( value ) => {
			var digits = reReplace( value, "[\s-]", "", "all" )
			if ( !reFind( "^(\d{9}[\dXx]|\d{13})$", digits ) ) {
				throw( message = "'#value#' isn't an ISBN-10 or ISBN-13" )
			}
			return ucase( digits )
		}
	}
}

That's why "978-0-06-051275-5" came back as "9780060512755" above. Whatever parseValue returns is what your function receives, so a scalar can just as well return a date or a BigDecimal. A bad value is refused before any of your code runs:

{ "errors": [ { "message": "Validation error (WrongType@[addBook]) : argument 'input.isbn' with value 'StringValue{value='12345'}' is not a valid 'Isbn' - Isbn: '12345' isn't an ISBN-10 or ISBN-13" } ] }

DateTime and Long need no configuration. Book.addedAt is typed date, so the module declares scalar DateTime itself and writes any BoxLang or Java date as a UTC instant, such as 2026-11-26T15:49:24.230935Z.

Authorization

@graphqlRequires( "admin" ) guards a field. It goes on a service function (removeBook), on a bean's field function (Book.note), or on a whole class:

@graphqlRequires( "admin" )
class accessors="true" {

	property name="library";

	/** Counts, for whoever runs the shelf. */
	@graphqlQuery
	@graphqlReturns( "Stats" )
	struct function stats(){
		return {
			"books"         : arrayLen( variables.library.books() ),
			"authors"       : arrayLen( variables.library.authors() ),
			"authorLookups" : variables.library.authorLookups(),
			"asOf"          : now()
		};
	}

}

The module doesn't decide what "admin" means. Before a guarded function is called, it asks the authorizer you supply, passing the annotation's value and the request's context:

"authorizer" : ( requirement, context, info ) => arrayContains( context.roles, requirement )

A refused field comes back null with an error, and the rest of the query still runs. Without the role:

{ stats { books } book( id: 1 ) { name note } }
{
	"data": { "stats": null, "book": { "name": "The Dispossessed", "note": null } },
	"errors": [
		{ "message": "Not authorized: Query.stats", "path": [ "stats" ], "extensions": { "type": "BxGraphQL.NotAuthorized", "classification": "DataFetchingException" } },
		{ "message": "Not authorized: Book.note", "path": [ "book", "note" ], "extensions": { "type": "BxGraphQL.NotAuthorized", "classification": "DataFetchingException" } }
	]
}

With it:

{ "data": { "stats": { "books": 3, "authors": 2, "authorLookups": 2 }, "book": { "note": "Added through the API" } } }

Two details. A guard on a parent class covers the functions its children expose. And if anything is marked @graphqlRequires but there's no authorizer, the app refuses to start, so a guard can't be silently ignored.

Guards are for functions. A plain property can't carry one, which is why the private note is exposed through note() and the property itself is @graphqlIgnore.

Wiring it up

app.bxs builds the engine once and serves it with BoxExpress:

library = new services.Library()

graph = bxGraphQL( {
	"modelPaths"          : [ expandPath( "./models" ) ],
	"servicePaths"        : [ expandPath( "./services" ) ],
	"schemaPaths"         : [ expandPath( "./schema" ) ],
	"resolverBasePackage" : expandPath( "./resolvers" ),

	"instanceFactory" : ( classPath, meta, kind ) => {
		var instance = new "#meta.name#"()
		if ( kind == "service" ) {
			instance.setLibrary( library )
		}
		return instance
	},

	"scalars" : {
		"Isbn" : {
			"serialize"  : ( value ) => value,
			"parseValue" : ( value ) => {
				var digits = reReplace( value, "[\s-]", "", "all" )
				if ( !reFind( "^(\d{9}[\dXx]|\d{13})$", digits ) ) {
					throw( message = "'#value#' isn't an ISBN-10 or ISBN-13" )
				}
				return ucase( digits )
			}
		}
	},

	"authorizer" : ( requirement, context, info ) => arrayContains( context.roles, requirement ),

	"loaders" : {
		"authors" : ( ids, context ) => library.authorsByIds( ids )
	},

	"structuredErrors" : true,
	"onError"          : ( detail ) => println( "[graphql] #detail.path.toList( '.' )#: #detail.message# (#detail.type#)" )
} )

app = boxExpress()
app.use( boxExpressJSON() )

app.post( "/graphql", ( req, res ) => {
	var result = graph.execute(
		query          = req.body.query ?: "",
		queryVariables = isStruct( req.body.variables ?: "" ) ? req.body.variables : {},
		context        = { "roles" : listToArray( req.get( "X-Roles" ) ?: "" ) }
	)
	res.json( result.errors.len() ? result : { "data" : result.data } )
} )

app.get( "/schema", ( req, res ) => res.type( "text/plain" ).send( graph.getGeneratedSDL() ) )

app.listen( getSystemSetting( "PORT", 3000 ), ( port ) => println( "Bookshelf on http://localhost:#port#/graphql" ) )

Four paths, all optional but one. modelPaths and servicePaths are the new ones. schemaPaths and resolverBasePackage are the originals, and they're no longer required once either of the new ones is set. servicePaths points at the whole folder: Library.bx is in there too, and it's ignored because nothing in it is annotated.

instanceFactory is where your DI goes. By default the module builds every class with a bare new. Give it a factory and it asks you instead, telling you what the instance is for: "service" and "resolver" are asked for once and kept, "input" is asked for every input bean and must be a new one each time. Here it hands each service the one Library. In a ColdBox-style app this is the line that would call your injector.

The route passes the context. Whatever goes in as context is what authorizer, loaders and context parameters receive. The X-Roles header is a stand-in so the example runs without a login. A real app would put the signed-in user there, as Feedhouse does with its API tokens.

/schema shows what was generated. getGeneratedSDL() returns the SDL made from your classes, and printSchema() the whole schema, hand-written parts included. When a generated type isn't what you expected, this is the first place to look.

For completeness, services/Library.bx is the in-memory store. It has no annotations and knows nothing about GraphQL:

/** The data, in memory. The only class here bx-graphql knows nothing about. */
class {

	variables.books         = [];
	variables.authors       = [];
	variables.nextBookId    = 1;
	variables.authorLookups = 0;

	function init(){
		addAuthor( "Ursula K. Le Guin" );
		addAuthor( "Frank Herbert" );
		return this;
	}

	any function addAuthor( required string name ){
		var author = new "../models/Author"( id = arrayLen( variables.authors ) + 1, name = arguments.name );
		arrayAppend( variables.authors, author );
		return author;
	}

	any function addBook( required any book ){
		arguments.book.setId( variables.nextBookId++ );
		arguments.book.setAddedAt( now() );
		arguments.book.setPrivateNote( "Added through the API" );
		if( isNull( arguments.book.getStatus() ) ){
			arguments.book.setStatus( "WANT" );
		}
		if( isNull( arguments.book.getReviews() ) ){
			arguments.book.setReviews( [] );
		}
		arrayAppend( variables.books, arguments.book );
		return arguments.book;
	}

	any function book( required numeric id ){
		var id    = arguments.id;
		var found = variables.books.filter( ( book ) => book.getId() == id );
		if( !arrayLen( found ) ){
			throw( type = "Bookshelf.NotFound", message = "Book #arguments.id# not found" );
		}
		return found[ 1 ];
	}

	array function books(){
		return variables.books;
	}

	array function authors(){
		return variables.authors;
	}

	boolean function hasAuthor( required numeric id ){
		var id = arguments.id;
		return variables.authors.some( ( author ) => author.getId() == id );
	}

	void function removeBook( required numeric id ){
		var doomed = book( arguments.id );
		variables.books = variables.books.filter( ( book ) => book.getId() != doomed.getId() );
	}

	/** One call for any number of authors. */
	struct function authorsByIds( required array ids ){
		variables.authorLookups++;
		var byId = {};
		for( var author in variables.authors ){
			if( arrayContains( arguments.ids, author.getId() ) ){
				byId[ author.getId() ] = author;
			}
		}
		return byId;
	}

	numeric function authorLookups(){
		return variables.authorLookups;
	}

}

Run it and try a query:

boxlang app.bxs
curl -s localhost:3000/graphql -H "Content-Type: application/json" -d '{"query":"mutation { addBook( input: { name: \"Dune\", pages: 612, authorId: 2, status: READING } ) { id name author { name } } }"}'
curl -s localhost:3000/graphql -H "Content-Type: application/json" -H "X-Roles: admin" -d '{"query":"{ stats { books authors } }"}'

Errors

In the last post, the part I liked least was parsing graphql-java's error strings with a regex to get the path back. That's gone. With structuredErrors on, each error is a struct shaped the way the GraphQL spec describes:

mutation { review( id: 2, review: { rating: 9 } ) { name } }
{
	"data": { "review": null },
	"errors": [ {
		"message": "A rating is 1 to 5",
		"path": [ "review" ],
		"locations": [ { "line": 1, "column": 12 } ],
		"extensions": { "type": "Bookshelf.Invalid", "classification": "DataFetchingException" }
	} ]
}

message is the exception's own message, not graphql-java's wrapper around it. extensions.type is the BoxLang exception type the service threw, so a client can tell Bookshelf.NotFound from Bookshelf.Invalid without reading prose. classification is graphql-java's: ValidationError for a query that doesn't fit the schema, DataFetchingException for something your code threw.

onError is for the server's side of it. It's called once per error with the same details plus the exception itself. The app prints a line each:

[graphql] review: A rating is 1 to 5 (Bookshelf.Invalid)
[graphql] book.note: Not authorized: Book.note (BxGraphQL.NotAuthorized)

That's where a stack trace or an alert belongs. The client only gets the summary.

Without structuredErrors, errors is the array of message strings it always was, so an app already parsing those keeps working.

Upgrading

A schema-first app needs no changes. Every new feature is off until its setting or annotation is used, and Feedhouse's own GraphQL specs pass against 0.2.0 untouched. Three things do behave differently:

  • A resolver that returns a class instance now gets its fields read. In 0.1.x every field of a bean came back null, with no error. Now they're read through getters. If you somehow depended on those nulls, you'll see data.
  • Resolver args are no longer passed through JSON. Values arrive as graphql-java coerced them. For the built-in scalars that's the same values; it matters once a custom scalar returns a real object.
  • A schema that declares a custom scalar must give its conversions in scalars, unless it's DateTime or Long.

And some things it doesn't do: generate CRUD from a bean, generate interfaces or unions from classes, guard a plain property, or support subscriptions. I've only run it on BoxLang 1.19, though box.json still says 1.15.

The README has the full annotation and type tables. Install it with:

box install bx-graphql

A ColdBox implementation can be found here: https://github.com/robertz/bx-testing-ground . This includes a GraphQL interface for easy querying,

No comments yet — be the first.