what's the difference between schema and documents in Graphql?
schema is like this:
type Query {
fo: String
}
but the document is like:
query SomeQuery {
foo {
bar
}
}
the spec is really confusing https://graphql.github.io/graphql-spec/June2018/#sec-Language.Document
I always use schema but for client-side type generation in graphql-code-generator it needs document file. https://graphql-code-generator.com/docs/getting-started/documents-field
A document is really any string containing valid GraphQL syntax. According to the spec, a document contains one or more definitions, where a definition could be:
an operation definition
query UsersQuery {
users {
id
email
}
}
a fragment definition
fragment UserFragment on User {
id
email
}
a type system definition
type User {
id: ID!
email: String!
}
a type system extension
extend type User {
name: String
}
Operation and fragment definitions are known as executable definitions. Documents sent to a GraphQL service must only contain executable definitions. Type system definitions and extensions are used in describing a schema -- that's why we commonly call them Schema Definition Language (SDL). A schema is a GraphQL service's "collective type system capabilities" -- it's basically a collection of types and directives that represent everything your GraphQL service can do.
A schema may be described using type system definitions, but it's not really accurate to say that the type definitions are the schema because the schema itself also includes the actual field resolution logic as well.
Related
Here is a simplified snippet out of a GraphQL Schema I work with. There are - an enum, type Contributor and type Review.
enum CONTRIBUTOR_TYPE {
AUTHOR
EDITOR
}
type Contributor {
name: String
role: CONTRIBUTOR_TYPE
}
type Article {
text: String
authors: [Contributor]
}
What I want to describe, is that the "authors" field is not just array of type Contributor, but Contributor with specific job role. In pseudocode it would look like
authors: [Contributor{type: CONTRIBUTOR_TYPE.AUTHOR}]!
Is there a way to describe this constraint in GraphQL Schema?
You should be able to use schema directives to describe / enforce the constraint. For apollo server check out https://www.apollographql.com/docs/apollo-server/schema/creating-directives/, for graphql-java check out https://www.graphql-java.com/documentation/v15/sdl-directives/, for other server implementations check their corresponding documentation.
With GraphQL schemas, when should I provide a type relation's field as a root-level field for its associated type?
Example
In many examples, I almost always see schemas that require the client to create queries that explicitly traverse the graph to get a nested field.
For a Rock Band Table-like component in the front end (or client), the GraphQL service that provides that component's data may have a schema that looks like this:
type Artist {
name: String!
instrument: String!
}
type RockBand {
leadSinger: Artist,
drummer: Artist,
leadGuitar: Artist,
}
type Query {
rockBand: RockBand
}
If the table component specified a column called, "Lead Singer Name", given the current schema, a possible query to fetch table data would look like this:
{
rockBand {
leadSinger {
name
}
}
}
For the same Rock Band Table, with the same column and needs, why not design a schema like this:
type RockBand {
leadSinger: Artist,
leadSingerName: String,
drummer: Artist,
leadGuitar: Artist,
}
That way a possible query can be like this?
{
rockBand {
leadSingerName
}
}
Does the choice to include the "leader singer's name", and similar relation fields, entirely depend on the client's need? Is modifying the schema to serve data for this use-case too specific a schema? Are there benefits to flattening the fields outside of making it easier for the client? Are there benefits to forcing traversal through the relation to get at a specific field?
In the type definition below, is there a way to require name or model, instead of name and model?
type Starship {
id: ID!
name: String!
model: String!
length(unit: LengthUnit = METER): Float
}
I may have name or model due to some legacy data limitations. I would rather enforce this at the GraphQL validation layer, rather than in code.
EDIT:
There is some good discussion about adding validation to the graphQL spec, which you can read here: https://github.com/graphql/graphql-js/issues/361
There are also a couple of libraries to extend validation:
https://github.com/xpepermint/graphql-type-factory
https://github.com/stephenhandley/graphql-validated-types
I'm going to stick with validating the types in code, at least until they add better support.
You could try to use union to represent name or model concept . As union only works with object type now , that means you have also model name and model as object type first.
Code wise the schema looks like :
type Name {
value : String!
}
type Model {
value : String!
}
union NameOrModel = Name | Model
type Starship {
id: ID!
nameOrModel : NameOrModel!
length(unit: LengthUnit = METER): Float
}
It is very ugly IMO as it introduces many unnecessary noise and complexity to the schema .So I would prefer to stick with your original schema and do that check manually in the backend.
From the spec:
By default, all types in GraphQL are nullable; the null value is a valid response for all of the above types. To declare a type that disallows null, the GraphQL Non‐Null type can be used. This type wraps an underlying type, and this type acts identically to that wrapped type, with the exception that null is not a valid response for the wrapping type. A trailing exclamation mark is used to denote a field that uses a Non‐Null type like this: name: String!.
An individual field may be nullable or non-nullable. Non-null validation happens at the field level, independent of other fields. So there is no mechanism for validating whether some combination of fields are or are not null.
I'm a newbie to Prisma/GraphQL. I'm writing a simple ToDo app and using Apollo Server 2 and Prisma GraphQL for the backend. I want to convert my createdAt field from the data model to something more usable on the front-end, like a UTC date string. My thought was to convert the stored value, which is a DateTime.
My datamodel.prisma has the following for the ToDo type
type ToDo {
id: ID! #id
added: DateTime! #createdAt
body: String!
title: String
user: User!
completed: Boolean! #default(value: false)
}
The added field is a DataTime. But in my schema.js I am listing that field as a String
type ToDo {
id: ID!
title: String,
added: String!
body: String!
user: User!
completed: Boolean!
}
and I convert it in my resolver
ToDo: {
added: async (parent, args) => {
const d = new Date(parent.added)
return d.toUTCString()
}
Is this OK to do? That is, have different types for the same field in the datamodel and the schema? It seems to work OK, but I didn't know if I was opening myself up to trouble down the road, following this technique in other circumstances.
If so, the one thing I was curious about is why accessing parent.added in the ToDo.added resolver doesn't start some kind of 'infinite loop' -- that is, that when you access the parent.added field it doesn't look to the resolver to resolve that field, which accesses the parent.added field, and so on. (I guess it's just clever enough not to do that?)
I've only got limited experience with Prisma, but I understand you can view it as an extra back-end GraphQL layer interfacing between your own GraphQL server and your data (i.e. the database).
Your first model (datamodel.prisma) uses enhanced Prisma syntax and directives to accurately describe your data, and is used by the Prisma layer, while the second model uses standard GraphQL syntax to implement the same object as a valid, standard GraphQL type, and is used by your own back-end.
In effect, if you looked into it, you'd see the DateTime type used by Prisma is actually a String, but is likely used by Prisma to validate date & time formats, etc., so there is no fundamental discrepancy between both models. But even if there was a discrepancy, that would be up to you as you could use resolvers to override the data you get from Prisma before returning it from your own back-end.
In short, what I'm trying to say here is that you're dealing with 2 different GraphQL layers: Prisma and your own. And while Prisma's role is to accurately represent your data as it exists in the database and to provide you with a wide collection of CRUD methods to work with that data, your own layer can (and should) be tailored to your specific needs.
As for your resolver question, parent in this context will hold the object returned by the parent resolver. Imagine you have a getTodo query at the root Query level returning a single item of type ToDo. Let's assume you resolve this to Prisma's default action to retrieve a single ToDo. According to your datamodel.prisma file, this query will resolve into an object that has an added property (which will exist in your DB as the createdAt field, as specified by the #createdAt Prisma directive). So parent.added will hold that value.
What your added resolver does is transform that original piece of data by turning it into an actual Date object and then formatting it into a UTC string, which conforms to your schema.js file where the added field is of type String!.
I've the following structure in my schema:
type gn_Feature implements Some_Interface {
s_description: String
s_id: URL!
some_parent: gn_Feature
}
As you can see, each gn_Feature has an another linked gn_Feature object (the linking is handled elsewhere, it doesn't really matter). By my current understanding, you only need to define the resolvers for the return types, so my resolvers look like the following:
export const resolvers = Object.assign(
{},
{
DateTime: DateTime,
Date: DateTime,
Time: RegularExpression("Time", /^\d{2}:\d{2}(:\d{2})?$/),
URL,
Query: {
gn_Feature: gn_FeatureResolver
},
gn_Feature: gn_FeatureResolver
}
);
But, my queries fail with the following error if I don't explicitly define the resolver for the nested field, like so:
gn_Feature: {some_parent: gn_FeatureResolver}
Error:
"message": "Resolve function for \"gn_Feature.s_description\"
returned undefined"
My resolver function doesn't even get invoked for my nested object when I don't specify it like the above.
My backend consists of some voodoo transpiling of GraphQL queries into SparQL queries which return data back so I won't post the resolver code as I utilize one universal resolver for many fields. I'd like to avoid having to specify resolvers for each nested field as that's going be extremely tedious (I have dozens of types with dozens of fields). Any clarifications are welcome, as I'm completely baffled.
Example GraphQL query:
gn_Feature(some_field:"AD", last:2){
s_description,
s_id
some_parent{
s_description
}
}
When executing a query, only the value of any particular field is initially unknown and needs to be resolved... everything else, like the types, selection sets, etc. is already known. A resolver is a function called to resolve a specific field. In GraphQL.js, there are no resolvers for types.
Apollo muddies the waters a bit in this regard, since for convenience, the API for makeExecutableSchema allows you to define custom scalars by including them in the resolver map. Additionally, even though interfaces and unions don't have resolvers either, Apollo lets you use the resolver map to specify a __resolveType function for these abstract types as well. Apollo's docs actually define a resolver as "a function that connects schema fields and types to various backends." However, in the context of GraphQL in general, you should think of a resolvers as "a functions that resolves the value of a field".
So, given a type called gn_Feature and a field called some_parent, this is the correct way to structure your resolvers:
const resolvers = {
gn_Feature: {
some_parent: someResolverFunction
}
}
Also note that Query and Mutation are both types themselves, so if you have a query called gn_Feature, you are actually resolving a field called gn_Feature for the Query type.