Advertisement
Guest User

Untitled

a guest
Apr 25th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. import Chalk from 'chalk'
  2.  
  3. import Logger from '../utils/logger'
  4.  
  5. import Hapi from 'hapi'
  6. import Inert from 'inert'
  7. import Routes from './http/routes'
  8.  
  9. import { prisma } from '../storage/prisma'
  10. import { typeDefs } from '../storage/prisma/prisma-schema'
  11. import { resolvers } from '../storage/resolvers/resolver'
  12. import { ApolloServer, gql as GQL } from 'apollo-server-hapi'
  13.  
  14. import jwt from 'jsonwebtoken'
  15.  
  16. import SocketIO from 'socket.io'
  17.  
  18. import RoomPlayer from '../core/rooms/player'
  19.  
  20. export default class Server {
  21.  
  22. constructor(config) {
  23.  
  24. this.config = config
  25.  
  26. this.HTTP = new Hapi.Server({
  27. port: 8081
  28. })
  29.  
  30. this.start()
  31. }
  32.  
  33. async start() {
  34.  
  35. try {
  36. await this.HTTP.register(Inert)
  37. await this.HTTP.route(Routes)
  38.  
  39. // Web Sockets
  40. this.socketIO = new SocketIO(this.HTTP.listener)
  41. await this.socketIO
  42. Logger.network('Started SocketIO [Web Sockets] listener')
  43.  
  44. // Database : GraphQL
  45. let HTTPServer = this.HTTP
  46. let environment = (this.config.mode == 'development') ? true : false
  47.  
  48. Logger.apollo('Started Apollo [GraphQL] listener')
  49. this.apolloServer = new ApolloServer({
  50. typeDefs,
  51. resolvers,
  52. introspection: environment,
  53. playground: environment,
  54. context: {
  55. db: prisma
  56. }
  57. })
  58. Logger.apollo(`${this.config.mode.charAt(0).toUpperCase() + this.config.mode.slice(1)} environment detected, playground and introspection ${environment ? 'enabled' : 'disabled'}`)
  59.  
  60. await this.apolloServer.applyMiddleware({
  61. app: HTTPServer
  62. })
  63. await this.apolloServer.installSubscriptionHandlers(this.HTTP.listener)
  64.  
  65. Logger.database('Switched to PostgreSQL connector')
  66. Logger.database('Connected to Prisma [GraphQL] successfully')
  67.  
  68. await this.HTTP.start()
  69.  
  70. } catch (error) {
  71. Logger.error(error)
  72. process.exit(1)
  73. }
  74.  
  75. Logger.server(`Server running on port ${Chalk.bold(this.HTTP.info.port)}`)
  76.  
  77. this.socketIO.on('connection', (socket) => {
  78. RoomPlayer.onConnect(socket)
  79.  
  80. socket.on('disconnect', () => {
  81. RoomPlayer.onDisconnect(socket)
  82. })
  83. })
  84. }
  85.  
  86. shutdown() {
  87. this.socketIO.emit('shutdown')
  88.  
  89. this.HTTP.stop({
  90. timeout: 100000
  91. }).then((error) => {
  92. Logger.error(error)
  93. })
  94.  
  95. Logger.info('Server shutted down.')
  96. process.exit(0)
  97. }
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement