GraphQL Flashcards
How does GraphQL define the schema of an API?
GraphQL has its own TYPE SYSTEM that’s used to define the schema of an API: Schema Definition Language (SDL)
What does SDL look like?
type Person {
name: String!
age: Int!
}
(Person has 2 fields with types, both are required)
How do you indicate a relationship between types?
Associate a type with another type. If it is a one to many relationship, the many side will be an array, e.g. [Person]
Sample query to get names of all Persons
{ allPersons { name } }
What are the 2 parts of a query?
The root field and the payload. Root field is ‘allPersons’ and payload is everything after that.
Explain query parameters
Each field can have zero or more arguments if that’s specified in the schema. E.g. allPersons(last:2) will limit results to last 2
How do you change what is stored in the DB?
Using mutations: create, update, delete.
How do you write a mutation?
Same as a query, but precede it with 'mutation': mutation { createPerson(name: "Bob", age: 36) { name age } }
the root field takes 2 arguments. The payload is optional, or you could ask for the autogenerated ID instead.
What is a subscription?
Unlike the request-response-cycle in queries and mutations, subscriptions initiate and hold a steady connection to the server, and stream the requested data to the client when it becomes available.
How do you create a subscription?
Same as a mutation. subscription { newPerson { name age } } whenever anyone creates a new person, the client will get their name and age.
What is does a schema do?
It specifies the capabilities of the API and defines how clients can request the data. It is often seen as a contract between the server and client. Basically, it is a collection of types.
How do you write a schema?
Start with TYPES. These are the entry points:
type Query { … }
type Mutation { … }
type Subscription { … }
In your schema, enable an allPersons query that allows the client to specify the last number of entries.
type Query {
allPersons(last: Int): [Person!]!
}
allPersons is the ROOT FIELD
(last:int) is the argument
[Person!]! is the the return type
In your schema, enable a mutation that allows the client to create a new person
type Mutation {
createPerson(name: String!, age: Int!): Person!
}
In your schema, enable a subscription that allows the client to receive a new person
type Subscription {
newPerson: Person!
}