diff --git a/app/controllers/api/v1/check_reports_controller.rb b/app/controllers/api/v1/check_reports_controller.rb new file mode 100644 index 0000000..396eaaf --- /dev/null +++ b/app/controllers/api/v1/check_reports_controller.rb @@ -0,0 +1,38 @@ +class Api::V1::CheckReportsController < Api::V1::BaseController + + # POST /check-reports or /check-reports.json + def create + @check_report = CheckReport.new(check_report_params) + + if @check_report.checks.empty? + render json: { message: "At least 1 check must be present" }, status: :unprocessable_entity + else + checks_params = ActionController::Parameters.new(@check_report.checks).permit(:name, :description).map { |check| + { + hostname: @check_report.hostname, + date: @check_report.date, + name: check.fetch(:name, ""), + description: check.fetch(:description, "") + } + } + checks = Check.create(checks_params) + + persisted = checks.count(&:persisted?) + invalid = checks.count(&:invalid?) + + if checks.all?(:persisted?) + render json: { message: "#{persisted} checks created" }, status: :created + else + render json: { message: "error while creating checks : #{persisted} persisted, #{invalid} invalid" }, status: :unprocessable_entity + end + end + end + + private + + # Only allow a list of trusted parameters through. + def check_report_params + params.require(:check_report).permit(:hostname, :date, {checks: [:name, :description]}) + end + +end \ No newline at end of file diff --git a/app/controllers/api/v1/checks_controller.rb b/app/controllers/api/v1/checks_controller.rb deleted file mode 100644 index 167d8a9..0000000 --- a/app/controllers/api/v1/checks_controller.rb +++ /dev/null @@ -1,26 +0,0 @@ -class Api::V1::ChecksController < Api::V1::BaseController - - # POST /checks or /checks.json - def create - @check = Check.new(check_params) - - if @check.save - render json: { message: "created" }, status: :created - else - render json: @check.errors, status: :unprocessable_entity - end - end - - private - - # Use callbacks to share common setup or constraints between actions. - def set_check - @check = Check.find(params[:id]) - end - - # Only allow a list of trusted parameters through. - def check_params - params.require(:check).permit(:name, :description, :hostname) - end - -end \ No newline at end of file diff --git a/app/models/check_report.rb b/app/models/check_report.rb new file mode 100644 index 0000000..6bb2300 --- /dev/null +++ b/app/models/check_report.rb @@ -0,0 +1,8 @@ +class CheckReport + include ActiveModel::API + include ActiveModel::Attributes + + attribute :hostname, :string + attribute :date, :datetime, default: -> { Time.now } + attribute :checks, array: true +end diff --git a/app/views/checks/index.html.erb b/app/views/checks/index.html.erb index 6da1e15..3f4c2ca 100644 --- a/app/views/checks/index.html.erb +++ b/app/views/checks/index.html.erb @@ -43,7 +43,7 @@ <%= check.description %>