mentorenwahl/docker/backend/src/backend/api/schema/helpers.cr

96 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-23 08:12:57 +00:00
module Backend
module Api
2022-01-23 08:12:57 +00:00
module Schema
2022-02-09 13:35:35 +00:00
# Schema helper macros
2022-01-23 08:12:57 +00:00
module Helpers
2022-02-09 13:35:35 +00:00
# Object helpers
2022-01-23 08:12:57 +00:00
module ObjectMacros
2022-02-09 13:35:35 +00:00
# Defines field property and GraphQL specific getter
2022-01-23 08:12:57 +00:00
macro field(type)
property {{ type.var }} {% if type.value %} = {{ type.value }}{% end %}
@[GraphQL::Field]
def {{ type.var }} : {{ type.type }}
@{{ type.var }}
end
end
end
2022-02-09 13:35:35 +00:00
# DB model leverage helpers
2022-01-23 08:12:57 +00:00
module ObjectDbInit
2022-02-09 13:35:35 +00:00
# Defines a DB model specific initializer
2022-01-23 08:12:57 +00:00
macro db_init(type)
def initialize(obj : {{ type }})
initialize(obj.id.not_nil!)
end
end
end
2022-02-09 13:35:35 +00:00
# DB model finder helpers
2022-01-23 08:12:57 +00:00
module ObjectFinders
2022-02-09 13:35:35 +00:00
# Defines finder
2022-01-23 08:12:57 +00:00
macro finders(type)
2022-02-09 13:35:35 +00:00
# Finds object by ID
2022-01-23 08:12:57 +00:00
def find : {{ type }}?
{{ type }}.find(@id)
end
2022-02-09 13:35:35 +00:00
# :ditto:
2022-01-23 08:12:57 +00:00
def find! : {{ type }}
obj = find
raise "#{{{ type }}} not found" unless obj
obj
end
end
end
2022-02-09 13:35:35 +00:00
# DB model field helpers
2022-01-23 08:12:57 +00:00
module DbObject
2022-02-09 13:35:35 +00:00
# Defines DB model field helper functions
2022-01-23 08:12:57 +00:00
macro db_object(type)
2022-02-09 13:35:35 +00:00
{% space_name = type.names.last.underscore.gsub(/_/, " ").capitalize %}
include ::Backend::Api::Schema::Helpers::ObjectDbInit
include ::Backend::Api::Schema::Helpers::ObjectFinders
2022-01-23 08:12:57 +00:00
db_init {{ type }}
finders {{ type }}
property id
def initialize(@id : Int32)
end
def initialize(obj : {{ type }})
@id = obj.id.not_nil!.to_i
end
@[GraphQL::Field]
2022-02-09 13:35:35 +00:00
# {{ space_name }}'s ID
2022-01-23 08:12:57 +00:00
def id : Int32
@id
end
end
end
end
end
end
end