mentorenwahl/docker/backend/src/backend/api/webserver.cr

90 lines
2.7 KiB
Crystal
Raw Normal View History

2022-02-10 07:43:47 +00:00
# Mentorenwahl: A fullstack application for assigning mentors to students based on their whishes.
# Copyright (C) 2022 Dominic Grimm
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
2022-01-29 15:40:39 +00:00
require "router"
require "http/server"
require "json"
module Backend
module Api
2022-02-09 13:35:35 +00:00
# Api webserver
2022-01-29 15:40:39 +00:00
class WebServer
include Router
2022-02-09 13:35:35 +00:00
# GraphQL playground HTML code
#
# NOTE: Is minified in production
GRAPHQL_PLAYGROUND = {{ flag?(:development) ? read_file("#{__DIR__}/playground.html") : run("./macros/minify_html.cr", read_file("#{__DIR__}/playground.html")).stringify }}
2022-02-09 13:35:35 +00:00
# GraphQL request data serializer
struct GraphQLQueryData
include JSON::Serializable
property query : String
property variables : Hash(String, JSON::Any)?
property operation_name : String?
end
2022-02-03 14:49:42 +00:00
2022-02-09 13:35:35 +00:00
# "Draws" (creates) routes
2022-01-29 15:40:39 +00:00
def draw_routes : Nil
2022-02-03 14:49:42 +00:00
# enable graphql playground when in development mode or explicitly enabled
2022-02-07 17:52:17 +00:00
if Backend.config.api.graphql_playground_fully_enabled?
2022-02-03 14:49:42 +00:00
Log.info { "GraphQL playground enabled" }
get "/" do |context|
context.response.content_type = "text/html"
context.response.puts(GRAPHQL_PLAYGROUND)
2022-02-03 14:49:42 +00:00
context
end
end
2022-01-29 15:40:39 +00:00
post "/" do |context|
context.response.content_type = "application/json"
data = GraphQLQueryData.from_json(context.request.body.not_nil!.gets.not_nil!)
2022-02-03 14:49:42 +00:00
context.response.print(
2022-01-29 15:40:39 +00:00
Schema::SCHEMA.execute(
data.query,
data.variables,
data.operation_name,
Context.new(context.request)
)
)
context
end
end
2022-02-09 13:35:35 +00:00
# Runs the webserver with according middleware
2022-01-29 15:40:39 +00:00
def run : Nil
draw_routes
server = HTTP::Server.new(
[
HTTP::LogHandler.new,
HTTP::ErrorHandler.new,
HTTP::CompressHandler.new,
route_handler,
]
)
server.bind_tcp("0.0.0.0", 80, true)
server.listen
end
end
end
end