crystal

Hello Postgres and REST in Crystal

Tagged postgres, crystal, rest  Languages bash, crystal, yaml

NOTE: This does not work with Crystal 0.25.2.

Install Crystal

brew install crystal-lang
mkdir projects/hello
shards init

Set up dependencies

dependencies:
  pg:
    github: will/crystal-pg
    version: "~> 0.5"
  kemal:
    github: sdogruyol/kemal
    version: "~> 0.16.1"
shards

Write a simple REST API

require "kemal"
require "json"
require "pg"

PG_URL = "postgres://postgres@localhost:5432/xxx"
DB     = PG.connect PG_URL

get "/" do |env|
  env.response.content_type = "application/json"
  users = DB.exec("SELECT * FROM users")
  users.to_hash.map do |user|
    {first_name: user["first_name"].as(String), last_name: user["last_name"].as(String)}
  end.to_json
end

Kemal.run(4567)

How to implement to_json in Crystal lang

Tagged to_json, crystal  Languages crystal

Tested on version 0.19.4. This is an example of how to implement a generic to_json method in Crystal lang:

class Document
  def initialize
    @name = "xyz"
    ...
  end
  
  # Returns an array containing all instance variables. Implemented with a macro.
  def instance_vars
    {{
      @type.instance_vars.map do |var|
        [ var.name.stringify, var.id ]
      end
    }}
  end

  # Returns a JSON string containing all instance variables
  def to_json
    result = String.build do |io|
      JSON::PrettyWriter.new(io, indent: "  ").json_object do |object|
        instance_vars.each do |var|
          name, value = var
          case value
          when XML::Node
            # skip
          else
            object.field name, value
          end
        end
      end
    end
  end