Académique Documents
Professionnel Documents
Culture Documents
$mkdirgraphqlintro&&cd./graphqlintro
$npminstallexpresssave
$npminstallbabelsave
$touch./server.js
$touch./index.js
This creates a folder for our project (graphql-intro), and installs Express
and Babel as dependencies. Babel isnt required for GraphQL either, but it
will let us write our JavaScript using ES2015 features that make life easier.
Finally, lets write some code:
https://medium.com/@clayallsopp/your-first-graphql-server-3c766ab4f0a2
1/10
7/19/2015
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//index.js
//byrequiring`babel/register`,allofoursuccessive`require`swillbeBabel
require('babel/register')
require('./server.js')
//server.js
importexpressfrom'express'
letapp=express()
letPORT=3000
app.post('/graphql',(req,res)=>{
res.send('Hello!')
})
letserver=app.listen(PORT,function(){
lethost=server.address().address
letport=server.address().port
console.log('GraphQLlisteningathttp://%s:%s',host,port)
})
graphql_1.jshostedwithbyGitHub
viewraw
$nodeindex.js
GraphQLlisteningathttp://0.0.0.0:3000
$curlXPOSThttp://localhost:3000/graphql
Hello!
https://medium.com/@clayallsopp/your-first-graphql-server-3c766ab4f0a2
2/10
7/19/2015
querygetHighScore{score}
In this case, our GraphQL client is requesting the `score` sub-eld of the
top-level `getHighScore` eld. Fields are the things we ask a GraphQL
server to return. Fields can also have arguments, like:
querygetHighScores(limit:10){score}
$npminstallgraphqlsave
$npminstallbodyparsersave
$touch./schema.js
This looks promising, right? The GraphQL module contains the GraphQL
technical preview, which allows us to compose our server schema and
process GraphQL requests against it. Body-parser is a simple Express
middleware that we use to grab the GraphQL request being sent.
Time to write our schema:
https://medium.com/@clayallsopp/your-first-graphql-server-3c766ab4f0a2
3/10
7/19/2015
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//schema.js
import{
GraphQLObjectType,
GraphQLSchema,
GraphQLInt
}from'graphql/lib/type'
letcount=0
letschema=newGraphQLSchema({
query:newGraphQLObjectType({
name:'RootQueryType',
fields:{
count:{
type:GraphQLInt,
resolve:function(){
returncount
}
}
}
})
})
exportdefaultschema
graphql_2.jshostedwithbyGitHub
viewraw
https://medium.com/@clayallsopp/your-first-graphql-server-3c766ab4f0a2
4/10
7/19/2015
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
importexpressfrom'express'
importschemafrom'./schema'
//newdependencies
import{graphql}from'graphql'
importbodyParserfrom'bodyparser'
letapp=express()
letPORT=3000
//parsePOSTbodyastext
app.use(bodyParser.text({type:'application/graphql'}))
app.post('/graphql',(req,res)=>{
//executeGraphQL!
graphql(schema,req.body)
.then((result)=>{
res.send(JSON.stringify(result,null,2))
})
})
letserver=app.listen(PORT,function(){
varhost=server.address().address
varport=server.address().port
console.log('GraphQLlisteningathttp://%s:%s',host,port)
})
graphql_3.jshostedwithbyGitHub
viewraw
$node./index.js//restartyourserver
//inanothershell
$curlXPOSTH"ContentType:application/graphql"d'query
RootQueryType{count}'http://localhost:3000/graphql
{
"data":{
"count":0
}
}
https://medium.com/@clayallsopp/your-first-graphql-server-3c766ab4f0a2
5/10
7/19/2015
$curlXPOSTH'ContentType:application/graphql'd'{count
}'http://localhost:3000/graphql
{
"data":{
"count":0
}
}
Now that weve got non-zero GraphQL stu working, lets take a minute
to talk about introspection.
$curlXPOSTH'ContentType:application/graphql'd
'{__schema{queryType{name,fields{name,description}}}}'
http://localhost:3000/graphql
{
"data":{
"__schema":{
"queryType":{
"name":"RootQueryType",
"fields":[
{
"name":"count",
"description":null
}
]
}
}
}
}
{
__schema{
queryType{
name,
fields{
name,
description
}
}
}
}
https://medium.com/@clayallsopp/your-first-graphql-server-3c766ab4f0a2
6/10
7/19/2015
letschema=newGraphQLSchema({
query:newGraphQLObjectType({
name:'RootQueryType',
fields:{
count:{
type:GraphQLInt,
//addthedescription
description:'Thecount!',
resolve:function(){
returncount
}
}
}
})
})
graphql_4.jshostedwithbyGitHub
viewraw
$curlXPOSTH'ContentType:application/graphql'd
'{__schema{queryType{name,fields{name,description}}}}'
http://localhost:3000/graphql
{
"data":{
"__schema":{
"queryType":{
"name":"RootQueryType",
"fields":[
{
"name":"count",
"description":"Thecount!"
}
]
}
https://medium.com/@clayallsopp/your-first-graphql-server-3c766ab4f0a2
7/10
7/19/2015
}
}
}
Were almost done with our whirlwind tour of GraphQLfor my last trick,
Ill show o mutations.
Add a Mutation
If you want read-only access to a bunch of data, then you probably dont
need to read any further. But for most applications, were going to have to
change our data. GraphQL calls these operations mutations.
Mutations are just elds that are intended to have side-eects, so most of
the syntax is identical. Like normal query elds, mutation elds must also
return a typed valuethe intent is that if you mutate something, you
should also return whatever it mutated.
How do we add mutations to our schema? Much like we dene a top-level
`query` key on our schema, we will also dene a top-level `mutation` key:
letschema=newGraphQLSchema({
query:...
mutation://todo
)}
{
first:changeTheNumber(newNumber:1){
theNumber
},
second:changeTheNumber(newNumber:3){
theNumber
},
third:changeTheNumber(newNumber:2){
theNumber
https://medium.com/@clayallsopp/your-first-graphql-server-3c766ab4f0a2
8/10
7/19/2015
}
}
Thus, by the end of the request, `theNumber` eld should have the value of
`2`.
Lets add a simple mutation that updates our counter and returns the value:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
letschema=newGraphQLSchema({
query
mutation:newGraphQLObjectType({
name:'RootMutationType',
fields:{
updateCount:{
type:GraphQLInt,
description:'Updatesthecount',
resolve:function(){
count+=1
returncount
}
}
}
})
})
graphql_5.jshostedwithbyGitHub
viewraw
$curlXPOSTH'ContentType:application/graphql'd'mutation
RootMutationType{updateCount}'http://localhost:3000/graphql
{
"data":{
"updateCount":1
}
}
Boomthe data has been updated. You can conrm this with a new query:
$curlXPOSTH'ContentType:application/graphql'd'{count
}'http://localhost:3000/graphql
{
"data":{
"count":1
}
}
https://medium.com/@clayallsopp/your-first-graphql-server-3c766ab4f0a2
9/10
7/19/2015
Wrapping Up
Thats a whirlwind tour of how you can use GraphQL today using
Facebooks JavaScript implementation. I didnt cover some more powerful
topicselds with arguments, resolving promises, fragments, directives
theres lots of cool things in the GraphQL spec. Theres also room for new
implementations and schema APIs on the server side. You can imagine a
GraphQL server written in a typed language like Java might look quite
dierent than how it looks in JavaScript.
This is also based on my 48-hour experience with GraphQLif theres
anything missing or wrong, dont hesitate to let me know. You can view the
source (each commit is a new step) here:
https://github.com/clayallsopp/graphql-intro
Thanks to the RisingStack folks for their excellent post and example on
GraphQL.
https://medium.com/@clayallsopp/your-first-graphql-server-3c766ab4f0a2
10/10