require "kemal" require "crest" require "json" require "dotenv" require "./utils/utils" require "time" Dotenv.load TOKEN = ENV["TOKEN"] STRAPI_URL = ENV["STRAPI_URL"] module Indrajith::Dev::Crystal VERSION = "0.1.0" macro page_renderer(filename, title) page_title = {{title}} published_at="" render "src/views/#{{{filename}}}.ecr", "src/views/layout.ecr" end macro render_404() page_renderer "404", "The VOID" end get "/" do |context| context.response.content_type = "text/html" page_renderer "home", "Home" end get "/about" do |context| context.response.content_type = "text/html" page_renderer "about", "About " end get "/timeline" do |context| context.response.content_type = "text/html" page_renderer "timeline", "Timeline" end get "/contact" do |context| context.response.content_type = "text/html" page_renderer "contact", "Contact" end get "/blog" do |context| context.response.content_type = "text/html" page_renderer "blog", "Blog" end get "/posts" do |context| begin site = Crest::Resource.new("#{STRAPI_URL}") response = site.get("/api/posts", params: { "fields[0]" => "post_title", "fields[1]" => "slug", "pagination[pageSize]" => 3, }, headers: {"Authorization" => "Bearer #{TOKEN}"} ) json_data = JSON.parse(response.body) data = json_data["data"].as_a puts data.size if data.size == 0 "
  • No Posts Yet
  • " else html_string = "" data.each do |item| attributes = item["attributes"] # puts attributes["post_title"] html_string += "
  • #{attributes["post_title"]}

  • " end html_string end rescue ex : Crest::NotFound puts ex.response render_404 end end get "/post/:slug" do |context| begin slug = context.params.url["slug"] site = Crest::Resource.new("#{STRAPI_URL}") response = site.get("/api/posts", params: { "filters[slug][$eq]" => "#{slug}", }, headers: {"Authorization" => "Bearer #{TOKEN}"} ) json_data = JSON.parse(response.body) data = json_data["data"].as_a post_item = data[0] post_attribute = post_item["attributes"] content = post_attribute["post_content"] published_raw_time = post_attribute["publishedAt"].as_s published_time = Time.parse(published_raw_time, "%Y-%m-%dT%H:%M:%S.%3NZ", Time::Location.local) published_at = format_date(published_time) page_title = post_attribute["post_title"] render "src/views/layout.ecr" rescue ex puts ex render_404 end end error 404 do |context| context.response.content_type = "text/html" render_404 end Kemal.run end