https://goo.gl/qYrg4q
{
"movies": [
"title": "Star Wars",
"year": 1977,
"directorId": 0,
]
}
GET http://api.example.com/v1/movies
{
"firstname": "George",
"lastname": "Lucas",
}
GET http://api.example.com/v1/directors/0
Waterfall
HTTP Method | URL |
---|---|
POST | http://api.example.com/v1/movies |
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="..."
xmlns:m="...">
<soap:Header>
</soap:Header>
<soap:Body>
<m:GetAllMovies>
<m:Genre>sf</m:Genre>
</m:GetAllMovies>
</soap:Body>
</soap:Envelope>
<?xml version="1.0"?>
<soap:Envelope>
<soap:Header>
</soap:Header>
<soap:Body>
<m:GetAllMoviesResponse>
<m:Movie>
<m:Title>Star Wars</m:Title>
<m:Year>1977</m:Year>
<m:DirectorId>0</m:DirectorId>
</m:Movie>
</m:GetAllMoviesResponse>
</soap:Body>
</soap:Envelope>
Depuis plusieurs années
Vous utilisez déjà GraphQL
2012 - 2015
{ movie { title } }
{ "movie": { "title": "Star Wars" } }
{ movie { title director { firstname lastname } } }
MOVIES
DIRECTORS
{ movie { title director { firstname lastname } } }
type Movie { title: String director: Director } type Director { firstname: String lastname: String }
type Movie { title: String @deprecated originalTitle: String director: Director releaseYear: Int }
type Movie { title: String director: Director }
Int
Float
String
Boolean
ID
<le vôtre ici>
type Movie { title: String! releaseYear: Int director: Person } type Person { name: String! age: Int! }
interface NamedEntity { name: String } type Person implements NamedEntity { name: String age: Int }
type Movie { title: String releaseYear: Int director: Person } type Person { name: String age: Int } union SearchResult = Movie | Person
enum Status { RUMORED IN_PRODUCTION RELEASED } type Movie { status: Status }
schema { # Récupération query: Query # Modification mutation: Mutation # Temps-réel subscription: Subscription }
type Query { movie(id: ID): Movie } type Movie { posterUrl(size: Int): String }
type Query { movies(genre: String): [Movie] } type Movie { actors: [Actor] }
input ReviewInput { stars: Int! comment: String } type Review { id: ID! stars: Int! comment: String } type Mutation { addReview(movie: ID!, review: ReviewInput): Review }
type Movie { title: String @deprecated originalTitle: String director: Director releaseYear: Int }
query { movies(genre: "sf") { title director { name age } } }
{
"data": {
"movies": [
{
"title": "Star Wars",
"director": {
"name": "George Lucas",
"age": 72
}
}
]
}
}
Document
Résultat
{ movies(genre: "sf") { title } tvShows(genre: "sf") { title } }
{
"movies": [
{
"title": "Star Wars"
}
],
"tvShows": [
{
"title": "The Expanse"
}
]
}
query videos ($genre: String = "all") { movies(genre: $genre) { title } tvShows(genre: $genre) { title } } { genre: "sf" }
query videos ($onlyMovies: Boolean = false) { movies @include(if: true) { title } tvShows @skip(if: $onlyMovies) { title } }
query { movies(genre: "sf") { ...movieFields } movies(genre: "action") { ...movieFields } } fragment movieFields on Movie { title releaseYear }
query { search { __typename title ... on Movies { releaseYear } ... on TvShow { currentSeason } } }
{
"search": [
{
"__typename": "Movie",
"title": "Star Wars",
"releaseYear": 1997
},
{
"__typename": "TvShow",
"title": "The Expanse",
"currentSeason": 2
}
]
}
query { searchResults: search { label: title ... on Movies { year: releaseYear } ... on TvShow { season: currentSeason } } }
{
"searchResults": [
{
"label": "Star Wars",
"year": 1997
},
{
"label": "The Expanse",
"season": 2
}
]
}
mutation addReview($movie: ID!, $review: ReviewInput) { newReview: addReview (movie: $movie, review: $review) { id stars comment } }
{
"newReview": {
"id": "f6gt7DA42-1F",
"stars": 5,
"comment": "This movie is awesome!"
}
}
query { __schema { types { name } } }
{
"__schema": {
"types": [
{
"name": "Movie"
},
{
"name": "TvShow"
}
]
}
}
meteor.io
apollodata.com/optics
Serveur HTTP
Schema
Resolvers
Connectors
type
{...}
const typeDefs = `
# General entity
interface Entity {
id: ID!
name: String!
image: String
}
# Movie
type Movie implements Entity {
id: ID!
name: String!
image: String
genre: String!
releaseYear: Int
director: Director
}
`
const collection = new DataBaseCollection()
export function getAll () {
return collection
}
export function getByGenre (genre) {
return collection.filter(i => i.genre === genre)
}
export function getById (id) {
return collection.find(i => i.id === id)
}
const resolvers = {
Movie: {
director: (movie) => Directors.getById(movie.directorId),
},
Query: {
movies: (root, { genre }) => Movies.getByGenre(genre),
movie: (root, { id }) => Movies.getById(id),
tvShows: (root, { genre }) => TvShows.getByGenre(genre),
tvShow: (root, { id }) => TvShows.getById(id),
search: (root, { text }) => Search.search(text),
},
}
import typeDefs from './type-defs'
import resolvers from './resolvers'
const jsSchema = makeExecutableSchema({
typeDefs,
resolvers,
})
export default jsSchema
import { graphqlExpress, graphiqlExpress }
from 'graphql-server-express'
import schema from './schema'
const PORT = process.env.PORT || 3000
const app = express()
// GraphQL server
app.use('/graphql', graphqlExpress({ schema }))
// GraphiQL devtool
app.use('/graphiql', graphiqlExpress({
endpointURL: '/graphql',
}))
app.listen(PORT, () => console.log(`Listening on port ${PORT}`))
Done!
Query
Mutation
Subscription (Web socket)
.gql
Observable
query
Cache Normalisé
import { ApolloClient, createNetworkInterface } from 'apollo-client'
// Create the apollo client
const apolloClient = new ApolloClient({
networkInterface: createNetworkInterface({
uri: 'http://localhost:3000/graphql',
transportBatching: true,
}),
connectToDevTools: true,
})
import gql from 'graphql-tag'
const MOVIES_QUERY = gql`
query Movies($genre: String) {
movies (genre: $genre) {
id
name
image
genre
releaseYear
}
}`
apolloClient.query({
query: MOVIES_QUERY,
variables: { genre: "sf" },
}).then(result => {
console.log(result)
})
const q = apolloClient.watchQuery({
query: MOVIES_QUERY,
})
const sub = q.subscribe({
next: (result) => console.log(result),
error: (error) => console.error(error),
})
// Later...
sub.unsubscribe()
q.refetch()
q.setVariables({
genre: 'comics',
})
q.setOptions({
fetchPolicy: 'cache-only',
})
q.fetchMore({
variables: {
page: this.page,
pageSize,
},
updateQuery: (previousResult, { fetchMoreResult }) => {
const newMovies = fetchMoreResult.paginatedMovies.movies
const hasMore = fetchMoreResult.paginatedMovies.hasMore
return {
paginatedMovies: {
// Merging the movie list
movies: [...previousResult.paginatedMovies.tags, ...newMovies],
hasMore,
},
}
},
})
apolloClient.mutate({
mutation: gql`mutation ($label: String!) {
addTag(label: $label) {
id
label
}
}`,
variables: { label: newTag },
updateQueries: {
tagList: (previousResult, { mutationResult }) => ({
tags: [...previousResult.tags, mutationResult.data.addTag],
}),
},
optimisticResponse: {
__typename: 'Mutation',
addTag: {
__typename: 'Tag',
id: -1,
label: newTag,
},
},
}).then((data) => {
console.log(data)
}).catch((error) => {
console.error(error)
this.newTag = newTag
})
github.com/Akryum/graphql-demo
conf.vuejs.org