index.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. 'use strict';
  2. const express = require('express');
  3. const graphqlHTTP = require('express-graphql');
  4. const {
  5. GraphQLBoolean,
  6. GraphQLID,
  7. GraphQLInt,
  8. GraphQLList,
  9. GraphQLNonNull,
  10. GraphQLObjectType,
  11. GraphQLSchema,
  12. GraphQLString,
  13. } = require('graphql');
  14. const {
  15. getVideoById,
  16. getVideos
  17. } = require('./src/data/index');
  18. const PORT = process.env.PORT || 3000;
  19. const server = express();
  20. const videoType = new GraphQLObjectType({
  21. name: 'Video',
  22. description: 'A video on egghead.io',
  23. fields: {
  24. id: {
  25. type: GraphQLID,
  26. description: 'The ID of the video'
  27. },
  28. title: {
  29. type: GraphQLString,
  30. description: 'The title of the video'
  31. },
  32. duration: {
  33. type: GraphQLInt,
  34. description: 'The duration of the video, in seconds',
  35. },
  36. watched: {
  37. type: GraphQLBoolean,
  38. description: 'Whether or not the viewer has watched the video'
  39. }
  40. }
  41. });
  42. const queryType = new GraphQLObjectType({
  43. name: 'QueryType',
  44. description: 'The root query type',
  45. fields: {
  46. video: {
  47. type: videoType,
  48. args: {
  49. id: {
  50. type: new GraphQLNonNull(GraphQLID),
  51. description: 'The ID of the video'
  52. }
  53. },
  54. resolve: (_, args) => {
  55. return getVideoById(args.id);
  56. }
  57. },
  58. videos: {
  59. type: new GraphQLList(videoType),
  60. // General form:
  61. // resolve: () => getVideos()
  62. // Shortcut:
  63. resolve: getVideos
  64. }
  65. }
  66. });
  67. const schema = new GraphQLSchema({
  68. query: queryType
  69. // Also available:
  70. // mutation: ...
  71. // subscription: ...
  72. });
  73. server.use('/graphql', graphqlHTTP({
  74. schema,
  75. graphiql: true
  76. }));
  77. server.listen(PORT, () => {
  78. console.log(`Listening on http://localhost:${PORT}`);
  79. });