Created
May 25, 2018 02:48
-
-
Save huttj/df925a0bc0f32ef25320d654e3dd75a9 to your computer and use it in GitHub Desktop.
GraphQL live example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const graphqlHTTP = require('express-graphql'); | |
const { makeExecutableSchema } = require('graphql-tools'); | |
const events = [{ | |
id: 1, | |
name: 'APIs and IPAs', | |
description: 'Cool event', | |
startTime: 'evening', | |
endTime: 'late evening' | |
},{ | |
id: 2, | |
name: 'Seattle JS Hackers', | |
description: 'Chill event', | |
startTime: 'evening', | |
endTime: 'somewhat later' | |
}]; | |
const typeDefs = ` | |
type Event { | |
id: ID | |
name: String! | |
description: String | |
startTime: String | |
endTime: String | |
} | |
type Query { | |
listEvents(name: String!): [Event] | |
} | |
input EventInput { | |
id: ID | |
name: String! | |
description: String | |
startTime: String | |
endTime: String | |
} | |
type Mutation { | |
saveEvent(event: EventInput): Event | |
} | |
`; | |
const resolvers = { | |
Query: { | |
listEvents: (root, { name }, context, ast) => { | |
if (name) { | |
const re = new RegExp(name, 'i'); | |
return events.filter(e => e.name.match(re)) | |
} | |
return events; | |
} | |
}, | |
Mutation: { | |
saveEvent: (root, { event }, context, ast) => { | |
if (event.id) { | |
const existingEvent = events.find(e => e.id == event.id); | |
if (!existingEvent) { | |
throw new Error('Event not found'); | |
} | |
for (const key in event) { | |
existingEvent[key] = event[key]; | |
} | |
return existingEvent; | |
} else { | |
event.id = events.length + 1; | |
events.push(event); | |
return event; | |
} | |
} | |
} | |
} | |
const schema = makeExecutableSchema({ | |
typeDefs, | |
resolvers | |
}) | |
express() | |
.use('/graphql', graphqlHTTP({ | |
graphiql: true, | |
schema | |
})) | |
.listen(8080, ()=>console.log('runnin\'')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment