Mapping that happens in the
codegen.js file allows us to expect that a Query/Mutation returning a given type returns all fields that are based on the intrinsic data of that object. Fields marked as
computed will need their own resolvers.
To demonstrate this with an example, let's take the type User from Quick Start
Fields that come straight from a Data Source have no annotations. In our example those are
On the other hand - we don't save the information whether someone is or is not underage - we calculate it runtime (
@computed annotation). That means that the resolver for Query like this:
will only expect an object with
dateOfBirth as it's return type. To speak in code:
Generator will also generate a resolver for User.underage to return a boolean based on the current date and the users dateOfBirth.
If you are following along from the Quick Start make sure you've modified your User type definition and run
npm run graphl:generateAll. At that point you will notice src/modules/Users/graphql/types/UserUnderage.ts file with a test scaffold next to it. As a practice go ahead and implement it, starting with test!
Example implementation that delegates the actual calculation to an external function:
This might seem like a rarely used feature at first, but it works the same way when you want to link different types (which itself is one of the main reasons to use GraphQL in the first place).
More complex mapping
note: The API might seem familiar to you. It's because our graphql-code-generator plugin was initially based on the typescript-mongodb plugin.
@map(path: String) (on
If you have a field in your data object that you want to expose differently in GraphQL use
For example, if your data source returns an object with a nested shape:
But want to expose it as a top level field in your GraphQL User type do:
If your data source returns an object that includes a field linking to a separate entity, for example:
You can map it like so:
In this case @link will tell the generator that your data source will not return an array of Books, but instead it will return an array of ids (it looks up Book.id field). @map on the other hand, tells the generator that the book ids are not at "books" key but at "bookIds" We end up with: