Commit ba17932b authored by Tyler's avatar Tyler

working demo

parents
# EditorConfig is awesome: http://EditorConfig.org
# top-most EditorConfig file
root = true
# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 2
# Matches multiple files with brace expansion notation
# Set default charset
[*.{js}]
charset = utf-8
node_modules
.env
.DS_Store
MIT License
Copyright (c) 2019 Tyler Golden
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# GraphQL Demo API
A demo server that allows subscriptions for new chat messages.
The server automatically generates new messages every 3 seconds for demo purposes.
To start the server:
- Install NodeJS 8.x
- Optional: Install yarn
- Run `yarn start` or `npm start` to start the server
- Server will be accessible at `http://localhost:4001/graphql`
{
"name": "graphql-server-demo",
"version": "0.1.0",
"author": "Tyler Golden",
"license": "MIT",
"private": true,
"dependencies": {
"apollo-server-express": "^2.4.8",
"body-parser": "^1.18.3",
"cors": "^2.8.5",
"express": "^4.16.4",
"graphql": "^14.2.1",
"graphql-relay": "^0.6.0"
},
"devDependencies": {
"standard": "^12.0.1"
},
"scripts": {
"start": "node src/server.js",
"lint": "standard",
"printschema": "node ./utils/printSchema.js"
}
}
// TODO to run this scalably - beyond a single server - replace PubSub with a persistent store such as Redis
const { PubSub } = require('apollo-server-express')
const pubsub = new PubSub()
const notify = () => {
const now = new Date()
pubsub.publish('NEW_MESSAGES', {
messages: {
node: {
username: 'demo-user',
message: `Hi, this is a new message sent at ${now.toUTCString()}`,
id: now.toUTCString()
},
cursor: now.toUTCString()
}
})
}
// This is just for demo purposes
setInterval(notify, 3000)
module.exports = pubsub
const {
GraphQLObjectType,
GraphQLNonNull,
GraphQLSchema,
GraphQLString,
GraphQLID
} = require('graphql')
const {
connectionDefinitions,
connectionArgs,
connectionFromArray
} = require('graphql-relay')
const pubsub = require('../pubsub')
const newMessagesType = new GraphQLObjectType({
name: 'newMessage',
description: 'A new chat message',
fields: () => ({
id: {
type: GraphQLNonNull(GraphQLID),
resolve: (source, args, context, info) => {
return Buffer.from(source.id).toString('base64')
}
},
username: {
type: GraphQLNonNull(GraphQLString),
description: 'The name of the user that sent the message',
resolve: (source, args, context, info) => {
return source.username
}
},
message: {
type: GraphQLNonNull(GraphQLString),
description: 'The message',
resolve: (source, args, context, info) => {
return source.message
}
}
})
})
const subscriptionType = new GraphQLObjectType({
name: 'Subscription',
description: 'Subscribe to data event streams',
fields: () => ({
messages: {
type: messageEdge,
description: 'New chat messages',
subscribe: (parent, args, context, info) => {
return pubsub.asyncIterator(['NEW_MESSAGES'])
}
}
})
})
const { connectionType: messageConnection, edgeType: messageEdge } = connectionDefinitions({ nodeType: newMessagesType })
function getMessages () {
return [
{
id: '1',
username: 'DemoUser1',
message: 'Hello World'
},
{
id: '2',
username: 'Hunter2',
message: 'Change your password'
}
]
}
const queryType = new GraphQLObjectType({
name: 'Query',
description: 'Root query type',
fields: () => ({
messages: {
type: messageConnection,
description: 'Messages in the mock chatroom - note that pagination is not implemented since this is just a demo',
args: connectionArgs,
resolve: (root, args) => {
return connectionFromArray(
getMessages(),
args
)
}
}
})
})
module.exports = new GraphQLSchema({
query: queryType,
subscription: subscriptionType
})
const { ApolloServer } = require('apollo-server-express')
const express = require('express')
const schema = require('./schema')
const app = express()
const cors = require('cors')
const http = require('http')
const corsOptions = {
origin: ['http://localhost:3000']
}
app.use(cors(corsOptions))
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort (val) {
const port = parseInt(val, 10)
if (isNaN(port)) {
// named pipe
return val
}
if (port >= 0) {
// port number
return port
}
return false
}
const apollo = new ApolloServer({ schema })
apollo.applyMiddleware({
app,
cors: corsOptions
})
const server = http.createServer(app)
// Add subscription support
apollo.installSubscriptionHandlers(server)
const port = normalizePort(4001)
server.listen({ port }, () => {
console.log(`Server ready at localhost:${port}/graphql`)
})
const GraphQLUtilities = require('graphql/utilities')
const schema = require('../src/schema')
console.log(GraphQLUtilities.printSchema(schema))
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment