0.0
No commit activity in last 3 years
No release in over 3 years
A tool to create a JSON response right inside of PostgreSQL 9.3+
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Runtime

>= 4.0.0, <= 7.0.0
~> 1.0.5
 Project Readme

alt text

Hadouken - rapid JSON generator directly inside the PostgreSQL 9.3+

TL;DR

class MyJsonResponse < Hadouken::Json
  attribute :my_var, String # I'm using Virtus.model, you can pass your arguments like that

  def structure
    {
      # Static columns marked with leading underscore
      _title: "Some static title",
      _myVariable: my_var,

      users: array_of({
        companyName: '.company.name', # A name field from, the company (belongs_to association)
        id: 'id',
        fullName: 'name', # name - is a column name
        address: "COALESCE(NULLIF(users.address, ''), users.geolocation)",

        posts: array_of({
          id: 'id',
          title: 'title',
          fullText: 'description',
          isPublished: 'published',
        }, for: 'posts') # 'for' could be a relation or a string with relation name

      }, for: relation)
    }
  end
end

MyJsonResponse.call(relation: User.all, my_var: 'anything') # => JSON string

Long story

Let's assume that we have following setup

class Company
  has_many :users
end

class User
  belongs_to :company
  has_many :posts, -> { where(published: true) }
end

class Post
  belongs_to :user
end

We want our controller

class ApiController < ::ApplicationController
  def users_with_posts
    render json: {???}.as_json, status: :ok
  end
end

to return a following json

{
  "time": "2021-08-26 20:29",
  "users": [
    {
      "uniqueId": 123
      "fullName": "James Smith",
      "companyName": "Best brewery Inc.",
      "posts": [
        {"title": "I really like beer", "description": "Lorem ipsum dolor sit amet..." },
        {"title": "I don't have problems with alcohol", "description": "Lorem ipsum dolor sit amet..."}
      ]
    },
    ...
  ]
}