# frozen_string_literal: true # typed: false - MongoClient new require "mongo" # Client to talk to Mongo database module MongoClient class << self # @return Client to work with MongoDb attr_accessor :client def insert(model, data, id) collection = MongoClient.client[model] collection.insert_one({ id: id, **data }) end def find(model, id) find_all(model, { id: id }, false)[:items] end def page_data(model, params, collection) page = params[:page].to_i.positive? ? params[:page].to_i : 1 page_size = params[:page_size].to_i.positive? ? params[:page_size].to_i : 10 total_count = collection.count_documents({}) total_pages = (total_count / page_size.to_f).ceil page_res = { current_page: page, page_size: page_size, total_count: total_count, total_pages: total_pages, _links: { self: { href: "/#{model}?page=#{page}&page_size=#{page_size}" } } } page_res[:_links][:next] = { href: "/#{model}?page=#{page + 1}&page_size=#{page_size}" } if page < total_pages page_res[:_links][:prev] = { href: "/#{model}?page=#{page - 1}&page_size=#{page_size}" } if page > 1 page_res end def find_all(model, params, paginate: true) collection = MongoClient.client[model] pagination = page_data(model, params, collection) skip = (pagination[:current_page] - 1) * pagination[:page_size] query = query_from_params params items = get_items collection, query, skip, pagination[:page_size] results = { _embedded: {} } results[:_embedded][model.to_sym] = items results[:pagination] = pagination if paginate results end def get_items(collection, query, skip, page_size) if query == {} return collection.find.skip(skip).limit(page_size).collect do |match| match.delete("_id") match end end collection.find(query).skip(skip).limit(page_size).collect do |match| match.delete("_id") match end end def query_from_params(params) query = params.dup query.delete(:page) query.delete(:page_size) query end def update(model, id, data) collection = MongoClient.client[model] collection.update_one({ id: id }, { id: id, **data }) end def delete(model, id) collection = MongoClient.client[model] collection.delete_one({ id: id }) end end end MongoClient.client = if ENV["mongo_root_password"] Mongo::Client.new( ["#{ENV["mongodb"]}:27017"], database: "api", password: ENV["mongo_root_password"], user: "root" ) else Mongo::Client.new( ["#{ENV["mongodb"]}:27017"], database: "api" ) end