A platform for community discussion. Free, open, simple.
DEV: Refactor and add missing tests for upload type in objects schema (#36285)
Alan Guo Xiang Tane4be1b4beeac
diff --git a/app/models/site_setting.rb b/app/models/site_setting.rbindex 9cec174e216..d1a802e319d 100644--- a/app/models/site_setting.rb+++ b/app/models/site_setting.rb@@ -92,8 +92,14 @@ class SiteSetting < ActiveRecord::Baseelsif self.data_type == SiteSettings::TypeSupervisor.types[:uploaded_image_list]upload_ids = self.value.split("|").compact.uniqUploadReference.ensure_exist!(upload_ids: upload_ids, target: self)- elsif self.data_type == SiteSettings::TypeSupervisor.types[:objects]- upload_ids = extract_upload_ids_from_objects_value+ elsif self.data_type == SiteSettings::TypeSupervisor.types[:objects] && self.value.present?+ upload_ids =+ SchemaSettingsObjectValidator.property_values_of_type(+ schema: SiteSetting.type_supervisor.type_hash(self.name.to_sym)[:schema],+ objects: JSON.parse(self.value),+ type: "upload",+ )+UploadReference.ensure_exist!(upload_ids: upload_ids, target: self) if upload_ids.any?endend@@ -382,31 +388,6 @@ class SiteSetting < ActiveRecord::Base@blocked_attachment_filenames_regex = nil@allowed_unicode_username_regex = nilend-- private-- def extract_upload_ids_from_objects_value- return [] if self.value.blank?-- type_hash = SiteSetting.type_supervisor.type_hash(self.name)- return [] unless type_hash[:schema]&.dig(:properties)-- begin- parsed_value = JSON.parse(self.value)- parsed_value = [parsed_value] unless parsed_value.is_a?(Array)- upload_ids = Set.new-- parsed_value.each do |obj|- validator = SchemaSettingsObjectValidator.new(schema: type_hash[:schema], object: obj)-- upload_ids.merge(validator.property_values_of_type("upload"))- end-- upload_ids.to_a- rescue JSON::ParserError- []- end- endend# == Schema Informationdiff --git a/app/models/theme_setting.rb b/app/models/theme_setting.rbindex e49747d9dd4..d02b7c37f0a 100644--- a/app/models/theme_setting.rb+++ b/app/models/theme_setting.rb@@ -19,13 +19,18 @@ class ThemeSetting < ActiveRecord::Baseafter_save :clear_settings_cacheafter_save do- if saved_change_to_value?- if self.data_type == ThemeSetting.types[:upload]- UploadReference.ensure_exist!(upload_ids: [self.value], target: self)- elsif self.data_type == ThemeSetting.types[:objects]- upload_ids = extract_upload_ids_from_objects_value- UploadReference.ensure_exist!(upload_ids: upload_ids, target: self) if upload_ids.any?- end+ if self.data_type == ThemeSetting.types[:upload] && saved_change_to_value?+ UploadReference.ensure_exist!(upload_ids: [self.value], target: self)+ elsif self.data_type == ThemeSetting.types[:objects] && saved_change_to_json_value? &&+ self.json_value.present?+ upload_ids =+ SchemaSettingsObjectValidator.property_values_of_type(+ schema: theme.settings[self.name.to_sym].schema,+ objects: self.json_value,+ type: "upload",+ )++ UploadReference.ensure_exist!(upload_ids: upload_ids, target: self) if upload_ids.any?endif theme.theme_modifier_set.refresh_theme_setting_modifiers(@@ -60,28 +65,6 @@ class ThemeSetting < ActiveRecord::Baseprivate- def extract_upload_ids_from_objects_value- return [] if self.value.blank?-- schema = theme.settings[self.name.to_sym]&.schema- return [] unless schema&.dig(:properties)-- begin- parsed_value = JSON.parse(self.value)- parsed_value = [parsed_value] unless parsed_value.is_a?(Array)- upload_ids = Set.new-- parsed_value.each do |obj|- validator = SchemaSettingsObjectValidator.new(schema: schema, object: obj)- upload_ids.merge(validator.property_values_of_type("upload"))- end-- upload_ids.to_a- rescue JSON::ParserError- []- end- end-def json_value_sizeif json_value.to_json.size > MAXIMUM_JSON_VALUE_SIZE_BYTESerrors.add(diff --git a/app/models/theme_site_setting.rb b/app/models/theme_site_setting.rbindex 286a0ecb286..186a46180a6 100644--- a/app/models/theme_site_setting.rb+++ b/app/models/theme_site_setting.rb@@ -16,8 +16,14 @@ class ThemeSiteSetting < ActiveRecord::Baseif saved_change_to_value?if self.data_type == SiteSettings::TypeSupervisor.types[:upload]UploadReference.ensure_exist!(upload_ids: [self.value], target: self)- elsif self.data_type == SiteSettings::TypeSupervisor.types[:objects]- upload_ids = extract_upload_ids_from_objects_value+ elsif self.data_type == SiteSettings::TypeSupervisor.types[:objects] && self.value.present?+ upload_ids =+ SchemaSettingsObjectValidator.property_values_of_type(+ schema: SiteSetting.type_supervisor.type_hash(self.name.to_sym)[:schema],+ objects: JSON.parse(self.value),+ type: "upload",+ )+UploadReference.ensure_exist!(upload_ids: upload_ids, target: self) if upload_ids.any?endend@@ -121,30 +127,6 @@ class ThemeSiteSetting < ActiveRecord::Basedef setting_rb_valueSiteSetting.type_supervisor.to_rb_value(self.name, self.value, self.data_type)end-- private-- def extract_upload_ids_from_objects_value- return [] if self.value.blank?-- type_hash = SiteSetting.type_supervisor.type_hash(self.name.to_sym)- return [] unless type_hash[:schema]&.dig(:properties)-- begin- parsed_value = JSON.parse(self.value)- parsed_value = [parsed_value] unless parsed_value.is_a?(Array)- upload_ids = Set.new-- parsed_value.each do |obj|- validator = SchemaSettingsObjectValidator.new(schema: type_hash[:schema], object: obj)- upload_ids.merge(validator.property_values_of_type("upload"))- end-- upload_ids.to_a- rescue JSON::ParserError- []- end- endend# == Schema Informationdiff --git a/lib/schema_settings_object_validator.rb b/lib/schema_settings_object_validator.rbindex b2e2873e0b7..92ce110f043 100644--- a/lib/schema_settings_object_validator.rb+++ b/lib/schema_settings_object_validator.rb@@ -16,6 +16,16 @@ class SchemaSettingsObjectValidatorerror_messagesend+ def property_values_of_type(schema:, objects:, type:)+ values = Set.new++ objects.each do |object|+ values.merge(self.new(schema: schema, object: object).property_values_of_type(type))+ end++ values.to_a+ end+privatedef humanize_error_messages(errors, index:, error_messages:)diff --git a/lib/site_setting_extension.rb b/lib/site_setting_extension.rbindex c6c3bc7abcb..fbe78e98b1f 100644--- a/lib/site_setting_extension.rb+++ b/lib/site_setting_extension.rb@@ -393,7 +393,6 @@ module SiteSettingExtension# For uploads nested in objects type, hydrate upload IDs to URLsif type_hash[:type].to_s == "objects" && type_hash[:schema]parsed_value = JSON.parse(value)-value = hydrate_uploads_in_objects(parsed_value, type_hash[:schema])end@@ -1146,14 +1145,14 @@ module SiteSettingExtensiondef hydrate_uploads_in_objects(objects, schema)return objects if objects.blank?- all_upload_ids = Set.new- objects.each do |object|- validator = SchemaSettingsObjectValidator.new(schema: schema, object: object)- all_upload_ids.merge(validator.property_values_of_type("upload"))- end-- uploads_by_id = Upload.where(id: all_upload_ids.to_a).index_by(&:id)+ upload_ids =+ SchemaSettingsObjectValidator.property_values_of_type(+ schema: schema,+ objects: objects,+ type: "upload",+ )+ uploads_by_id = Upload.where(id: upload_ids).index_by(&:id)objects.map { |obj| hydrate_uploads_in_object(obj, schema[:properties], uploads_by_id) }enddiff --git a/spec/lib/theme_settings_object_validator_spec.rb b/spec/lib/schema_settings_object_validator_spec.rbsimilarity index 96%rename from spec/lib/theme_settings_object_validator_spec.rbrename to spec/lib/schema_settings_object_validator_spec.rbindex 62c3f5dbcad..48d7d7b86c6 100644--- a/spec/lib/theme_settings_object_validator_spec.rb+++ b/spec/lib/schema_settings_object_validator_spec.rb@@ -1,6 +1,67 @@# frozen_string_literal: trueRSpec.describe SchemaSettingsObjectValidator do+ describe ".property_values_of_type" do+ it "returns an empty array when objects array is empty" do+ schema = { name: "section", properties: { upload: { type: "upload" } } }++ result = described_class.property_values_of_type(schema:, objects: [], type: "upload")++ expect(result).to eq([])+ end++ it "returns the correct array of property values of the specified type" do+ schema = {+ name: "section",+ properties: {+ header_image: {+ type: "upload",+ },+ links: {+ type: "objects",+ schema: {+ name: "link",+ properties: {+ icon: {+ type: "upload",+ },+ category: {+ type: "categories",+ },+ related_topic: {+ type: "topic",+ },+ },+ },+ },+ },+ }++ objects = [+ {+ header_image: 10,+ links: [+ { icon: 20, category: [100, 101], related_topic: 200 },+ { icon: nil, category: [102], related_topic: nil },+ ],+ },+ { header_image: nil, links: [{ icon: 30 }] },+ ]++ expect(+ described_class.property_values_of_type(schema:, objects:, type: "upload"),+ ).to match_array([10, 20, 30])++ expect(+ described_class.property_values_of_type(schema:, objects:, type: "categories"),+ ).to match_array([100, 101, 102])++ expect(+ described_class.property_values_of_type(schema:, objects:, type: "topic"),+ ).to match_array([200])+ end+ end+describe ".validate_objects" doit "should return the right array of humanized error messages for objects that are invalid" doschema = {diff --git a/spec/lib/site_setting_extension_spec.rb b/spec/lib/site_setting_extension_spec.rbindex 31cd87814ec..250d7b31b67 100644--- a/spec/lib/site_setting_extension_spec.rb+++ b/spec/lib/site_setting_extension_spec.rb@@ -883,6 +883,7 @@ RSpec.describe SiteSettingExtension doit "should hydrate upload IDs to URLs" doupload1 = Fabricate(:upload)upload2 = Fabricate(:upload)+ upload3 = Fabricate(:upload)schema = {name: "section",@@ -893,12 +894,27 @@ RSpec.describe SiteSettingExtension doimage: {type: "upload",},+ links: {+ type: "objects",+ schema: {+ name: "link",+ properties: {+ link_image: {+ type: "upload",+ },+ },+ },+ },},}settings.setting(:test_objects_with_uploads, "[]", type: :objects, schema: schema)settings.test_objects_with_uploads = [- { "title" => "Section 1", "image" => upload1.id },+ {+ "title" => "Section 1",+ "image" => upload1.id,+ "links" => [{ "link_image" => upload3.id }],+ },{ "title" => "Section 2", "image" => upload2.id },].to_jsonsettings.refresh!@@ -910,6 +926,7 @@ RSpec.describe SiteSettingExtension doexpect(value[1]["image"]).to eq(upload2.url)expect(value[0]["title"]).to eq("Section 1")expect(value[1]["title"]).to eq("Section 2")+ expect(value[0]["links"][0]["link_image"]).to eq(upload3.url)endit "should batch uploads query" dodiff --git a/spec/models/site_setting_spec.rb b/spec/models/site_setting_spec.rbindex 6df4705cdbb..2d29949bd15 100644--- a/spec/models/site_setting_spec.rb+++ b/spec/models/site_setting_spec.rb@@ -296,6 +296,39 @@ RSpec.describe SiteSetting doendend+ describe "creating upload references for type objects settings with upload fields" do+ let(:provider) { SiteSettings::DbProvider.new(SiteSetting) }+ fab!(:upload)+ fab!(:upload2, :upload)++ it "creates upload references for objects with upload fields" do+ objects_value =+ JSON.generate(+ [+ { "name" => "object1", "upload_id" => upload.id },+ { "name" => "object2", "upload_id" => upload2.id },+ ],+ )++ expect {+ provider.save(+ "test_objects_with_uploads",+ objects_value,+ SiteSettings::TypeSupervisor.types[:objects],+ )+ }.to change { UploadReference.count }.by(2)++ upload_references =+ UploadReference.where(target: SiteSetting.find_by(name: "test_objects_with_uploads"))++ expect(upload_references.pluck(:upload_id)).to contain_exactly(upload.id, upload2.id)++ expect { provider.destroy("test_objects_with_uploads") }.to change {+ UploadReference.count+ }.by(-2)+ end+ end+describe "Upload" dobefore { setup_s3 }diff --git a/spec/models/theme_setting_spec.rb b/spec/models/theme_setting_spec.rbindex d1560033530..d543a0a9843 100644--- a/spec/models/theme_setting_spec.rb+++ b/spec/models/theme_setting_spec.rb@@ -3,6 +3,51 @@RSpec.describe ThemeSetting dofab!(:theme)+ describe "creating upload references for objects settings with upload fields" do+ fab!(:upload)+ fab!(:upload2, :upload)++ let(:objects_setting_yaml) { <<~YAML }+ objects_with_upload:+ type: objects+ default: []+ schema:+ name: test_object+ properties:+ name:+ type: string+ image:+ type: upload+ YAML++ it "creates upload references for type objects settings with upload fields" do+ theme.set_field(target: :settings, name: "yaml", value: objects_setting_yaml)+ theme.save!++ theme.settings[:objects_with_upload].value = [+ { "name" => "object1", "image" => upload.id },+ { "name" => "object2", "image" => upload2.id },+ ]++ theme_setting = theme.theme_settings.find_by(name: "objects_with_upload")+ upload_references = UploadReference.where(target: theme_setting)+ expect(upload_references.pluck(:upload_id)).to contain_exactly(upload.id, upload2.id)+ end++ it "destroys upload references for type objects setting when the setting is destroyed" do+ theme.set_field(target: :settings, name: "yaml", value: objects_setting_yaml)+ theme.save!++ theme.settings[:objects_with_upload].value = [+ { "name" => "object1", "image" => upload.id },+ { "name" => "object2", "image" => upload2.id },+ ]++ theme_setting = theme.theme_settings.find_by(name: "objects_with_upload")+ expect { theme_setting.destroy! }.to change { UploadReference.count }.by(-2)+ end+ end+context "for validations" doit "should be invalid when json_value size is greater than the maximum allowed size" dojson_value = { "key" => "value" }diff --git a/spec/models/theme_site_setting_spec.rb b/spec/models/theme_site_setting_spec.rbindex c85ef1f2570..32c8aa6dd80 100644--- a/spec/models/theme_site_setting_spec.rb+++ b/spec/models/theme_site_setting_spec.rb@@ -68,4 +68,46 @@ RSpec.describe ThemeSiteSetting doendendend++ describe "creating upload references for type objects settings with upload fields" do+ fab!(:upload)+ fab!(:upload2, :upload)++ it "creates upload references for settings with upload fields" do+ theme_site_setting =+ ThemeSiteSetting.create!(+ theme: theme_1,+ name: "test_objects_with_uploads",+ data_type: SiteSettings::TypeSupervisor.types[:objects],+ value:+ JSON.generate(+ [+ { "name" => "object1", "upload_id" => upload.id },+ { "name" => "object2", "upload_id" => upload2.id },+ ],+ ),+ )++ upload_references = UploadReference.where(target: theme_site_setting)+ expect(upload_references.pluck(:upload_id)).to contain_exactly(upload.id, upload2.id)+ end++ it "destroys upload references when the setting is destroyed" do+ theme_site_setting =+ ThemeSiteSetting.create!(+ theme: theme_1,+ name: "test_objects_with_uploads",+ data_type: SiteSettings::TypeSupervisor.types[:objects],+ value:+ JSON.generate(+ [+ { "name" => "object1", "upload_id" => upload.id },+ { "name" => "object2", "upload_id" => upload2.id },+ ],+ ),+ )++ expect { theme_site_setting.destroy! }.to change { UploadReference.count }.by(-2)+ end+ endenddiff --git a/spec/services/site_settings_spec.rb b/spec/services/site_settings_spec.rbindex 5a197afc65d..c9b0222b182 100644--- a/spec/services/site_settings_spec.rb+++ b/spec/services/site_settings_spec.rb@@ -50,37 +50,5 @@ RSpec.describe SiteSettingsTask doexpect(counts[:errors]).to eq 1expect(SiteSetting.min_password_length).to eq 10end-- context "for objects with upload fields" do- let(:provider) { SiteSettings::DbProvider.new(SiteSetting) }- fab!(:upload)- fab!(:upload2, :upload)-- it "creates upload references for objects with upload fields" do- objects_value =- JSON.generate(- [- { "name" => "object1", "upload_id" => upload.id },- { "name" => "object2", "upload_id" => upload2.id },- ],- )-- expect {- provider.save(- "test_objects_with_uploads",- objects_value,- SiteSettings::TypeSupervisor.types[:objects],- )- }.to change { UploadReference.count }.by(2)-- upload_references =- UploadReference.all.where(target: SiteSetting.find_by(name: "test_objects_with_uploads"))- expect(upload_references.pluck(:upload_id)).to contain_exactly(upload.id, upload2.id)-- expect { provider.destroy("test_objects_with_uploads") }.to change {- UploadReference.count- }.by(-2)- end- endendend