Independent consultant
Web / Mobile / VR / AR / IoT / AI
GDE, author, dev advocate @hasura.io
A query language for your API
Description of resource is coupled to implementation
Overfetching
Underfetching
chaining requests to server to get needed data
Avoid over-fetching
Prevent multipe API calls
Lesser communication with API developers
Self-documenting
type Post {
title: String!
content: String!
user: User!
}
type Person {
name: String!
address: String
posts: [Post!]!
}
Tip: If you are not sure with how to write GraphQL syntax use Explorer feature
1_getting-to-know-graphql
yarn add apollo-server graphql
const { ApolloServer, gql } = require('apollo-server')
const posts = [{
id: 1,
title: "Some title",
description: "Description",
userId: 1
}]
const users = [{
id: 1,
name: "Vladimir Novick",
email: "12312@asdfa.com"
}]
const typeDefs = gql`
type Post {
id: ID!
title: String!
description: String!
user: User
}
type User {
id: ID!
name: String!
email: String
}
type Query {
posts: [Post]
users: [User]
}
type Mutation {
addPost(post: PostInputType): Post
}
input PostInputType {
userId: ID!
title: String!
content: String!
}
`
const resolvers = {
Query: {
posts: () => posts.map(post => {
const user = users.find(user => user.id === post.userId)
return {
id: post.id,
title: post.title,
description: post.description,
user
}
}),
users: () => users
},
Mutation: {
addPost: (_, { post: {userId, title, content}}) => {
const user = users.filter(user => user.id === userId).reduce((acc, u) => u, {})
const postToPublish = {
id: posts.reverse()[0].id + 1,
title,
description: content,
userId: user.id
}
posts.push(postToPublish)
return postToPublish
}
}
}
const server = new ApolloServer({
typeDefs,
resolvers
})
server.listen().then(({ url }) => console.log(url));
yarn add @apollo/react-hooks
passing variables to mutation
passing different options such as refetchQueries etc
3_graphql_client
open source and free engine that gives you auto-generates real-time GraphQL API on top of new or existing Postgres database
Go to hasura.io
Click on Get started with Heroku
Click on
Enter your app name
Click on deploy button
Click on View app
Create posts table
create users table
connect posts and users using foreign key and relationships
Add a remote schema
Change your code sandbox from Excercise 2 to connect to your newly created blog api
@VladimirNovick