index.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. 'user strict';
  2. const express = require('express');
  3. const graphqlHTTP = require('express-graphql');
  4. const {
  5. GraphQLSchema,
  6. GraphQLObjectType,
  7. GraphQLID,
  8. GraphQLString,
  9. GraphQLInt,
  10. GraphQLBoolean
  11. } = require('graphql');
  12. const PORT = process.env.PORT || 3000;
  13. const server = express();
  14. const videoType = new GraphQLObjectType({
  15. name: 'Video',
  16. description: 'A video on egghead.io',
  17. fields: {
  18. id: {
  19. type: GraphQLID,
  20. description: 'The ID of the video'
  21. },
  22. title: {
  23. type: GraphQLString,
  24. description: 'The title of the video'
  25. },
  26. duration: {
  27. type: GraphQLInt,
  28. description: 'The duration of the video, in seconds',
  29. },
  30. watched: {
  31. type: GraphQLBoolean,
  32. description: 'Whether or not the viewer has watched the video'
  33. }
  34. }
  35. });
  36. const queryType = new GraphQLObjectType({
  37. name: 'QueryType',
  38. description: 'The root query type',
  39. fields: {
  40. video: {
  41. type: videoType,
  42. resolve: () => new Promise((resolve) => {
  43. resolve({
  44. id: 'a',
  45. title: 'GraphQL',
  46. duration: 180,
  47. watched: false
  48. });
  49. })
  50. }
  51. }
  52. });
  53. const schema = new GraphQLSchema({
  54. query: queryType,
  55. // Also available:
  56. // mutation: ...
  57. // subscription: ...
  58. });
  59. const videoA = {
  60. id: 'a',
  61. title: 'Create a GraphQL schema',
  62. duration: 120,
  63. watched: true
  64. };
  65. const videoB = {
  66. id: 'b',
  67. title: 'Ember.js CLI',
  68. duration: 240,
  69. watched: false
  70. };
  71. const videos = [videoA, videoB];
  72. const resolvers = {
  73. video: () => ({
  74. id: () => '1',
  75. title: () => 'Foo',
  76. duration: () => 180,
  77. watched: () => true
  78. }),
  79. videos: () => videos
  80. };
  81. server.use('/graphql', graphqlHTTP({
  82. schema,
  83. graphiql: true
  84. }));
  85. server.listen(PORT, () => {
  86. console.log(`Listening on http://localhost:${PORT}`);
  87. });