diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..31eeee0b --- /dev/null +++ b/.gitattributes @@ -0,0 +1,7 @@ +# See https://git-scm.com/docs/gitattributes for more about git attribute files. + +# Mark the database schema as having been generated. +db/schema.rb linguist-generated + +# Mark any vendored files as having been vendored. +vendor/* linguist-vendored diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 9f6787d0..b2e54c32 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -17,7 +17,7 @@ jobs: runs-on: ubuntu-22.04 strategy: matrix: - ruby: ['2.7.7', '2.7.8', '3.0.6'] + ruby: ['2.7.7', '2.7.8', '3.0.6', '3.1.4', '3.2.2'] mongodb-version: ['4.2', '4.4', '5.0', '6.0'] steps: @@ -34,20 +34,24 @@ jobs: - name: Gems id: gems run: | - gem install bundler:2.4.10 + gem install bundler:2.4.12 bundle install -j 5 - - name: Tests Active Record - id: rspec-ar - run: | - DRIVER=ar bundle exec rspec - - name: Start MongoDB uses: supercharge/mongodb-github-action@1.8.0 with: mongodb-version: ${{ matrix.mongodb-version }} - - name: Tests Active Mongoid - id: rspec-mongo + - name: Original Tests Mongoid Bundle + id: rspec-mongo-original-bundle + run: | + cd spec/tester_mongo + pwd + gem install bundler:2.4.12 + bundle install -j 5 + + - name: Original Tests Mongoid + id: rspec-mongo-original run: | - DRIVER=mongo bundle exec rspec + cd spec/tester_mongo + DRIVER=mongo rspec diff --git a/.gitignore b/.gitignore index e2496e19..e55fba0d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,34 @@ -.byebug_history -graphoid-*.gem -coverage +# See https://help.github.com/articles/ignoring-files for more about ignoring files. +# +# If you find yourself ignoring temporary files generated by your text editor +# or operating system, you probably want to add a global ignore instead: +# git config --global core.excludesfile '~/.gitignore_global' + +# Ignore bundler config. +/.bundle + +# Ignore the default SQLite database. +/db/*.sqlite3 +/db/*.sqlite3-* + +# Ignore all logfiles and tempfiles. +/log/* +/tmp/* +!/log/.keep +!/tmp/.keep + +# Ignore pidfiles, but keep the directory. +/tmp/pids/* +!/tmp/pids/ +!/tmp/pids/.keep + +# Ignore uploaded files in development. +/storage/* +!/storage/.keep +/tmp/storage/* +!/tmp/storage/ +!/tmp/storage/.keep + +# Ignore master key for decrypting credentials and more. +/config/master.key +*.gem diff --git a/.rspec b/.rspec new file mode 100644 index 00000000..c99d2e73 --- /dev/null +++ b/.rspec @@ -0,0 +1 @@ +--require spec_helper diff --git a/.ruby-version b/.ruby-version index 818bd47a..9e79f6c4 100644 --- a/.ruby-version +++ b/.ruby-version @@ -1 +1 @@ -3.0.6 +ruby-3.2.2 diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 9c975e6e..00000000 --- a/.travis.yml +++ /dev/null @@ -1,19 +0,0 @@ -env: - global: - - CC_TEST_REPORTER_ID=b59406eb545843eae141deb6772544cbfa135076b25779a9c28efe630312f8d9 -services: - - mongodb -language: ruby -rvm: - - 2.4.5 -before_script: - - curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter - - chmod +x ./cc-test-reporter - - ./cc-test-reporter before-build -script: - - DRIVER=ar DEBUG=1 bundle exec rspec - - DRIVER=mongo DEBUG=1 bundle exec rspec -after_script: - - ./cc-test-reporter format-coverage -t simplecov -o coverage/codeclimate.json coverage/.resultset.json - - ./cc-test-reporter sum-coverage coverage/codeclimate.json -p 1 - - if [[ "$TRAVIS_TEST_RESULT" == 0 ]]; then ./cc-test-reporter upload-coverage; fi diff --git a/Gemfile b/Gemfile index 41bf8bf1..b7ce614e 100644 --- a/Gemfile +++ b/Gemfile @@ -1,31 +1,24 @@ -# frozen_string_literal: true +source "https://rubygems.org" +git_source(:github) { |repo| "https://github.com/#{repo}.git" } -source 'https://rubygems.org' -ruby '>= 2.7.0' +ruby ">= 2.7.0" -gemspec +# Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main" +gem 'activemodel' +gem 'actionpack' -#gem 'graphql', '~> 1.8.0' -gem 'graphql', git: 'https://github.com/oxeanbits/graphql-ruby.git', branch: 'ruby3-1.8.18' +gem "mongoid" -gem 'nokogiri', '~> 1.13.9' - -gem 'activemodel', '>= 5.1' -gem 'actionpack', '>= 6.0.1' +# Use graphql gem for handle API +gem 'graphql', "~> 2.0.21" group :development, :test do - gem 'byebug' - gem 'simplecov', require: false - gem 'pry-rails', '~> 0.3.4' - - # Adds step-by-step debugging and stack navigation capabilities to pry using byebug. - gem 'pry-byebug' + gem "pry-byebug" + gem "rspec-rails" end -group :test do - gem 'mongoid' - gem 'mongoid-rspec' - gem 'rspec' - gem 'rspec-rails', '>= 6.0' - gem 'sqlite3' +group :development do + # Speed up commands on slow machines / big apps [https://github.com/rails/spring] + # gem "spring" end + diff --git a/Gemfile.lock b/Gemfile.lock index 92e8af09..e60b44fb 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,171 +1,79 @@ -GIT - remote: https://github.com/oxeanbits/graphql-ruby.git - revision: 6619f2fe4e1c0e542149a2a49769b2cfbb1b971b - branch: ruby3-1.8.18 - specs: - graphql (1.8.18) - -PATH - remote: . - specs: - graphoid (0.2.0) - nokogiri (~> 1.13.9) - rails (~> 6) - GEM remote: https://rubygems.org/ specs: - actioncable (6.1.7) - actionpack (= 6.1.7) - activesupport (= 6.1.7) - nio4r (~> 2.0) - websocket-driver (>= 0.6.1) - actionmailbox (6.1.7) - actionpack (= 6.1.7) - activejob (= 6.1.7) - activerecord (= 6.1.7) - activestorage (= 6.1.7) - activesupport (= 6.1.7) - mail (>= 2.7.1) - actionmailer (6.1.7) - actionpack (= 6.1.7) - actionview (= 6.1.7) - activejob (= 6.1.7) - activesupport (= 6.1.7) - mail (~> 2.5, >= 2.5.4) - rails-dom-testing (~> 2.0) - actionpack (6.1.7) - actionview (= 6.1.7) - activesupport (= 6.1.7) - rack (~> 2.0, >= 2.0.9) + actionpack (7.0.4.3) + actionview (= 7.0.4.3) + activesupport (= 7.0.4.3) + rack (~> 2.0, >= 2.2.0) rack-test (>= 0.6.3) rails-dom-testing (~> 2.0) rails-html-sanitizer (~> 1.0, >= 1.2.0) - actiontext (6.1.7) - actionpack (= 6.1.7) - activerecord (= 6.1.7) - activestorage (= 6.1.7) - activesupport (= 6.1.7) - nokogiri (>= 1.8.5) - actionview (6.1.7) - activesupport (= 6.1.7) + actionview (7.0.4.3) + activesupport (= 7.0.4.3) builder (~> 3.1) erubi (~> 1.4) rails-dom-testing (~> 2.0) rails-html-sanitizer (~> 1.1, >= 1.2.0) - activejob (6.1.7) - activesupport (= 6.1.7) - globalid (>= 0.3.6) - activemodel (6.1.7) - activesupport (= 6.1.7) - activerecord (6.1.7) - activemodel (= 6.1.7) - activesupport (= 6.1.7) - activestorage (6.1.7) - actionpack (= 6.1.7) - activejob (= 6.1.7) - activerecord (= 6.1.7) - activesupport (= 6.1.7) - marcel (~> 1.0) - mini_mime (>= 1.1.0) - activesupport (6.1.7) + activemodel (7.0.4.3) + activesupport (= 7.0.4.3) + activesupport (7.0.4.3) concurrent-ruby (~> 1.0, >= 1.0.2) i18n (>= 1.6, < 2) minitest (>= 5.1) tzinfo (~> 2.0) - zeitwerk (~> 2.3) - bson (4.12.1) + bson (4.15.0) builder (3.2.4) byebug (11.1.3) coderay (1.1.3) - concurrent-ruby (1.1.10) + concurrent-ruby (1.2.2) crass (1.0.6) diff-lcs (1.5.0) - docile (1.3.5) - erubi (1.11.0) - globalid (1.0.0) - activesupport (>= 5.0) + erubi (1.12.0) + graphql (2.0.21) i18n (1.12.0) concurrent-ruby (~> 1.0) - loofah (2.19.0) + loofah (2.20.0) crass (~> 1.0.2) nokogiri (>= 1.5.9) - mail (2.7.1) - mini_mime (>= 0.1.1) - marcel (1.0.2) method_source (1.0.0) - mini_mime (1.1.2) - mini_portile2 (2.8.1) - minitest (5.15.0) - mongo (2.16.3) - bson (>= 4.8.2, < 5.0.0) - mongoid (7.3.5) + minitest (5.18.0) + mongo (2.18.2) + bson (>= 4.14.1, < 5.0.0) + mongoid (8.0.3) activemodel (>= 5.1, < 7.1, != 7.0.0) - mongo (>= 2.10.5, < 3.0.0) + mongo (>= 2.18.0, < 3.0.0) ruby2_keywords (~> 0.0.5) - mongoid-compatibility (0.6.0) - activesupport - mongoid (>= 2.0) - mongoid-rspec (4.1.0) - activesupport (>= 3.0.0) - mongoid (>= 3.1) - mongoid-compatibility (>= 0.5.1) - rspec-core (~> 3.3) - rspec-expectations (~> 3.3) - rspec-mocks (~> 3.3) - nio4r (2.5.8) - nokogiri (1.13.10) - mini_portile2 (~> 2.8.0) + nokogiri (1.14.3-x86_64-linux) racc (~> 1.4) - pry (0.13.1) + pry (0.14.2) coderay (~> 1.1) method_source (~> 1.0) - pry-byebug (3.9.0) + pry-byebug (3.10.1) byebug (~> 11.0) - pry (~> 0.13.0) - pry-rails (0.3.9) - pry (>= 0.10.4) + pry (>= 0.13, < 0.15) racc (1.6.2) - rack (2.2.4) - rack-test (2.0.2) + rack (2.2.6.4) + rack-test (2.1.0) rack (>= 1.3) - rails (6.1.7) - actioncable (= 6.1.7) - actionmailbox (= 6.1.7) - actionmailer (= 6.1.7) - actionpack (= 6.1.7) - actiontext (= 6.1.7) - actionview (= 6.1.7) - activejob (= 6.1.7) - activemodel (= 6.1.7) - activerecord (= 6.1.7) - activestorage (= 6.1.7) - activesupport (= 6.1.7) - bundler (>= 1.15.0) - railties (= 6.1.7) - sprockets-rails (>= 2.0.0) rails-dom-testing (2.0.3) activesupport (>= 4.2.0) nokogiri (>= 1.6) - rails-html-sanitizer (1.4.3) - loofah (~> 2.3) - railties (6.1.7) - actionpack (= 6.1.7) - activesupport (= 6.1.7) + rails-html-sanitizer (1.5.0) + loofah (~> 2.19, >= 2.19.1) + railties (7.0.4.3) + actionpack (= 7.0.4.3) + activesupport (= 7.0.4.3) method_source rake (>= 12.2) thor (~> 1.0) + zeitwerk (~> 2.5) rake (13.0.6) - rspec (3.12.0) - rspec-core (~> 3.12.0) - rspec-expectations (~> 3.12.0) - rspec-mocks (~> 3.12.0) - rspec-core (3.12.0) + rspec-core (3.12.1) rspec-support (~> 3.12.0) - rspec-expectations (3.12.0) + rspec-expectations (3.12.2) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.12.0) - rspec-mocks (3.12.0) + rspec-mocks (3.12.5) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.12.0) rspec-rails (6.0.1) @@ -178,47 +86,24 @@ GEM rspec-support (~> 3.11) rspec-support (3.12.0) ruby2_keywords (0.0.5) - simplecov (0.18.5) - docile (~> 1.1) - simplecov-html (~> 0.11) - simplecov-html (0.12.3) - sprockets (4.1.1) - concurrent-ruby (~> 1.0) - rack (> 1, < 3) - sprockets-rails (3.4.2) - actionpack (>= 5.2) - activesupport (>= 5.2) - sprockets (>= 3.0.0) - sqlite3 (1.4.4) thor (1.2.1) - tzinfo (2.0.5) + tzinfo (2.0.6) concurrent-ruby (~> 1.0) - websocket-driver (0.7.5) - websocket-extensions (>= 0.1.0) - websocket-extensions (0.1.5) - zeitwerk (2.6.6) + zeitwerk (2.6.7) PLATFORMS - ruby + x86_64-linux DEPENDENCIES - actionpack (>= 6.0.1) - activemodel (>= 5.1) - byebug - graphoid! - graphql! + actionpack + activemodel + graphql (~> 2.0.21) mongoid - mongoid-rspec - nokogiri (~> 1.13.9) pry-byebug - pry-rails (~> 0.3.4) - rspec - rspec-rails (>= 6.0) - simplecov - sqlite3 + rspec-rails RUBY VERSION - ruby 3.0.6p216 + ruby 3.2.2p53 BUNDLED WITH - 2.4.10 + 2.4.12 diff --git a/graphoid.gemspec b/graphoid.gemspec index 02a441c3..8241b89b 100644 --- a/graphoid.gemspec +++ b/graphoid.gemspec @@ -5,20 +5,18 @@ $LOAD_PATH.push File.expand_path('lib', __dir__) # Describe your gem and declare its dependencies: Gem::Specification.new do |gem| gem.name = 'graphoid' - gem.version = '0.2.0' - gem.authors = ['Maximiliano Perez Coto'] - gem.email = ['maxiperezc@gmail.com'] - gem.homepage = 'https://github.com/maxiperezc/graphoid' + gem.version = '1.0.0' + gem.authors = ['Nilton Vasques', 'Maximiliano Perez Coto'] + gem.email = ['nilton.vasques@gmail.com'] + gem.homepage = 'https://github.com/oxeanbits/graphoid' gem.summary = 'Generates a GraphQL API from Rails ActiveRecord or Mongoid' gem.description = 'A gem that helps you autogenerate a GraphQL API from Mongoid or ActiveRecord models.' gem.license = 'MIT' - gem.files = Dir['{app,config,db,lib}/**/*', 'MIT-LICENSE', 'Rakefile', 'README.md'] + gem.files = Dir['{lib}/**/*', 'MIT-LICENSE', 'Rakefile', 'README.md'] gem.required_ruby_version = '>= 2.7.0' - # gem.add_dependency 'graphql', '~> 1.8.0' - # gem.add_dependency 'graphql', git: 'https://github.com/oxeanbits/graphoid.git', branch: 'ruby3-1.8.18' - gem.add_dependency 'rails', '~> 6' - gem.add_dependency 'nokogiri', '~> 1.13.9' + gem.add_dependency 'graphql', '~> 2.0.21' + gem.add_dependency 'rails', '>= 6.0' end diff --git a/lib/graphoid/config.rb b/lib/graphoid/config.rb index 0f98894e..49c0a69f 100644 --- a/lib/graphoid/config.rb +++ b/lib/graphoid/config.rb @@ -1,6 +1,26 @@ # frozen_string_literal: true module Graphoid + @graphs = {} + + class << self + attr_reader :driver + + def initialize + Graphoid.driver = configuration&.driver + Graphoid::Scalars.generate + end + + def build(model, _action = nil) + @graphs[model] ||= Graphoid::Grapho.new(model) + end + + def driver=(driver) + #@driver = driver == :active_record ? ActiveRecordDriver : MongoidDriver + @driver = MongoidDriver + end + end + class << self attr_accessor :configuration @@ -15,7 +35,7 @@ class Configuration attr_accessor :driver def initialize - @driver = :active_record + @driver = :mongoid end end end diff --git a/lib/graphoid/definitions/filters.rb b/lib/graphoid/definitions/filters.rb index dd997bc9..490b38ae 100644 --- a/lib/graphoid/definitions/filters.rb +++ b/lib/graphoid/definitions/filters.rb @@ -6,50 +6,62 @@ module Filters class << self def generate(model) - LIST[model] ||= GraphQL::InputObjectType.define do - name("#{Utils.graphqlize(model.name)}Filter") - description("Generated model filter for #{model.name}") + unless LIST[model] + model_type_const = "Graphoid::Types::#{Utils.graphqlize(model.name)}Filter" + LIST[model] ||= Graphoid::Types.const_get(model_type_const) - Attribute.fields_of(model).each do |field| - type = Graphoid::Mapper.convert(field) - name = Utils.camelize(field.name) + LIST[model].class_eval do + graphql_name("#{Utils.graphqlize(model.name)}Filter") + description("Generated model filter for #{model.name}") - argument name, type + m = self + argument(:OR, -> { [m] }, required: false) + argument(:AND, -> { [m] }, required: false) - m = LIST[model] - argument(:OR, -> { types[m] }) - argument(:AND, -> { types[m] }) + Attribute.fields_of(model).each do |field| + type = Graphoid::Mapper.convert(field) + name = Utils.camelize(field.name) - operators = %w[lt lte gt gte contains not] - operators.push('regex') if Graphoid.configuration.driver == :mongoid + argument name, type, required: false, camelize: false - operators.each do |suffix| - argument "#{name}_#{suffix}", type - end + # m = LIST[model] + # argument(:OR, m, required: false) + # argument(:OR, -> { m }, required: false) + + operators = %w[lt lte gt gte contains not] + operators.push('regex') if Graphoid.configuration.driver == :mongoid + + operators.each do |suffix| + argument "#{name}_#{suffix}", type, required: false, camelize: false + end - %w[in nin].each do |suffix| - argument "#{name}_#{suffix}", types[type] + %w[in nin].each do |suffix| + argument "#{name}_#{suffix}", [type], required: false, camelize: false + end end - end - Relation.relations_of(model).each do |name, relation| - relation_class = relation.class_name.safe_constantize - next unless relation_class + Relation.relations_of(model).each do |name, relation| + relation_class = relation.class_name.safe_constantize + relation_name = Utils.graphqlize(relation_class.name) + + next unless relation_class - relation_filter = LIST[relation_class] - next unless relation_filter + relation_filter = LIST[relation_class] + relation_filter = "Graphoid::Types::#{relation_name}Filter" unless relation_filter - relation_name = Utils.camelize(name) + relation_name = Utils.camelize(name) - if Relation.new(relation).many? - %w[some none every].each do |suffix| - argument "#{relation_name}_#{suffix}", relation_filter + if Relation.new(relation).many? + %w[some none every].each do |suffix| + argument "#{relation_name}_#{suffix}", relation_filter, required: false, camelize: false + end + else + argument relation_name.to_s, relation_filter, required: false, camelize: false end - else - argument relation_name.to_s, relation_filter end end end + LIST[model] end end end diff --git a/lib/graphoid/definitions/inputs.rb b/lib/graphoid/definitions/inputs.rb index 764a174d..8a378941 100644 --- a/lib/graphoid/definitions/inputs.rb +++ b/lib/graphoid/definitions/inputs.rb @@ -6,9 +6,9 @@ module Inputs class << self def generate(model) - LIST[model] ||= GraphQL::InputObjectType.define do + LIST[model] ||= Class.new(GraphQL::Schema::InputObject) do name = Utils.graphqlize(model.name) - name("#{name}Input") + graphql_name("#{name}Input") description("Generated model input for #{name}") Attribute.fields_of(model).each do |field| @@ -17,7 +17,7 @@ def generate(model) type = Graphoid::Mapper.convert(field) name = Utils.camelize(field.name) - argument(name, type) + argument(name, type, required: false) end Relation.relations_of(model).each do |name, relation| @@ -31,9 +31,9 @@ def generate(model) r = Relation.new(relation) if r.many? - argument(name, -> { types[relation_input] }) + argument(name, -> { [relation_input] }, required: false) else - argument(name, -> { relation_input }) + argument(name, -> { relation_input }, required: false) end end end diff --git a/lib/graphoid/definitions/sorter.rb b/lib/graphoid/definitions/sorter.rb index 7d7abb40..7a02fe50 100644 --- a/lib/graphoid/definitions/sorter.rb +++ b/lib/graphoid/definitions/sorter.rb @@ -8,33 +8,40 @@ module Sorter class << self def generate(model) - LIST[model] ||= GraphQL::InputObjectType.define do - name("#{Utils.graphqlize(model.name)}Sorter") - description("Generated model Sorter for #{model.name}") - - Attribute.fields_of(model).each do |field| - name = Utils.camelize(field.name) - next argument(name, Sorter.dynamic_type) if field.try(:dynamic?) - argument(name, Sorter.enum_type) - end + unless LIST[model] + model_type_const = "Graphoid::Types::#{Utils.graphqlize(model.name)}Sorter" + LIST[model] ||= Graphoid::Types.const_get(model_type_const) + + LIST[model].class_eval do + graphql_name("#{Utils.graphqlize(model.name)}Sorter") + description("Generated model Sorter for #{model.name}") - Relation.relations_of(model).each do |name, relation| - relation_class = relation.class_name.safe_constantize - next unless relation_class + Attribute.fields_of(model).each do |field| + name = Utils.camelize(field.name) + next argument(name, Sorter.dynamic_type, required: false) if field.try(:dynamic?) + argument(name, Sorter.enum_type, required: false) + end - relation_order = LIST[relation_class] - next unless relation_order + #Relation.relations_of(model).each do |name, relation| + # relation_class = relation.class_name.safe_constantize + # next unless relation_class - relation_name = Utils.camelize(name) + # relation_order = LIST[relation_class] + # next unless relation_order - argument(relation_name, relation_order) + # relation_name = Utils.camelize(name) + + # argument(relation_name, relation_order) + #end end end + + LIST[model] end def enum_type - @@enum_type ||= GraphQL::EnumType.define do - name 'SorterType' + @@enum_type ||= Class.new(GraphQL::Schema::Enum) do + graphql_name 'SorterType' value 'ASC', 'Ascendent' value 'DESC', 'Descendent' diff --git a/lib/graphoid/definitions/types.rb b/lib/graphoid/definitions/types.rb index 82d71acf..76cb7894 100644 --- a/lib/graphoid/definitions/types.rb +++ b/lib/graphoid/definitions/types.rb @@ -1,125 +1,137 @@ # frozen_string_literal: true module Graphoid + module Resolvers + def self.resolver_class(relation_class, relation_type, association) + association_name = association.name + relation_name = Utils.graphqlize(relation_class.name) + + Class.new(GraphQL::Schema::Resolver) do + type [relation_type], null: true + + self.const_set(:ASSOCIATION_NAME, association_name) + + filter = Graphoid::Filters::LIST[relation_class] + filter = "Graphoid::Types::#{relation_name}Filter" unless filter + order = Graphoid::Sorter::LIST[relation_class] + order = "Graphoid::Types::#{relation_name}Sorter" unless order + + argument :where, filter, required: false + argument :order, order, required: false + argument :limit, GraphQL::Types::Int, required: false + argument :skip, GraphQL::Types::Int, required: false + + def resolve(where: nil, order: nil, limit: nil, skip: nil) + obj = self.object + processor = Graphoid::Queries::Processor + + association_name = self.class.const_get(:ASSOCIATION_NAME) + result = obj.send(association_name) + result = processor.execute(result, where) if where.present? + + if order.present? + order = processor.parse_order(obj.send(association_name), order) + result = result.order(order) + end + + result = result.limit(limit) if limit.present? + result = result.skip(skip) if skip.present? + + result + end + end + end + end + module Types LIST = {} ENUMS = {} class << self - def generate(model) - Graphoid::Types::Meta ||= GraphQL::ObjectType.define do - name('xMeta') - description('xMeta Type') - field('count', types.Int) + def initialize(*models) + models.each do |model| + type_const = "#{model.name}Type" + filter_const = "#{model.name}Filter" + sorter_const = "#{model.name}Sorter" + #input_const = "#{model.name}Input" + Graphoid::Types::const_set(type_const, Class.new(GraphQL::Schema::Object)) + Graphoid::Types::const_set(filter_const, Class.new(GraphQL::Schema::InputObject)) + Graphoid::Types::const_set(sorter_const, Class.new(GraphQL::Schema::InputObject)) + #Graphoid::Types::const_set(input_const, Class.new(GraphQL::Schema::InputObject)) end + end - LIST[model] ||= GraphQL::ObjectType.define do - name = Utils.graphqlize(model.name) - name("#{name}Type") - description("Generated model type for #{name}") - - Attribute.fields_of(model).each do |attribute| - type = Graphoid::Mapper.convert(attribute) - name = Utils.camelize(attribute.name) - field(name, type) - - model.class_eval do - if attribute.name.include?('_') - define_method :"#{Utils.camelize(attribute.name)}" do - method_name = attribute.name.to_s - self[method_name] || send(method_name) + def generate(model) + unless LIST[model] + model_type_const = "Graphoid::Types::#{Utils.graphqlize(model.name)}Type" + LIST[model] ||= Graphoid::Types.const_get(model_type_const) + + LIST[model].class_eval do + name = Utils.graphqlize(model.name) + graphql_name("#{name}Type") + description("Generated model type for #{name}") + + Attribute.fields_of(model).each do |attribute| + type = Graphoid::Mapper.convert(attribute) + name = Utils.camelize(attribute.name) + field(name, type) + + model.class_eval do + if attribute.name.include?('_') + define_method :"#{Utils.camelize(attribute.name)}" do + method_name = attribute.name.to_s + self[method_name] || send(method_name) + end end end end - end - Relation.relations_of(model).each do |_, relation| - relation_class = relation.class_name.safe_constantize + Relation.relations_of(model).each do |_, relation| + relation_class = relation.class_name.safe_constantize + relation_name = Utils.graphqlize(relation_class.name) - message = "in model #{model.name}: skipping relation #{relation.class_name}" - unless relation_class - warn "Graphoid: warning: #{message} because the model name is not valid" if ENV['DEBUG'] - next - end + message = "in model #{model.name}: skipping relation #{relation.class_name}" + unless relation_class + warn "Graphoid: warning: #{message} because the model name is not valid" if ENV['DEBUG'] + next + end - relation_type = LIST[relation_class] - unless relation_type - warn "Graphoid: warning: #{message} because it was not found as a model" if ENV['DEBUG'] - next - end + relation_type = LIST[relation_class] + unless relation_type + # using string type to avoid circular dependency + # https://github.com/rmosolgo/graphql-ruby/issues/2874#issuecomment-614104142 + relation_type = "Graphoid::Types::#{relation_name}Type" + end - name = Utils.camelize(relation.name) + name = Utils.camelize(relation.name) - model.class_eval do - if relation.name.to_s.include?('_') - define_method :"#{name}" do - send(relation.name) + model.class_eval do + if relation.name.to_s.include?('_') + define_method :"#{name}" do + send(relation.name) + end end end - end - next unless relation_type + next unless relation_type - filter = Graphoid::Filters::LIST[relation_class] - order = Graphoid::Sorter::LIST[relation_class] + filter = Graphoid::Filters::LIST[relation_class] + filter = "Graphoid::Types::#{relation_name}Filter" unless filter - if Relation.new(relation).many? - plural_name = name.pluralize + if Relation.new(relation).many? + plural_name = name.pluralize - field plural_name, types[relation_type] do - Graphoid::Argument.query_many(self, filter, order) - Graphoid::Types.resolve_many(self, relation_class, relation) - end - - field "x_meta_#{plural_name}", Graphoid::Types::Meta do - Graphoid::Argument.query_many(self, filter, order) - Graphoid::Types.resolve_many(self, relation_class, relation) - end - else - field name, relation_type do - argument :where, filter - Graphoid::Types.resolve_one(self, relation_class, relation) + resolver = Graphoid::Resolvers.resolver_class(relation_class, relation_type, relation) + field plural_name, resolver: resolver + else + # one-to-one relation + field name, relation_type end end end + LIST[model] end end - - def resolve_one(field, model, association) - field.resolve lambda { |obj, args, _ctx| - filter = args['where'].to_h - result = obj.send(association.name) - processor = Graphoid::Queries::Processor - if filter.present? && result - result = processor.execute(model.where(id: result.id), filter).first - end - result - } - end - - def resolve_many(field, _model, association) - field.resolve lambda { |obj, args, _ctx| - filter = args['where'].to_h - order = args['order'].to_h - limit = args['limit'] - skip = args['skip'] - - processor = Graphoid::Queries::Processor - - result = obj.send(association.name) - result = processor.execute(result, filter) if filter.present? - - if order.present? - order = processor.parse_order(obj.send(association.name), order) - result = result.order(order) - end - - result = result.limit(limit) if limit.present? - result = result.skip(skip) if skip.present? - - result - } - end end end end diff --git a/lib/graphoid/drivers/active_record.rb b/lib/graphoid/drivers/active_record.rb deleted file mode 100644 index e3473c75..00000000 --- a/lib/graphoid/drivers/active_record.rb +++ /dev/null @@ -1,205 +0,0 @@ -# frozen_string_literal: true - -module Graphoid - module ActiveRecordDriver - class << self - def through?(type) - type == ActiveRecord::Reflection::ThroughReflection - end - - def has_and_belongs_to_many?(type) - type == ActiveRecord::Reflection::HasAndBelongsToManyReflection - end - - def has_many?(type) - type == ActiveRecord::Reflection::HasManyReflection - end - - def belongs_to?(type) - type == ActiveRecord::Reflection::BelongsToReflection - end - - def has_one?(type) - type == ActiveRecord::Reflection::HasOneReflection - end - - def embeds_one?(_type) - false - end - - def embeds_many?(_type) - false - end - - def embedded_in?(_type) - false - end - - def types_map - { - binary: GraphQL::Types::Boolean, - boolean: GraphQL::Types::Boolean, - float: GraphQL::Types::Float, - integer: GraphQL::Types::Int, - string: GraphQL::Types::String, - - datetime: Graphoid::Scalars::DateTime, - date: Graphoid::Scalars::DateTime, - time: Graphoid::Scalars::DateTime, - timestamp: Graphoid::Scalars::DateTime, - text: Graphoid::Scalars::Text, - bigint: Graphoid::Scalars::BigInt, - decimal: Graphoid::Scalars::Decimal - } - end - - def class_of(relation) - { - ActiveRecord::Reflection::HasAndBelongsToManyReflection => ManyToMany, - ActiveRecord::Reflection::BelongsToReflection => BelongsTo, - ActiveRecord::Reflection::ThroughReflection => ManyToMany, - ActiveRecord::Reflection::HasManyReflection => HasMany, - ActiveRecord::Reflection::HasOneReflection => HasOne - }[relation.class] || Relation - end - - def inverse_name_of(relation) - relation.inverse_of&.class_name&.underscore - end - - def fields_of(model) - model.columns - end - - def relations_of(model) - model.reflections - end - - def skip(result, skip) - result.offset(skip) - end - - def relation_type(relation) - relation.class - end - - def generate_array(nodes) - include_array = [] - nodes.each do |node| - children = node.selections.select!{ |n| !n.selections.empty? } - - if children.empty? - include_array.push(node.name.to_sym) - else - include_array.push(node.name.to_sym => generate_array(children)) - end - end - - include_array - end - - def eager_load(selection, model) - nodes = selection.ast_node.selections.first.selections - nodes.select!{ |n| !n.selections.empty? } - include_array = generate_array(nodes) - include_array.empty? ? model : model.includes(*include_array) - end - - def execute_and(scope, parsed) - scope.where(parsed) - end - - def execute_or(scope, list) - list.map! do |object| - Graphoid::Queries::Processor.execute(scope, object) - end - list.reduce(:or) - end - - def parse(attribute, value, operator) - field = attribute.name - case operator - when 'not' - parsed = ["#{field} != ?", value] - parsed = ["#{field} not like ?", value.to_s] if attribute.type == :string - parsed = ["#{field} is not null"] if value.nil? - when 'contains', 'regex' - parsed = ["#{field} like ?", "%#{value}%"] - when 'gt', 'gte', 'lt', 'lte', 'not', 'in', 'nin' - operator = { gt: '>', gte: '>=', lt: '<', lte: '<=', in: 'in', nin: 'not in' }[operator.to_sym] - parsed = ["#{field} #{operator} (?)", value] - else - parsed = ["#{field} = ?", value] - end - parsed - end - - # TODO: fix this as it is unused - def relate_through(scope, relation, value) - # if relation.has_one_through? - # ids = Graphoid::Queries::Processor.execute(relation.klass, value).to_a.map(&:id) - # through = relation.source.options[:through].to_s.camelize.constantize - # ids = through.where(id: ids) - # ids = Graphoid::Queries::Processor.execute(relation.klass, value).to_a.map(&:id) - # parsed = *["#{field.underscore}_id in (?)", ids] - # end - end - - def relate_many(scope, relation, value, operator) - parsed = {} - field_name = relation.inverse_name || scope.name.underscore - target = Graphoid::Queries::Processor.execute(relation.klass, value).to_a - - if relation.many_to_many? - field_name = field_name.to_s.singularize + '_ids' - ids = target.map(&field_name.to_sym) - ids.flatten!.uniq! - else - field_name = :"#{field_name}_id" - ids = target.map(&field_name) - end - - if operator == 'none' - parsed = ['id not in (?)', ids] if ids.present? - elsif operator == 'some' - parsed = ['id in (?)', ids] - elsif operator == 'every' - - # the following process is a SQL division - # the amount of queries it executes is on per row - # it is the same than doing an iteration process - # that iteration process would work in mongoid too - - # TODO: check and fix this query for many to many relations - - plural_name = relation.name.pluralize - conditions = value.map do |_key, _value| - operation = Operation.new(relation.klass, _key, _value) - parsed = parse(operation.operand, operation.value, operation.operator) - val = parsed.last.is_a?(String) ? "'#{parsed.last}'" : parsed.last - parsed = parsed.first.sub('?', val) - " AND #{parsed}" - end.join - - query = " - SELECT count(id) as total, #{field_name} - FROM #{plural_name} A - GROUP BY #{field_name} - HAVING total = ( - SELECT count(id) - FROM #{plural_name} B - WHERE B.#{field_name} = A.#{field_name} - #{conditions} - ) - " - result = ActiveRecord::Base.connection.execute(query) - ids = result.map { |row| row[field_name.to_s] } - - parsed = ['id in (?)', ids] - end - - parsed - end - end - end -end diff --git a/lib/graphoid/drivers/mongoid.rb b/lib/graphoid/drivers/mongoid_driver.rb similarity index 83% rename from lib/graphoid/drivers/mongoid.rb rename to lib/graphoid/drivers/mongoid_driver.rb index abb3ca75..9380f8f9 100644 --- a/lib/graphoid/drivers/mongoid.rb +++ b/lib/graphoid/drivers/mongoid_driver.rb @@ -115,40 +115,41 @@ def relation_type(relation) relation.relation end - def eager_load(selection, model, first = true) - referenced_relations = [ - mongo_constants[:many_to_many], - mongo_constants[:has_many], - mongo_constants[:has_one], - mongo_constants[:belongs_to] - ] - - properties = first ? Utils.first_children_of(selection) : Utils.children_of(selection) - inclusions = Utils.symbolize(properties) - - Relation.relations_of(model).each do |name, relation| - name = relation.name - next if inclusions.exclude?(name) || referenced_relations.exclude?(relation.relation) - - subselection = properties[name.to_s.camelize(:lower)] - subproperties = Utils.children_of(subselection) - subchildren = Utils.symbolize(subproperties) - subrelations = relation.class_name.constantize.relations.values.map(&:name) - - if (subrelations & subchildren).empty? - model = model.includes(name) - else - begin - gem "mongoid_includes" - model = model.includes(name, with: ->(instance) { eager_load(subselection, instance, false) }) - rescue Gem::LoadError - model = model.includes(name) - end - end - end - - model - end + # irep_node is deprecated + #def eager_load(selection, model, first = true) + # referenced_relations = [ + # mongo_constants[:many_to_many], + # mongo_constants[:has_many], + # mongo_constants[:has_one], + # mongo_constants[:belongs_to] + # ] + + # properties = first ? Utils.first_children_of(selection) : Utils.children_of(selection) + # inclusions = Utils.symbolize(properties) + + # Relation.relations_of(model).each do |name, relation| + # name = relation.name + # next if inclusions.exclude?(name) || referenced_relations.exclude?(relation.relation) + + # subselection = properties[name.to_s.camelize(:lower)] + # subproperties = Utils.children_of(subselection) + # subchildren = Utils.symbolize(subproperties) + # subrelations = relation.class_name.constantize.relations.values.map(&:name) + + # if (subrelations & subchildren).empty? + # model = model.includes(name) + # else + # begin + # gem "mongoid_includes" + # model = model.includes(name, with: ->(instance) { eager_load(subselection, instance, false) }) + # rescue Gem::LoadError + # model = model.includes(name) + # end + # end + # end + + # model + #end def execute_and(scope, parsed) scope.and(parsed) diff --git a/lib/graphoid/graphield.rb b/lib/graphoid/graphield.rb index 2c278178..2997ccad 100644 --- a/lib/graphoid/graphield.rb +++ b/lib/graphoid/graphield.rb @@ -1,5 +1,6 @@ # frozen_string_literal: true + module Graphoid module Graphield extend ActiveSupport::Concern diff --git a/lib/graphoid/grapho.rb b/lib/graphoid/grapho.rb index e4d84f66..ab82376b 100644 --- a/lib/graphoid/grapho.rb +++ b/lib/graphoid/grapho.rb @@ -1,5 +1,6 @@ # frozen_string_literal: true + module Graphoid class Grapho attr_reader :name, :plural, :camel_name diff --git a/lib/graphoid.rb b/lib/graphoid/graphoid.rb similarity index 91% rename from lib/graphoid.rb rename to lib/graphoid/graphoid.rb index 4c8b55f4..e516a692 100644 --- a/lib/graphoid.rb +++ b/lib/graphoid/graphoid.rb @@ -27,12 +27,9 @@ require 'graphoid/mutations/processor' require 'graphoid/mutations/structure' -require 'graphoid/drivers/mongoid' -require 'graphoid/drivers/active_record' +require 'graphoid/drivers/mongoid_driver' require 'graphoid/definitions/types' require 'graphoid/definitions/sorter' require 'graphoid/definitions/filters' require 'graphoid/definitions/inputs' - -require 'graphoid/main' diff --git a/lib/graphoid/main.rb b/lib/graphoid/main.rb deleted file mode 100644 index 8348e06e..00000000 --- a/lib/graphoid/main.rb +++ /dev/null @@ -1,23 +0,0 @@ -# frozen_string_literal: true - -module Graphoid - @graphs = {} - - class << self - attr_reader :driver - - def initialize - Graphoid.driver = configuration&.driver - Rails.application.eager_load! - Graphoid::Scalars.generate - end - - def build(model, _action = nil) - @graphs[model] ||= Graphoid::Grapho.new(model) - end - - def driver=(driver) - @driver = driver == :active_record ? ActiveRecordDriver : MongoidDriver - end - end -end diff --git a/lib/graphoid/mapper.rb b/lib/graphoid/mapper.rb index 6eb483dc..29083088 100644 --- a/lib/graphoid/mapper.rb +++ b/lib/graphoid/mapper.rb @@ -11,3 +11,4 @@ def convert(field) end end end + diff --git a/lib/graphoid/mutations/create.rb b/lib/graphoid/mutations/create.rb index bb762683..1f967898 100644 --- a/lib/graphoid/mutations/create.rb +++ b/lib/graphoid/mutations/create.rb @@ -3,11 +3,8 @@ module Graphoid module Mutations module Create - extend ActiveSupport::Concern - - included do + def self.build(model) Graphoid.initialize - model = self grapho = Graphoid.build(model) type = ::Types::MutationType @@ -18,10 +15,6 @@ module Create argument(:data, grapho.input, required: false) end - type.field(name: plural_name, type: [grapho.type], null: true) do - argument(:data, [grapho.input], required: false) - end - type.class_eval do define_method :"#{name}" do |data: {}| begin @@ -32,19 +25,6 @@ module Create end end end - - type.class_eval do - define_method :"#{plural_name}" do |data: []| - begin - user = context[:current_user] - result = [] - data.each { |d| result << Graphoid::Mutations::Processor.execute(model, grapho, d, user) } - result - rescue Exception => ex - GraphQL::ExecutionError.new(ex.message) - end - end - end end end end diff --git a/lib/graphoid/mutations/delete.rb b/lib/graphoid/mutations/delete.rb index 643c773c..626fea80 100644 --- a/lib/graphoid/mutations/delete.rb +++ b/lib/graphoid/mutations/delete.rb @@ -5,9 +5,8 @@ module Mutations module Delete extend ActiveSupport::Concern - included do + def self.build(model) Graphoid.initialize - model = self grapho = Graphoid.build(model) type = ::Types::MutationType @@ -18,10 +17,6 @@ module Delete argument :id, GraphQL::Types::ID, required: true end - type.field(name: plural, type: [grapho.type], null: true) do - argument :where, grapho.filter, required: false - end - type.class_eval do define_method :"#{name}" do |id:| begin @@ -33,18 +28,6 @@ module Delete end end end - - type.class_eval do - define_method :"#{plural}" do |where: {}| - begin - objects = Graphoid::Queries::Processor.execute(model, where.to_h) - objects.destroy_all - objects.all.to_a - rescue Exception => ex - GraphQL::ExecutionError.new(ex.message) - end - end - end end end end diff --git a/lib/graphoid/mutations/processor.rb b/lib/graphoid/mutations/processor.rb index 20579322..2fbade86 100644 --- a/lib/graphoid/mutations/processor.rb +++ b/lib/graphoid/mutations/processor.rb @@ -6,7 +6,7 @@ module Processor def self.execute(model, grapho, data, user) root_object = [] operations = [] - data.each { |key, value| operations << Operation.new(model, key, value) } + data.each { |key, value| operations << Operation.new(model, key, value, camelize: true) } operations.each do |operation| item = operation.operand.precreate(operation.value) diff --git a/lib/graphoid/mutations/structure.rb b/lib/graphoid/mutations/structure.rb index ccc3af41..561cdf94 100644 --- a/lib/graphoid/mutations/structure.rb +++ b/lib/graphoid/mutations/structure.rb @@ -2,10 +2,14 @@ module Graphoid module Mutations - extend ActiveSupport::Concern + def self.generate(*models) + models.each { |model| Graphoid::Mutations.build(model) } + end - include Graphoid::Mutations::Create - include Graphoid::Mutations::Update - include Graphoid::Mutations::Delete + def self.build(model) + Graphoid::Mutations::Create.build(model) + Graphoid::Mutations::Update.build(model) + Graphoid::Mutations::Delete.build(model) + end end end diff --git a/lib/graphoid/mutations/update.rb b/lib/graphoid/mutations/update.rb index 02416b4c..cc654fdc 100644 --- a/lib/graphoid/mutations/update.rb +++ b/lib/graphoid/mutations/update.rb @@ -5,9 +5,8 @@ module Mutations module Update extend ActiveSupport::Concern - included do + def self.build(model) Graphoid.initialize - model = self grapho = Graphoid.build(model) type = ::Types::MutationType @@ -19,11 +18,6 @@ module Update argument :data, grapho.input, required: false end - type.field name: plural, type: [grapho.type], null: true do - argument :where, grapho.filter, required: false - argument :data, grapho.input, required: false - end - type.class_eval do define_method :"#{name}" do |id:, data: {}| attrs = Utils.build_update_attributes(data, model, context) @@ -37,20 +31,6 @@ module Update end end end - - type.class_eval do - define_method :"#{plural}" do |where: {}, data: {}| - attrs = Utils.build_update_attributes(data, model, context) - - begin - objects = Graphoid::Queries::Processor.execute(model, where.to_h) - objects.update_all(attrs) - objects.all.to_a - rescue Exception => ex - GraphQL::ExecutionError.new(ex.message) - end - end - end end end end diff --git a/lib/graphoid/operators/attribute.rb b/lib/graphoid/operators/attribute.rb index cf04f85a..d8f92396 100644 --- a/lib/graphoid/operators/attribute.rb +++ b/lib/graphoid/operators/attribute.rb @@ -11,8 +11,8 @@ def initialize(name:, type:, opts: {}) @camel_name = Utils.camelize(@name) @type = type @opts = opts - end - + end + def dynamic? @opts[:dynamic] == true end @@ -60,6 +60,7 @@ def correct(model, attributes) result = {} fieldnames = fieldnames_of(model) attributes.each do |key, value| + key = key.to_s.camelize(:lower) if fieldnames.exclude?(key) key = key.to_s.underscore if fieldnames.exclude?(key.to_s) result[key] = value end diff --git a/lib/graphoid/queries/operation.rb b/lib/graphoid/queries/operation.rb index 5a1236e7..1b58e663 100644 --- a/lib/graphoid/queries/operation.rb +++ b/lib/graphoid/queries/operation.rb @@ -4,13 +4,18 @@ module Graphoid class Operation attr_reader :scope, :operand, :operator, :value - def initialize(scope, key, value) + OPERATORS_REGEX = /^(.+)_(lt|lte|gt|gte|contains|not|in|nin|regex|some|none|every)$/.freeze + + def initialize(scope, key, value, camelize: false) + # camelize it because graphql 2.0 is passing keys as symbols using underscore format + # but for queries we need the underscore format to identify operators such as contains, regex + key = key.to_s.camelcase(:lower) if camelize @scope = scope @operator = nil @operand = key @value = value - match = key.match(/^(.+)_(.+)$/) + match = key.match(OPERATORS_REGEX) @operand, @operator = match[1..2] if match @operand = build_operand(@scope, @operand) || @operand end @@ -22,6 +27,8 @@ def resolve private def build_operand(model, key) + key = key.to_s if key.is_a? Symbol + key = '_id' if key == 'id' fields = Attribute.fields_of(model) field = fields.find { |f| f.name == key } @@ -30,6 +37,9 @@ def build_operand(model, key) field = fields.find { |f| f.name == key.underscore } return Attribute.new(name: key.underscore, type: field.type) if field + field = fields.find { |f| f.name == key.camelize(:lower) } + return Attribute.new(name: key.camelize(:lower), type: field.type) if field + relations = model.reflect_on_all_associations relation = relations.find { |r| r.name == key.to_sym } @@ -40,3 +50,4 @@ def build_operand(model, key) end end end + diff --git a/lib/graphoid/queries/processor.rb b/lib/graphoid/queries/processor.rb index 8e8eb581..3ac9ffc7 100644 --- a/lib/graphoid/queries/processor.rb +++ b/lib/graphoid/queries/processor.rb @@ -5,7 +5,10 @@ module Queries module Processor class << self def execute(scope, object) - object.each { |key, value| scope = process(scope, value, key) } + object.each do |key, value| + key = key.to_s if key.is_a? Symbol + scope = process(scope, value, key) + end scope end @@ -41,3 +44,4 @@ def parse_order(scope, order) end end end + diff --git a/lib/graphoid/queries/queries.rb b/lib/graphoid/queries/queries.rb index 155073ea..c1e0d46c 100644 --- a/lib/graphoid/queries/queries.rb +++ b/lib/graphoid/queries/queries.rb @@ -2,11 +2,12 @@ module Graphoid module Queries - extend ActiveSupport::Concern + def self.generate(*models) + models.each { |model| Graphoid::Queries.build(model) } + end - included do + def self.build(model) Graphoid.initialize - model = self grapho = Graphoid.build(model) query_type = ::Types::QueryType @@ -19,11 +20,13 @@ module Queries Graphoid::Argument.query_many(self, grapho.filter, grapho.order, required: false) end - query_type.field name: "x_meta_#{grapho.plural}", type: Graphoid::Types::Meta, null: true do - Graphoid::Argument.query_many(self, grapho.filter, grapho.order, required: false) - end - query_type.class_eval do + # Dynamically defining a resolver method for queries: + # query { + # project(id: "5e7b5b9b0b0b0b0b0b0b0b0b", where: { name_regex: "[a-z]" }) { + # id + # name + # } define_method :"#{grapho.name}" do |id: nil, where: nil| begin return model.find(id) if id @@ -35,9 +38,19 @@ module Queries end query_type.class_eval do + # Dynamically defining a resolver method for queries: + # query { + # projects(where: { name_contains: "a" }, order: { name: ASC }, limit: 10, skip: 10) { + # id + # name + # } define_method :"#{grapho.plural}" do |where: nil, order: nil, limit: nil, skip: nil| begin - model = Graphoid.driver.eager_load(context.irep_node, model) + # irep_node is deprecated + # maybe use context.ast_node instead + # but the problem is that it is not the same + # model = Graphoid.driver.eager_load(context.irep_node, model) + # https://graphql-ruby.org/fields/introduction.html#extra-field-metadata result = Processor.execute(model, where.to_h) order = Processor.parse_order(model, order.to_h) result = result.order(order).limit(limit) @@ -46,9 +59,8 @@ module Queries GraphQL::ExecutionError.new(ex.message) end end - - alias_method :"x_meta_#{grapho.plural}", :"#{grapho.plural}" end end end end + diff --git a/lib/graphoid/scalars.rb b/lib/graphoid/scalars.rb index e50c1bd4..9b5a6d2a 100644 --- a/lib/graphoid/scalars.rb +++ b/lib/graphoid/scalars.rb @@ -1,96 +1,103 @@ # frozen_string_literal: true module Graphoid - module Upload - end - module Scalars class << self def generate - Graphoid::Scalars::DateTime ||= GraphQL::ScalarType.define do - name 'DateTime' + Graphoid::Scalars::DateTime ||= Class.new(GraphQL::Schema::Scalar) do + graphql_name 'DateTime' description 'DateTime ISO8601 formated' - coerce_input lambda { |value, _| + def self.coerce_input(value, _ctx) begin ::DateTime.iso8601(value) rescue Exception => ex GraphQL::ExecutionError.new(ex) end - } + end end - Graphoid::Scalars::Date ||= GraphQL::ScalarType.define do - name 'Date' + Graphoid::Scalars::Date ||= Class.new(GraphQL::Schema::Scalar) do + graphql_name 'Date' description 'Date ISO8601 formated' - coerce_input lambda { |value, _| + def self.coerce_input(value, _ctx) begin ::DateTime.iso8601(value) rescue Exception => ex GraphQL::ExecutionError.new(ex) end - } + end end - Graphoid::Scalars::Time ||= GraphQL::ScalarType.define do - name 'Time' + Graphoid::Scalars::Time ||= Class.new(GraphQL::Schema::Scalar) do + graphql_name 'Time' description 'Time ISO8601 formated' - coerce_input lambda { |value, _| + def self.coerce_input(value, _ctx) begin ::DateTime.iso8601(value) rescue Exception => ex GraphQL::ExecutionError.new(ex) end - } + end end - Graphoid::Scalars::Timestamp ||= GraphQL::ScalarType.define do - name 'Timestamp' + Graphoid::Scalars::Timestamp ||= Class.new(GraphQL::Schema::Scalar) do + graphql_name 'Timestamp' description 'Second elapsed since 1970-01-01' - coerce_input lambda { |value, _| + def self.coerce_input(value, _ctx) begin ::DateTime.iso8601(value) rescue Exception => ex GraphQL::ExecutionError.new(ex) end - } + end end - Graphoid::Scalars::Text ||= GraphQL::ScalarType.define do - name 'Text' - description 'Should be string? explain this please.' + Graphoid::Scalars::Text ||= Class.new(GraphQL::Schema::Scalar) do + graphql_name 'Text' + description 'Text scalar' end - Graphoid::Scalars::BigInt ||= GraphQL::ScalarType.define do - name 'BigInt' - description 'WTF ??' + Graphoid::Scalars::BigInt ||= Class.new(GraphQL::Schema::Scalar) do + graphql_name 'BigInt' + description 'BigInt scalar' + + def self.coerce_input(value, _ctx) + begin + value.to_i + rescue Exception => ex + GraphQL::ExecutionError.new(ex) + end + end end - Graphoid::Scalars::Decimal ||= GraphQL::ScalarType.define do - name 'Decimal' - description 'Define pliiiizzzzzzz' + Graphoid::Scalars::Decimal ||= Class.new(GraphQL::Schema::Scalar) do + graphql_name 'Decimal' + description 'Decimal scalar' end - Graphoid::Scalars::Hash ||= GraphQL::ScalarType.define do - name 'Hash' + Graphoid::Scalars::Hash ||= Class.new(GraphQL::Schema::Scalar) do + graphql_name 'Hash' description 'Hash scalar' - def self.coerce_input(input_value, _context) + def self.coerce_input(input_value, _ctx) input_value.to_h rescue StandardError raise GraphQL::CoercionError, "#{input_value.inspect} is not a valid Hash" end - def self.coerce_result(ruby_value, _context) + def self.coerce_result(ruby_value, _ctx) ruby_value.to_h + rescue StandardError + raise GraphQL::CoercionError, "#{ruby_value.inspect} is not a valid Hash" end end - Graphoid::Scalars::Array ||= GraphQL::ScalarType.define do - name 'Array' + Graphoid::Scalars::Array ||= Class.new(GraphQL::Schema::Scalar) do + graphql_name 'Array' description 'Array scalar' end end diff --git a/spec/tester_mongo/db/test.sqlite3 b/lib/graphoid/tasks/.keep similarity index 100% rename from spec/tester_mongo/db/test.sqlite3 rename to lib/graphoid/tasks/.keep diff --git a/lib/graphoid/utils.rb b/lib/graphoid/utils.rb index 2379c70e..354b42b2 100644 --- a/lib/graphoid/utils.rb +++ b/lib/graphoid/utils.rb @@ -23,7 +23,7 @@ def symbolize(fields) def children_of(selection) selection.scoped_children.values.first end - + def first_children_of(selection) selection.scoped_children.values.first.values.first.scoped_children.values.first end @@ -31,6 +31,8 @@ def first_children_of(selection) def underscore(props, fields = []) attrs = {} props.each do |key, value| + key = key.to_s if key.is_a? Symbol + key = key.camelize(:lower) if fields.exclude?(key) key = key.underscore if fields.exclude?(key) attrs[key] = value end diff --git a/package-lock.json b/package-lock.json deleted file mode 100644 index 48e341a0..00000000 --- a/package-lock.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "lockfileVersion": 1 -} diff --git a/spec/graphoid/mutations/create_many_spec.rb b/spec/graphoid/mutations/create_many_spec.rb deleted file mode 100644 index c2e7a339..00000000 --- a/spec/graphoid/mutations/create_many_spec.rb +++ /dev/null @@ -1,24 +0,0 @@ -# frozen_string_literal: true - -require 'rails_helper' - -describe 'MutationCreateMany', type: :request do - before { Account.delete_all } - subject { Helper.resolve(self, 'createAccounts', @query) } - - it 'creates many objects' do - @query = %{ - mutation { - createAccounts(data: [ - { camelCase: "camel0", snakeCase: "snake0", stringField: "account0" }, - { camelCase: "camel1", snakeCase: "snake1", stringField: "account1" }, - ]){ - id - } - } - } - - expect(Account.find(subject[0]['id'])).to be - expect(Account.find(subject[1]['id'])).to be - end -end diff --git a/spec/graphoid/mutations/delete_many_spec.rb b/spec/graphoid/mutations/delete_many_spec.rb deleted file mode 100644 index c49a92ef..00000000 --- a/spec/graphoid/mutations/delete_many_spec.rb +++ /dev/null @@ -1,29 +0,0 @@ -# frozen_string_literal: true - -require 'rails_helper' - -describe 'MutationDeleteMany', type: :request do - before { Account.delete_all } - subject { Helper.resolve(self, @action, @query) } - - let!(:a0) { Account.create!(string_field: 'bob') } - let!(:a1) { Account.create!(string_field: 'bob') } - let!(:a2) { Account.create!(string_field: 'oob') } - - it 'deletes many objects by condition' do - @action = 'deleteManyAccounts' - - @query = %{ - mutation { - deleteManyAccounts(where: { stringField: "bob" }){ - id - } - } - } - - expect(Account.count).to eq(3) - subject - expect(Account.count).to eq(1) - expect(Account.first.string_field).to eq('oob') - end -end diff --git a/spec/graphoid/mutations/update_many_spec.rb b/spec/graphoid/mutations/update_many_spec.rb deleted file mode 100644 index f6c3db96..00000000 --- a/spec/graphoid/mutations/update_many_spec.rb +++ /dev/null @@ -1,27 +0,0 @@ -# frozen_string_literal: true - -require 'rails_helper' - -describe 'MutationUpdateMany', type: :request do - before { Account.delete_all } - subject { Helper.resolve(self, 'updateManyAccounts', @query) } - - let!(:a0) { Account.create!(string_field: 'account0', snake_case: 'snake', camelCase: 'camel') } - let!(:a1) { Account.create!(string_field: 'account1', snake_case: 'snake', camelCase: 'camel') } - let!(:a2) { Account.create!(string_field: 'account2', snake_case: 'snaki', camelCase: 'camel') } - - it 'updates many objects by condition' do - @query = %{ - mutation M { - updateManyAccounts(where: { snakeCase: "snake" }, data: { camelCase: "updated" }){ - id - camelCase - } - } - } - - expect(subject[0]['camelCase']).to eq('updated') - expect(subject[1]['camelCase']).to eq('updated') - expect(a2.reload.camelCase).to eq('camel') - end -end diff --git a/spec/graphoid/queries/aggregations/count_spec.rb b/spec/graphoid/queries/aggregations/count_spec.rb deleted file mode 100644 index cfeaab7a..00000000 --- a/spec/graphoid/queries/aggregations/count_spec.rb +++ /dev/null @@ -1,42 +0,0 @@ -# frozen_string_literal: true - -require 'rails_helper' - -describe 'QueryAndCount', type: :request do - let!(:delete) { Account.delete_all } - subject { Helper.resolve(self, 'xMetaAccounts', @query)['count'] } - - let!(:a0) { Account.create!(snake_case: 'snaki', camelCase: 'camol') } - let!(:a1) { Account.create!(snake_case: 'snaki', camelCase: 'camol') } - let!(:a2) { Account.create!(snake_case: 'snaki', camelCase: 'camol') } - let!(:a3) { Account.create!(snake_case: 'snake', camelCase: 'camel') } - let!(:a4) { Account.create!(snake_case: 'snake', camelCase: 'camel') } - - describe 'count on models' do - it 'with a string camelCased field' do - @query = %( - query { - xMetaAccounts { - count - } - } - ) - - expect(subject).to eq 5 - end - - it 'with a filter' do - @query = %{ - query { - xMetaAccounts(where: { - snakeCase_contains: "ki" - }) { - count - } - } - } - - expect(subject).to eq 3 - end - end -end diff --git a/spec/graphoid/queries/attributes/subfilter_spec.rb b/spec/graphoid/queries/attributes/subfilter_spec.rb deleted file mode 100644 index e9a5bee7..00000000 --- a/spec/graphoid/queries/attributes/subfilter_spec.rb +++ /dev/null @@ -1,110 +0,0 @@ -# frozen_string_literal: true - -# TODO: should apply submodel filtering on embeeded relations -# TODO: elaborate more complex cases - -require 'rails_helper' - -describe 'QuerySubFilter', type: :request do - subject { Helper.resolve(self, @action, @query) } - - before(:all) do - Person.delete_all - Label.delete_all - Account.delete_all - House.delete_all - - @h0 = House.create!(name: 'h0') - @a0 = Account.create!(integer_field: 2, house: @h0) - @p0 = Person.create!(account: @a0, name: 'p0', snake_case: 'snake', camelCase: 'camel') - @l0 = Label.create!(account: @a0, name: 'l0', amount: 2) - @l1 = Label.create!(account: @a0, name: 'l1', amount: 2) - end - - after(:all) do - [@h0, @a0, @p0, @l0, @l1].map(&:destroy) - end - - describe 'applies filters in related models' do - it 'when has many' do - @action = 'accounts' - @query = %{ - query { - accounts { - id - labels(where: { amount: 2, name: "l0" }) { - id - } - } - } - } - - expect(subject[0]['labels'].size).to eq(1) - expect(subject[0]['labels'][0]['id']).to eq @l0.id.to_s - end - - it 'when has one and does not match' do - @action = 'account' - @query = %{ - query { - account { - id - person(where: { name: "something" }) { - id - } - } - } - } - - expect(subject['person']).not_to be - end - - it 'when has one and matches' do - @action = 'account' - @query = %{ - query { - account { - id - person(where: { name: "p0" }) { - id - } - } - } - } - - expect(subject['person']['id']).to eq @p0.id.to_s - end - - it 'when belongs to and does not match' do - @action = 'account' - @query = %{ - query { - account { - id - house(where: { name: "something" }) { - id - } - } - } - } - - expect(subject['house']).not_to be - end - - it 'when belongs to and does and matches' do - @action = 'account' - @query = %{ - query { - account { - id - house(where: { name: "h0" }) { - id - } - } - } - } - - expect(subject['house']['id']).to eq @h0.id.to_s - end - end -end diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb index 8c185a1b..d330b97e 100644 --- a/spec/rails_helper.rb +++ b/spec/rails_helper.rb @@ -1,34 +1,65 @@ # frozen_string_literal: true -require 'simplecov' -SimpleCov.start 'rails' - +# This file is copied to spec/ when you run 'rails generate rspec:install' require 'spec_helper' -require 'pry-rails' - ENV['RAILS_ENV'] ||= 'test' +require_relative '../config/environment' +# Prevent database truncation if the environment is production +abort("The Rails environment is running in production mode!") if Rails.env.production? +require 'rspec/rails' +# Add additional requires below this line. Rails is not loaded until this point! -tests_folder = "tester_#{ENV['DRIVER'] || 'ar'}" - -require File.expand_path("../#{tests_folder}/config/environment", __FILE__) +# Requires supporting ruby files with custom matchers and macros, etc, in +# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are +# run as spec files by default. This means that files in spec/support that end +# in _spec.rb will both be required and run as specs, causing the specs to be +# run twice. It is recommended that you do not name files matching this glob to +# end with _spec.rb. You can configure this pattern with the --pattern +# option on the command line or in ~/.rspec, .rspec or `.rspec-local`. +# +# The following line is provided for convenience purposes. It has the downside +# of increasing the boot-up time by auto-requiring all files in the support +# directory. Alternatively, in the individual `*_spec.rb` files, manually +# require only the support files necessary. +# +# Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f } -# Prevent database truncation if the environment is production -abort('The Rails environment is running in production mode!') if Rails.env.production? +# Checks for pending migrations and applies them before tests are run. +# If you are not using ActiveRecord, you can remove these lines. +begin + ActiveRecord::Migration.maintain_test_schema! +rescue ActiveRecord::PendingMigrationError => e + abort e.to_s.strip +end +RSpec.configure do |config| + # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures + config.fixture_path = "#{::Rails.root}/spec/fixtures" -require 'rspec/rails' + # If you're not using ActiveRecord, or you'd prefer not to run each of your + # examples within a transaction, remove the following line or assign false + # instead of true. + config.use_transactional_fixtures = true -RSpec.configure(&:filter_rails_from_backtrace!) + # You can uncomment this line to turn off ActiveRecord support entirely. + # config.use_active_record = false -module Helper - def self.resolve(test, action, query) - test.post '/graphql', params: { query: query } - body = test.response.body - pp body if ENV['DEBUG'] - result = JSON.parse(body)['data'] - result && result[action] - end + # RSpec Rails can automatically mix in different behaviours to your tests + # based on their file location, for example enabling you to call `get` and + # `post` in specs under `spec/controllers`. + # + # You can disable this behaviour by removing the line below, and instead + # explicitly tag your specs with their type, e.g.: + # + # RSpec.describe UsersController, type: :controller do + # # ... + # end + # + # The different available types are documented in the features, such as in + # https://relishapp.com/rspec/rspec-rails/docs + config.infer_spec_type_from_file_location! - def self.ids_of(*objects) - objects.map(&:id).map(&:to_s) - end + # Filter lines from Rails gems in backtraces. + config.filter_rails_from_backtrace! + # arbitrary gems may also be filtered via: + # config.filter_gems_from_backtrace("gem name") end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 426504e3..43e5256d 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -14,7 +14,7 @@ # the additional setup, and require it from the spec files that actually need # it. # -# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration +# See https://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration RSpec.configure do |config| # rspec-expectations config goes here. You can use an alternate # assertion/expectation library such as wrong or the stdlib/minitest @@ -46,52 +46,51 @@ # triggering implicit auto-inclusion in groups with matching metadata. config.shared_context_metadata_behavior = :apply_to_host_groups - # The settings below are suggested to provide a good initial experience - # with RSpec, but feel free to customize to your heart's content. - # # This allows you to limit a spec run to individual examples or groups - # # you care about by tagging them with `:focus` metadata. When nothing - # # is tagged with `:focus`, all examples get run. RSpec also provides - # # aliases for `it`, `describe`, and `context` that include `:focus` - # # metadata: `fit`, `fdescribe` and `fcontext`, respectively. - # config.filter_run_when_matching :focus - # - # # Allows RSpec to persist some state between runs in order to support - # # the `--only-failures` and `--next-failure` CLI options. We recommend - # # you configure your source control system to ignore this file. - # config.example_status_persistence_file_path = "spec/examples.txt" - # - # # Limits the available syntax to the non-monkey patched syntax that is - # # recommended. For more details, see: - # # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ - # # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ - # # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode - # config.disable_monkey_patching! - # - # # Many RSpec users commonly either run the entire suite or an individual - # # file, and it's useful to allow more verbose output when running an - # # individual spec file. - # if config.files_to_run.one? - # # Use the documentation formatter for detailed output, - # # unless a formatter has already been configured - # # (e.g. via a command-line flag). - # config.default_formatter = "doc" - # end - # - # # Print the 10 slowest examples and example groups at the - # # end of the spec run, to help surface which specs are running - # # particularly slow. - # config.profile_examples = 10 - # - # # Run specs in random order to surface order dependencies. If you find an - # # order dependency and want to debug it, you can fix the order by providing - # # the seed, which is printed after each run. - # # --seed 1234 - # config.order = :random - # - # # Seed global randomization in this process using the `--seed` CLI option. - # # Setting this allows you to use `--seed` to deterministically reproduce - # # test failures related to randomization by passing the same `--seed` value - # # as the one that triggered the failure. - # Kernel.srand config.seed -end +# The settings below are suggested to provide a good initial experience +# with RSpec, but feel free to customize to your heart's content. +=begin + # This allows you to limit a spec run to individual examples or groups + # you care about by tagging them with `:focus` metadata. When nothing + # is tagged with `:focus`, all examples get run. RSpec also provides + # aliases for `it`, `describe`, and `context` that include `:focus` + # metadata: `fit`, `fdescribe` and `fcontext`, respectively. + config.filter_run_when_matching :focus + + # Allows RSpec to persist some state between runs in order to support + # the `--only-failures` and `--next-failure` CLI options. We recommend + # you configure your source control system to ignore this file. + config.example_status_persistence_file_path = "spec/examples.txt" + + # Limits the available syntax to the non-monkey patched syntax that is + # recommended. For more details, see: + # https://relishapp.com/rspec/rspec-core/docs/configuration/zero-monkey-patching-mode + config.disable_monkey_patching! + + # Many RSpec users commonly either run the entire suite or an individual + # file, and it's useful to allow more verbose output when running an + # individual spec file. + if config.files_to_run.one? + # Use the documentation formatter for detailed output, + # unless a formatter has already been configured + # (e.g. via a command-line flag). + config.default_formatter = "doc" + end + + # Print the 10 slowest examples and example groups at the + # end of the spec run, to help surface which specs are running + # particularly slow. + config.profile_examples = 10 + # Run specs in random order to surface order dependencies. If you find an + # order dependency and want to debug it, you can fix the order by providing + # the seed, which is printed after each run. + # --seed 1234 + config.order = :random + + # Seed global randomization in this process using the `--seed` CLI option. + # Setting this allows you to use `--seed` to deterministically reproduce + # test failures related to randomization by passing the same `--seed` value + # as the one that triggered the failure. + Kernel.srand config.seed +=end +end diff --git a/spec/tester_mongo/.gitignore b/spec/tester_mongo/.gitignore index 2afd9512..12439e58 100644 --- a/spec/tester_mongo/.gitignore +++ b/spec/tester_mongo/.gitignore @@ -1,3 +1,33 @@ -.byebug_history -tmp/ -log/ +# See https://help.github.com/articles/ignoring-files for more about ignoring files. +# +# If you find yourself ignoring temporary files generated by your text editor +# or operating system, you probably want to add a global ignore instead: +# git config --global core.excludesfile '~/.gitignore_global' + +# Ignore bundler config. +/.bundle + +# Ignore the default SQLite database. +/db/*.sqlite3 +/db/*.sqlite3-* + +# Ignore all logfiles and tempfiles. +/log/* +/tmp/* +!/log/.keep +!/tmp/.keep + +# Ignore pidfiles, but keep the directory. +/tmp/pids/* +!/tmp/pids/ +!/tmp/pids/.keep + +# Ignore uploaded files in development. +/storage/* +!/storage/.keep +/tmp/storage/* +!/tmp/storage/ +!/tmp/storage/.keep + +# Ignore master key for decrypting credentials and more. +/config/master.key diff --git a/spec/tester_mongo/.ruby-version b/spec/tester_mongo/.ruby-version new file mode 100644 index 00000000..9e79f6c4 --- /dev/null +++ b/spec/tester_mongo/.ruby-version @@ -0,0 +1 @@ +ruby-3.2.2 diff --git a/spec/tester_mongo/Gemfile b/spec/tester_mongo/Gemfile index c0d337f4..064424b4 100644 --- a/spec/tester_mongo/Gemfile +++ b/spec/tester_mongo/Gemfile @@ -1,21 +1,58 @@ -# frozen_string_literal: true +source "https://rubygems.org" +git_source(:github) { |repo| "https://github.com/#{repo}.git" } -source 'https://rubygems.org' +ruby ">= 2.7.0" -gem 'puma', '~> 3.7' -gem 'rails', '~> 6.0' +# Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main" +gem "rails", "~> 7.0.4", ">= 7.0.4.3" -gem 'mongoid', '~> 7.0' -gem 'mongoid-rspec' -gem 'mongoid_includes', '~> 3.0.2' +# Use sqlite3 as the database for Active Record +gem "sqlite3", "~> 1.4" -gem "nokogiri", "~> 1.13.9" +gem "mongoid" -group :development do - gem 'byebug' +# Use the Puma web server [https://github.com/puma/puma] +gem "puma", "~> 5.0" + +# Use graphql gem for handle API +gem 'graphql', "~> 2.0.21" + +gem 'graphoid', path: "../../", require: 'graphoid/graphoid' + +# Build JSON APIs with ease [https://github.com/rails/jbuilder] +# gem "jbuilder" + +# Use Redis adapter to run Action Cable in production +# gem "redis", "~> 4.0" + +# Use Kredis to get higher-level data types in Redis [https://github.com/rails/kredis] +# gem "kredis" + +# Use Active Model has_secure_password [https://guides.rubyonrails.org/active_model_basics.html#securepassword] +gem "bcrypt", "~> 3.1.18" + +# Windows does not include zoneinfo files, so bundle the tzinfo-data gem +gem "tzinfo-data", platforms: %i[ mingw mswin x64_mingw jruby ] + +# Reduces boot times through caching; required in config/boot.rb +gem "bootsnap", require: false + +# Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images] +# gem "image_processing", "~> 1.2" + +# Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible +# gem "rack-cors" + +group :development, :test do + # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem + gem "debug", platforms: %i[ mri mingw x64_mingw ] + gem "graphiql-rails" + gem "pry-byebug" + gem "rspec-rails" end -gem 'graphiql-rails', '~> 1.7.0', group: :development -gem 'graphql', '~> 1.8.18' +group :development do + # Speed up commands on slow machines / big apps [https://github.com/rails/spring] + # gem "spring" +end -gem 'graphoid', path: '../../' diff --git a/spec/tester_mongo/Gemfile.lock b/spec/tester_mongo/Gemfile.lock index efc908d1..70bdffe6 100644 --- a/spec/tester_mongo/Gemfile.lock +++ b/spec/tester_mongo/Gemfile.lock @@ -1,89 +1,104 @@ PATH remote: ../.. specs: - graphoid (0.1.0) - graphql (~> 1.8.0) - nokogiri (~> 1.13.9) - rails (~> 6) + graphoid (1.0.0) + graphql (~> 2.0.21) + rails (>= 6.0) GEM remote: https://rubygems.org/ specs: - actioncable (6.1.7.3) - actionpack (= 6.1.7.3) - activesupport (= 6.1.7.3) + actioncable (7.0.4.3) + actionpack (= 7.0.4.3) + activesupport (= 7.0.4.3) nio4r (~> 2.0) websocket-driver (>= 0.6.1) - actionmailbox (6.1.7.3) - actionpack (= 6.1.7.3) - activejob (= 6.1.7.3) - activerecord (= 6.1.7.3) - activestorage (= 6.1.7.3) - activesupport (= 6.1.7.3) + actionmailbox (7.0.4.3) + actionpack (= 7.0.4.3) + activejob (= 7.0.4.3) + activerecord (= 7.0.4.3) + activestorage (= 7.0.4.3) + activesupport (= 7.0.4.3) mail (>= 2.7.1) - actionmailer (6.1.7.3) - actionpack (= 6.1.7.3) - actionview (= 6.1.7.3) - activejob (= 6.1.7.3) - activesupport (= 6.1.7.3) + net-imap + net-pop + net-smtp + actionmailer (7.0.4.3) + actionpack (= 7.0.4.3) + actionview (= 7.0.4.3) + activejob (= 7.0.4.3) + activesupport (= 7.0.4.3) mail (~> 2.5, >= 2.5.4) + net-imap + net-pop + net-smtp rails-dom-testing (~> 2.0) - actionpack (6.1.7.3) - actionview (= 6.1.7.3) - activesupport (= 6.1.7.3) - rack (~> 2.0, >= 2.0.9) + actionpack (7.0.4.3) + actionview (= 7.0.4.3) + activesupport (= 7.0.4.3) + rack (~> 2.0, >= 2.2.0) rack-test (>= 0.6.3) rails-dom-testing (~> 2.0) rails-html-sanitizer (~> 1.0, >= 1.2.0) - actiontext (6.1.7.3) - actionpack (= 6.1.7.3) - activerecord (= 6.1.7.3) - activestorage (= 6.1.7.3) - activesupport (= 6.1.7.3) + actiontext (7.0.4.3) + actionpack (= 7.0.4.3) + activerecord (= 7.0.4.3) + activestorage (= 7.0.4.3) + activesupport (= 7.0.4.3) + globalid (>= 0.6.0) nokogiri (>= 1.8.5) - actionview (6.1.7.3) - activesupport (= 6.1.7.3) + actionview (7.0.4.3) + activesupport (= 7.0.4.3) builder (~> 3.1) erubi (~> 1.4) rails-dom-testing (~> 2.0) rails-html-sanitizer (~> 1.1, >= 1.2.0) - activejob (6.1.7.3) - activesupport (= 6.1.7.3) + activejob (7.0.4.3) + activesupport (= 7.0.4.3) globalid (>= 0.3.6) - activemodel (6.1.7.3) - activesupport (= 6.1.7.3) - activerecord (6.1.7.3) - activemodel (= 6.1.7.3) - activesupport (= 6.1.7.3) - activestorage (6.1.7.3) - actionpack (= 6.1.7.3) - activejob (= 6.1.7.3) - activerecord (= 6.1.7.3) - activesupport (= 6.1.7.3) + activemodel (7.0.4.3) + activesupport (= 7.0.4.3) + activerecord (7.0.4.3) + activemodel (= 7.0.4.3) + activesupport (= 7.0.4.3) + activestorage (7.0.4.3) + actionpack (= 7.0.4.3) + activejob (= 7.0.4.3) + activerecord (= 7.0.4.3) + activesupport (= 7.0.4.3) marcel (~> 1.0) mini_mime (>= 1.1.0) - activesupport (6.1.7.3) + activesupport (7.0.4.3) concurrent-ruby (~> 1.0, >= 1.0.2) i18n (>= 1.6, < 2) minitest (>= 5.1) tzinfo (~> 2.0) - zeitwerk (~> 2.3) + bcrypt (3.1.18) + bootsnap (1.16.0) + msgpack (~> 1.2) bson (4.15.0) builder (3.2.4) - byebug (11.0.1) + byebug (11.1.3) + coderay (1.1.3) concurrent-ruby (1.2.2) crass (1.0.6) date (3.3.3) - diff-lcs (1.3) + debug (1.7.2) + irb (>= 1.5.0) + reline (>= 0.3.1) + diff-lcs (1.5.0) erubi (1.12.0) globalid (1.1.0) activesupport (>= 5.0) - graphiql-rails (1.7.0) + graphiql-rails (1.9.0) railties sprockets-rails - graphql (1.8.17) + graphql (2.0.21) i18n (1.12.0) concurrent-ruby (~> 1.0) + io-console (0.6.0) + irb (1.6.4) + reline (>= 0.3.0) loofah (2.20.0) crass (~> 1.0.2) nokogiri (>= 1.5.9) @@ -95,24 +110,14 @@ GEM marcel (1.0.2) method_source (1.0.0) mini_mime (1.1.2) - mini_portile2 (2.8.1) minitest (5.18.0) mongo (2.18.2) bson (>= 4.14.1, < 5.0.0) - mongoid (7.5.2) + mongoid (8.0.3) activemodel (>= 5.1, < 7.1, != 7.0.0) - mongo (>= 2.10.5, < 3.0.0) + mongo (>= 2.18.0, < 3.0.0) ruby2_keywords (~> 0.0.5) - mongoid-compatibility (0.5.1) - activesupport - mongoid (>= 2.0) - mongoid-rspec (4.0.1) - activesupport (>= 3.0.0) - mongoid (>= 3.1) - mongoid-compatibility (>= 0.5.1) - rspec (~> 3.3) - mongoid_includes (3.0.2) - mongoid (>= 7.0.10, < 9.0.0) + msgpack (1.7.0) net-imap (0.3.4) date net-protocol @@ -123,62 +128,75 @@ GEM net-smtp (0.3.3) net-protocol nio4r (2.5.9) - nokogiri (1.13.10) - mini_portile2 (~> 2.8.0) + nokogiri (1.14.3-x86_64-linux) racc (~> 1.4) - puma (3.12.1) + pry (0.14.2) + coderay (~> 1.1) + method_source (~> 1.0) + pry-byebug (3.10.1) + byebug (~> 11.0) + pry (>= 0.13, < 0.15) + puma (5.6.5) + nio4r (~> 2.0) racc (1.6.2) rack (2.2.6.4) rack-test (2.1.0) rack (>= 1.3) - rails (6.1.7.3) - actioncable (= 6.1.7.3) - actionmailbox (= 6.1.7.3) - actionmailer (= 6.1.7.3) - actionpack (= 6.1.7.3) - actiontext (= 6.1.7.3) - actionview (= 6.1.7.3) - activejob (= 6.1.7.3) - activemodel (= 6.1.7.3) - activerecord (= 6.1.7.3) - activestorage (= 6.1.7.3) - activesupport (= 6.1.7.3) + rails (7.0.4.3) + actioncable (= 7.0.4.3) + actionmailbox (= 7.0.4.3) + actionmailer (= 7.0.4.3) + actionpack (= 7.0.4.3) + actiontext (= 7.0.4.3) + actionview (= 7.0.4.3) + activejob (= 7.0.4.3) + activemodel (= 7.0.4.3) + activerecord (= 7.0.4.3) + activestorage (= 7.0.4.3) + activesupport (= 7.0.4.3) bundler (>= 1.15.0) - railties (= 6.1.7.3) - sprockets-rails (>= 2.0.0) + railties (= 7.0.4.3) rails-dom-testing (2.0.3) activesupport (>= 4.2.0) nokogiri (>= 1.6) rails-html-sanitizer (1.5.0) loofah (~> 2.19, >= 2.19.1) - railties (6.1.7.3) - actionpack (= 6.1.7.3) - activesupport (= 6.1.7.3) + railties (7.0.4.3) + actionpack (= 7.0.4.3) + activesupport (= 7.0.4.3) method_source rake (>= 12.2) thor (~> 1.0) + zeitwerk (~> 2.5) rake (13.0.6) - rspec (3.8.0) - rspec-core (~> 3.8.0) - rspec-expectations (~> 3.8.0) - rspec-mocks (~> 3.8.0) - rspec-core (3.8.2) - rspec-support (~> 3.8.0) - rspec-expectations (3.8.4) + reline (0.3.3) + io-console (~> 0.5) + rspec-core (3.12.1) + rspec-support (~> 3.12.0) + rspec-expectations (3.12.2) diff-lcs (>= 1.2.0, < 2.0) - rspec-support (~> 3.8.0) - rspec-mocks (3.8.1) + rspec-support (~> 3.12.0) + rspec-mocks (3.12.5) diff-lcs (>= 1.2.0, < 2.0) - rspec-support (~> 3.8.0) - rspec-support (3.8.2) + rspec-support (~> 3.12.0) + rspec-rails (6.0.1) + actionpack (>= 6.1) + activesupport (>= 6.1) + railties (>= 6.1) + rspec-core (~> 3.11) + rspec-expectations (~> 3.11) + rspec-mocks (~> 3.11) + rspec-support (~> 3.11) + rspec-support (3.12.0) ruby2_keywords (0.0.5) - sprockets (3.7.2) + sprockets (4.2.0) concurrent-ruby (~> 1.0) - rack (> 1, < 3) - sprockets-rails (3.2.1) - actionpack (>= 4.0) - activesupport (>= 4.0) + rack (>= 2.2.4, < 4) + sprockets-rails (3.4.2) + actionpack (>= 5.2) + activesupport (>= 5.2) sprockets (>= 3.0.0) + sqlite3 (1.6.2-x86_64-linux) thor (1.2.1) timeout (0.3.2) tzinfo (2.0.6) @@ -189,19 +207,25 @@ GEM zeitwerk (2.6.7) PLATFORMS - ruby + x86_64-linux DEPENDENCIES - byebug + bcrypt (~> 3.1.18) + bootsnap + debug graphiql-rails graphoid! - graphql - mongoid (~> 7.0) - mongoid-rspec - mongoid_includes - nokogiri (~> 1.13.9) - puma (~> 3.7) - rails (~> 6.0) + graphql (~> 2.0.21) + mongoid + pry-byebug + puma (~> 5.0) + rails (~> 7.0.4, >= 7.0.4.3) + rspec-rails + sqlite3 (~> 1.4) + tzinfo-data + +RUBY VERSION + ruby 3.2.2p53 BUNDLED WITH - 2.1.4 + 2.4.12 diff --git a/spec/tester_mongo/Rakefile b/spec/tester_mongo/Rakefile index 488c551f..d2a78aa2 100644 --- a/spec/tester_mongo/Rakefile +++ b/spec/tester_mongo/Rakefile @@ -3,6 +3,6 @@ # Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. -require_relative 'config/application' +require_relative "config/application" Rails.application.load_tasks diff --git a/spec/tester_mongo/app/models/account.rb b/spec/tester_mongo/app/models/account.rb index 4345e930..11effdcb 100644 --- a/spec/tester_mongo/app/models/account.rb +++ b/spec/tester_mongo/app/models/account.rb @@ -4,8 +4,6 @@ class Account include Mongoid::Document include Mongoid::Timestamps - include Graphoid::Queries - include Graphoid::Mutations include Graphoid::Graphield graphield :graphield0, String diff --git a/spec/tester_mongo/app/models/contract.rb b/spec/tester_mongo/app/models/contract.rb index 61d239d3..9168a5f5 100644 --- a/spec/tester_mongo/app/models/contract.rb +++ b/spec/tester_mongo/app/models/contract.rb @@ -4,9 +4,6 @@ class Contract include Mongoid::Document include Mongoid::Timestamps - include Graphoid::Queries - include Graphoid::Mutations - field :hello, type: String belongs_to :label end diff --git a/spec/tester_mongo/app/models/house.rb b/spec/tester_mongo/app/models/house.rb index 8c47469f..3a654fcd 100644 --- a/spec/tester_mongo/app/models/house.rb +++ b/spec/tester_mongo/app/models/house.rb @@ -4,9 +4,6 @@ class House include Mongoid::Document include Mongoid::Timestamps - include Graphoid::Queries - include Graphoid::Mutations - field :name, type: String has_many :accounts, dependent: :destroy diff --git a/spec/tester_mongo/app/models/label.rb b/spec/tester_mongo/app/models/label.rb index 4c95ad42..22b11d06 100644 --- a/spec/tester_mongo/app/models/label.rb +++ b/spec/tester_mongo/app/models/label.rb @@ -3,8 +3,6 @@ class Label include Mongoid::Document include Mongoid::Timestamps - include Graphoid::Queries - include Graphoid::Mutations field :snake_case, type: String field :camelCase, type: String diff --git a/spec/tester_mongo/app/models/person.rb b/spec/tester_mongo/app/models/person.rb index 43f37da4..5af1af87 100644 --- a/spec/tester_mongo/app/models/person.rb +++ b/spec/tester_mongo/app/models/person.rb @@ -3,8 +3,6 @@ class Person include Mongoid::Document include Mongoid::Timestamps - include Graphoid::Queries - include Graphoid::Mutations field :snake_case, type: String field :camelCase, type: String diff --git a/spec/tester_mongo/app/models/snake.rb b/spec/tester_mongo/app/models/snake.rb index 1d800db9..7f522880 100644 --- a/spec/tester_mongo/app/models/snake.rb +++ b/spec/tester_mongo/app/models/snake.rb @@ -3,8 +3,6 @@ class Snake include Mongoid::Document include Mongoid::Timestamps - include Graphoid::Queries - include Graphoid::Mutations field :snake_case, type: Float field :camelCase, type: Integer diff --git a/spec/tester_mongo/app/models/unused/player.rb b/spec/tester_mongo/app/models/unused/player.rb index d35be8fb..a4a65afd 100644 --- a/spec/tester_mongo/app/models/unused/player.rb +++ b/spec/tester_mongo/app/models/unused/player.rb @@ -1,4 +1,4 @@ # frozen_string_literal: true -class Player +class Unused::Player end diff --git a/spec/tester_mongo/app/models/unused/team.rb b/spec/tester_mongo/app/models/unused/team.rb index f252283a..42b8b4a6 100644 --- a/spec/tester_mongo/app/models/unused/team.rb +++ b/spec/tester_mongo/app/models/unused/team.rb @@ -1,4 +1,4 @@ # frozen_string_literal: true -class Team +class Unused::Team end diff --git a/spec/tester_mongo/app/models/user.rb b/spec/tester_mongo/app/models/user.rb index 1829e08e..2485b45e 100644 --- a/spec/tester_mongo/app/models/user.rb +++ b/spec/tester_mongo/app/models/user.rb @@ -4,9 +4,6 @@ class User include Mongoid::Document include Mongoid::Timestamps - include Graphoid::Queries - include Graphoid::Mutations - field :name, type: String has_and_belongs_to_many :dependencies, class_name: 'User', inverse_of: :dependents diff --git a/spec/tester_mongo/app/models/value.rb b/spec/tester_mongo/app/models/value.rb index 74e1cd3d..e9f12350 100644 --- a/spec/tester_mongo/app/models/value.rb +++ b/spec/tester_mongo/app/models/value.rb @@ -3,8 +3,6 @@ class Value include Mongoid::Document include Mongoid::Timestamps - include Graphoid::Queries - include Graphoid::Mutations field :text, type: String field :name, type: String diff --git a/spec/tester_mongo/bin/bundle b/spec/tester_mongo/bin/bundle index 2dbb7176..42c7fd7c 100755 --- a/spec/tester_mongo/bin/bundle +++ b/spec/tester_mongo/bin/bundle @@ -1,5 +1,109 @@ #!/usr/bin/env ruby # frozen_string_literal: true -ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) -load Gem.bin_path('bundler', 'bundle') +# +# This file was generated by Bundler. +# +# The application 'bundle' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +require "rubygems" + +m = Module.new do + module_function + + def invoked_as_script? + File.expand_path($0) == File.expand_path(__FILE__) + end + + def env_var_version + ENV["BUNDLER_VERSION"] + end + + def cli_arg_version + return unless invoked_as_script? # don't want to hijack other binstubs + return unless "update".start_with?(ARGV.first || " ") # must be running `bundle update` + bundler_version = nil + update_index = nil + ARGV.each_with_index do |a, i| + if update_index && update_index.succ == i && a =~ Gem::Version::ANCHORED_VERSION_PATTERN + bundler_version = a + end + next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/ + bundler_version = $1 + update_index = i + end + bundler_version + end + + def gemfile + gemfile = ENV["BUNDLE_GEMFILE"] + return gemfile if gemfile && !gemfile.empty? + + File.expand_path("../Gemfile", __dir__) + end + + def lockfile + lockfile = + case File.basename(gemfile) + when "gems.rb" then gemfile.sub(/\.rb$/, ".locked") + else "#{gemfile}.lock" + end + File.expand_path(lockfile) + end + + def lockfile_version + return unless File.file?(lockfile) + lockfile_contents = File.read(lockfile) + return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/ + Regexp.last_match(1) + end + + def bundler_requirement + @bundler_requirement ||= + env_var_version || + cli_arg_version || + bundler_requirement_for(lockfile_version) + end + + def bundler_requirement_for(version) + return "#{Gem::Requirement.default}.a" unless version + + bundler_gem_version = Gem::Version.new(version) + + bundler_gem_version.approximate_recommendation + end + + def load_bundler! + ENV["BUNDLE_GEMFILE"] ||= gemfile + + activate_bundler + end + + def activate_bundler + gem_error = activation_error_handling do + gem "bundler", bundler_requirement + end + return if gem_error.nil? + require_error = activation_error_handling do + require "bundler/version" + end + return if require_error.nil? && Gem::Requirement.new(bundler_requirement).satisfied_by?(Gem::Version.new(Bundler::VERSION)) + warn "Activating bundler (#{bundler_requirement}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_requirement}'`" + exit 42 + end + + def activation_error_handling + yield + nil + rescue StandardError, LoadError => e + e + end +end + +m.load_bundler! + +if m.invoked_as_script? + load Gem.bin_path("bundler", "bundle") +end diff --git a/spec/tester_mongo/bin/rails b/spec/tester_mongo/bin/rails index a31728ab..efc03774 100755 --- a/spec/tester_mongo/bin/rails +++ b/spec/tester_mongo/bin/rails @@ -1,6 +1,4 @@ #!/usr/bin/env ruby -# frozen_string_literal: true - -APP_PATH = File.expand_path('../config/application', __dir__) -require_relative '../config/boot' -require 'rails/commands' +APP_PATH = File.expand_path("../config/application", __dir__) +require_relative "../config/boot" +require "rails/commands" diff --git a/spec/tester_mongo/bin/rake b/spec/tester_mongo/bin/rake index c1999550..4fbf10b9 100755 --- a/spec/tester_mongo/bin/rake +++ b/spec/tester_mongo/bin/rake @@ -1,6 +1,4 @@ #!/usr/bin/env ruby -# frozen_string_literal: true - -require_relative '../config/boot' -require 'rake' +require_relative "../config/boot" +require "rake" Rake.application.run diff --git a/spec/tester_mongo/bin/setup b/spec/tester_mongo/bin/setup index 3b7333ed..ec47b79b 100755 --- a/spec/tester_mongo/bin/setup +++ b/spec/tester_mongo/bin/setup @@ -1,39 +1,33 @@ #!/usr/bin/env ruby -# frozen_string_literal: true - -require 'pathname' -require 'fileutils' -include FileUtils +require "fileutils" # path to your application root. -APP_ROOT = Pathname.new File.expand_path('..', __dir__) +APP_ROOT = File.expand_path("..", __dir__) def system!(*args) system(*args) || abort("\n== Command #{args} failed ==") end -chdir APP_ROOT do - # This script is a starting point to setup your application. +FileUtils.chdir APP_ROOT do + # This script is a way to set up or update your development environment automatically. + # This script is idempotent, so that you can run it at any time and get an expectable outcome. # Add necessary setup steps to this file. - puts '== Installing dependencies ==' - system! 'gem install bundler --conservative' - system('bundle check') || system!('bundle install') - - # Install JavaScript dependencies if using Yarn - # system('bin/yarn') + puts "== Installing dependencies ==" + system! "gem install bundler --conservative" + system("bundle check") || system!("bundle install") # puts "\n== Copying sample files ==" - # unless File.exist?('config/database.yml') - # cp 'config/database.yml.sample', 'config/database.yml' + # unless File.exist?("config/database.yml") + # FileUtils.cp "config/database.yml.sample", "config/database.yml" # end puts "\n== Preparing database ==" - system! 'bin/rails db:setup' + system! "bin/rails db:prepare" puts "\n== Removing old logs and tempfiles ==" - system! 'bin/rails log:clear tmp:clear' + system! "bin/rails log:clear tmp:clear" puts "\n== Restarting application server ==" - system! 'bin/rails restart' + system! "bin/rails restart" end diff --git a/spec/tester_mongo/bin/update b/spec/tester_mongo/bin/update deleted file mode 100755 index 1d6aa6a5..00000000 --- a/spec/tester_mongo/bin/update +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env ruby -# frozen_string_literal: true - -require 'pathname' -require 'fileutils' -include FileUtils - -# path to your application root. -APP_ROOT = Pathname.new File.expand_path('..', __dir__) - -def system!(*args) - system(*args) || abort("\n== Command #{args} failed ==") -end - -chdir APP_ROOT do - # This script is a way to update your development environment automatically. - # Add necessary update steps to this file. - - puts '== Installing dependencies ==' - system! 'gem install bundler --conservative' - system('bundle check') || system!('bundle install') - - puts "\n== Updating database ==" - system! 'bin/rails db:migrate' - - puts "\n== Removing old logs and tempfiles ==" - system! 'bin/rails log:clear tmp:clear' - - puts "\n== Restarting application server ==" - system! 'bin/rails restart' -end diff --git a/spec/tester_mongo/bin/yarn b/spec/tester_mongo/bin/yarn deleted file mode 100755 index 80b670de..00000000 --- a/spec/tester_mongo/bin/yarn +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env ruby -# frozen_string_literal: true - -VENDOR_PATH = File.expand_path('..', __dir__) -Dir.chdir(VENDOR_PATH) do - exec "yarnpkg #{ARGV.join(' ')}" -rescue Errno::ENOENT - warn 'Yarn executable was not detected in the system.' - warn 'Download Yarn at https://yarnpkg.com/en/docs/install' - exit 1 -end diff --git a/spec/tester_mongo/config.ru b/spec/tester_mongo/config.ru index 842bccc3..4a3c09a6 100644 --- a/spec/tester_mongo/config.ru +++ b/spec/tester_mongo/config.ru @@ -1,7 +1,6 @@ -# frozen_string_literal: true - # This file is used by Rack-based servers to start the application. -require_relative 'config/environment' +require_relative "config/environment" run Rails.application +Rails.application.load_server diff --git a/spec/tester_mongo/config/application.rb b/spec/tester_mongo/config/application.rb index d3127c80..f327cf71 100644 --- a/spec/tester_mongo/config/application.rb +++ b/spec/tester_mongo/config/application.rb @@ -1,28 +1,51 @@ # frozen_string_literal: true -require_relative 'boot' +require_relative "boot" -require 'rails' +require "rails" +# Pick the frameworks you want: +require "active_model/railtie" +require "active_job/railtie" +# require "active_record/railtie" +require "active_storage/engine" +require "action_controller/railtie" +require "action_mailer/railtie" +# require "action_mailbox/engine" +# require "action_text/engine" +require "action_view/railtie" +require "action_cable/engine" +require "rails/test_unit/railtie" -require 'active_model/railtie' -require 'active_job/railtie' -require 'action_controller/railtie' -require 'action_mailer/railtie' -require 'action_view/railtie' -require 'action_cable/engine' -require 'sprockets/railtie' -require 'rails/test_unit/railtie' +if Rails.env.development? + require "sprockets/railtie" +end +# Require the gems listed in Gemfile, including any gems +# you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) -require 'graphoid' -module TesterMongo +module DummyRailsApp class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. - config.load_defaults 5.1 + config.load_defaults 7.0 + + # Configuration for the application, engines, and railties goes here. + # + # These settings can be overridden in specific environments using the files + # in config/environments, which are processed later. + # + # config.time_zone = "Central Time (US & Canada)" + # config.eager_load_paths << Rails.root.join("extras") + + # Only loads a smaller set of middleware suitable for API only apps. + # Middleware like session, flash, cookies can be added back manually. + # Skip views, helpers and assets when generating a new resource. + config.api_only = true - # Settings in config/environments/* take precedence over those specified here. - # Application configuration should go into files in config/initializers - # -- all .rb files in that directory are automatically loaded. + if Rails.env.development? + config.middleware.use ActionDispatch::Cookies + config.middleware.use ActionDispatch::Session::CookieStore + config.session_store :cookie_store, key: '_graphql-rails-sample' + end end end diff --git a/spec/tester_mongo/config/boot.rb b/spec/tester_mongo/config/boot.rb index 6d2cba07..aef6d031 100644 --- a/spec/tester_mongo/config/boot.rb +++ b/spec/tester_mongo/config/boot.rb @@ -1,7 +1,6 @@ # frozen_string_literal: true -# Set up gems listed in the Gemfile. -ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../Gemfile', __dir__) +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) -require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) -$LOAD_PATH.unshift File.expand_path('../../../lib', __dir__) +require "bundler/setup" # Set up gems listed in the Gemfile. +require "bootsnap/setup" # Speed up boot time by caching expensive operations. diff --git a/spec/tester_mongo/config/cable.yml b/spec/tester_mongo/config/cable.yml index 152992b6..a6d27328 100644 --- a/spec/tester_mongo/config/cable.yml +++ b/spec/tester_mongo/config/cable.yml @@ -2,9 +2,9 @@ development: adapter: async test: - adapter: async + adapter: test production: adapter: redis - url: redis://localhost:6379/1 - channel_prefix: tester_mongo_production + url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %> + channel_prefix: graphql_rails_sample_production diff --git a/spec/tester_mongo/config/credentials.yml.enc b/spec/tester_mongo/config/credentials.yml.enc new file mode 100644 index 00000000..d8c6d420 --- /dev/null +++ b/spec/tester_mongo/config/credentials.yml.enc @@ -0,0 +1 @@ +F2JALo6ECmNmT+sWHWhucR13GVNC1KrpZM2pZo64vtFSfpUJBLPjUFK+3T3YIarQIOpOtnNP00j5D3pqmM5H7JzBBR7+EusZYSqhyc3vRVK7t6NjQfkmXze7LL23ENAi6IfGGOtUdbycjE/sJGAXYpqi18XWq119K/bA09R9e2T89poQb9bd57Vq1n1ijvb3iYAMQe9KKsqJgV1ZRZU7g7F7gqJVq/BZapZNy7GqJG0ubWk0yKtSA4SIXLqKvG3/c31iLWSOryUXI02cEtRm1n2WSLGKjHsqNRAsblPioyTBS/qmvDJPvGCEHDB3OR6ASvxVwbHmqd7vqPBVmz2NcJABSLeHaisNhzT0iihfULuutPr7FXwG08vkI4pLjLRa1q1skCi5UaKOYrjwPOGJqqVBiiXxoxTMy+AG--7DPvY8kiFV3T+X+B--1btNZVzf7faPAbzA8g+olQ== \ No newline at end of file diff --git a/spec/tester_mongo/config/database.yml b/spec/tester_mongo/config/database.yml new file mode 100644 index 00000000..fcba57f1 --- /dev/null +++ b/spec/tester_mongo/config/database.yml @@ -0,0 +1,25 @@ +# SQLite. Versions 3.8.0 and up are supported. +# gem install sqlite3 +# +# Ensure the SQLite 3 gem is defined in your Gemfile +# gem "sqlite3" +# +default: &default + adapter: sqlite3 + pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> + timeout: 5000 + +development: + <<: *default + database: db/development.sqlite3 + +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". +# Do not set this db to the same as development or production. +test: + <<: *default + database: db/test.sqlite3 + +production: + <<: *default + database: db/production.sqlite3 diff --git a/spec/tester_mongo/config/environment.rb b/spec/tester_mongo/config/environment.rb index d5abe558..7df99e89 100644 --- a/spec/tester_mongo/config/environment.rb +++ b/spec/tester_mongo/config/environment.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true # Load the Rails application. -require_relative 'application' +require_relative "application" # Initialize the Rails application. Rails.application.initialize! diff --git a/spec/tester_mongo/config/environments/development.rb b/spec/tester_mongo/config/environments/development.rb index 012f9eb1..5cb98e19 100644 --- a/spec/tester_mongo/config/environments/development.rb +++ b/spec/tester_mongo/config/environments/development.rb @@ -1,10 +1,12 @@ # frozen_string_literal: true +require "active_support/core_ext/integer/time" + Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. - # In the development environment your application's code is reloaded on - # every request. This slows down response time but is perfect for development + # In the development environment your application's code is reloaded any time + # it changes. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false @@ -14,13 +16,15 @@ # Show full error reports. config.consider_all_requests_local = true - # Enable/disable caching. By default caching is disabled. - if Rails.root.join('tmp/caching-dev.txt').exist? - config.action_controller.perform_caching = true + # Enable server timing + config.server_timing = true + # Enable/disable caching. By default caching is disabled. + # Run rails dev:cache to toggle caching. + if Rails.root.join("tmp/caching-dev.txt").exist? config.cache_store = :memory_store config.public_file_server.headers = { - 'Cache-Control' => "public, max-age=#{2.days.seconds.to_i}" + "Cache-Control" => "public, max-age=#{2.days.to_i}" } else config.action_controller.perform_caching = false @@ -28,6 +32,9 @@ config.cache_store = :null_store end + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.service = :local + # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false @@ -36,18 +43,21 @@ # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log - # Debug mode disables concatenation and preprocessing of assets. - # This option may cause significant delays in view rendering with a large - # number of complex assets. - config.assets.debug = true + # Raise exceptions for disallowed deprecations. + config.active_support.disallowed_deprecation = :raise + + # Tell Active Support which deprecation messages to disallow. + config.active_support.disallowed_deprecation_warnings = [] + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true - # Suppress logger output for asset requests. - config.assets.quiet = true + # Annotate rendered view with file names. + # config.action_view.annotate_rendered_view_with_filenames = true - # Raises error for missing translations - # config.action_view.raise_on_missing_translations = true + # Uncomment if you wish to allow Action Cable access from any origin. + # config.action_cable.disable_request_forgery_protection = true - # Use an evented file watcher to asynchronously detect changes in source code, - # routes, locales, etc. This feature depends on the listen gem. - # config.file_watcher = ActiveSupport::EventedFileUpdateChecker + # required by session store + config.action_controller.allow_forgery_protection = true end diff --git a/spec/tester_mongo/config/environments/production.rb b/spec/tester_mongo/config/environments/production.rb index a15c341e..81ca98bf 100644 --- a/spec/tester_mongo/config/environments/production.rb +++ b/spec/tester_mongo/config/environments/production.rb @@ -1,5 +1,7 @@ # frozen_string_literal: true +require "active_support/core_ext/integer/time" + Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. @@ -14,53 +16,47 @@ # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false - config.action_controller.perform_caching = true - # Attempt to read encrypted secrets from `config/secrets.yml.enc`. - # Requires an encryption key in `ENV["RAILS_MASTER_KEY"]` or - # `config/secrets.yml.key`. - config.read_encrypted_secrets = true + # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] + # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). + # config.require_master_key = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. - config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? - - # Compress JavaScripts and CSS. - config.assets.js_compressor = :uglifier - # config.assets.css_compressor = :sass - - # Do not fallback to assets pipeline if a precompiled asset is missed. - config.assets.compile = false - - # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb + config.public_file_server.enabled = ENV["RAILS_SERVE_STATIC_FILES"].present? # Enable serving of images, stylesheets, and JavaScripts from an asset server. - # config.action_controller.asset_host = 'http://assets.example.com' + # config.asset_host = "http://assets.example.com" # Specifies the header that your server uses for sending files. - # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache - # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX + # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for Apache + # config.action_dispatch.x_sendfile_header = "X-Accel-Redirect" # for NGINX + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.service = :local - # Mount Action Cable outside main process or domain + # Mount Action Cable outside main process or domain. # config.action_cable.mount_path = nil - # config.action_cable.url = 'wss://example.com/cable' - # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] + # config.action_cable.url = "wss://example.com/cable" + # config.action_cable.allowed_request_origins = [ "http://example.com", /http:\/\/example.*/ ] + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true - # Use the lowest log level to ensure availability of diagnostic information - # when problems arise. - config.log_level = :debug + # Include generic and useful information about system operation, but avoid logging too much + # information to avoid inadvertent exposure of personally identifiable information (PII). + config.log_level = :info # Prepend all log lines with the following tags. - config.log_tags = [:request_id] + config.log_tags = [ :request_id ] # Use a different cache store in production. # config.cache_store = :mem_cache_store - # Use a real queuing backend for Active Job (and separate queues per environment) + # Use a real queuing backend for Active Job (and separate queues per environment). # config.active_job.queue_adapter = :resque - # config.active_job.queue_name_prefix = "tester_mongo_#{Rails.env}" + # config.active_job.queue_name_prefix = "graphql_rails_sample_production" + config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. @@ -71,17 +67,17 @@ # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true - # Send deprecation notices to registered listeners. - config.active_support.deprecation = :notify + # Don't log any deprecations. + config.active_support.report_deprecations = false # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Use a different logger for distributed setups. - # require 'syslog/logger' - # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') + # require "syslog/logger" + # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new "app-name") - if ENV['RAILS_LOG_TO_STDOUT'].present? + if ENV["RAILS_LOG_TO_STDOUT"].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) diff --git a/spec/tester_mongo/config/environments/test.rb b/spec/tester_mongo/config/environments/test.rb index 669350ab..08426ee9 100644 --- a/spec/tester_mongo/config/environments/test.rb +++ b/spec/tester_mongo/config/environments/test.rb @@ -1,34 +1,44 @@ # frozen_string_literal: true +require "active_support/core_ext/integer/time" + +# The test environment is used exclusively to run your application's +# test suite. You never need to work with it otherwise. Remember that +# your test database is "scratch space" for the test suite and is wiped +# and recreated between test runs. Don't rely on the data there! + Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. - # The test environment is used exclusively to run your application's - # test suite. You never need to work with it otherwise. Remember that - # your test database is "scratch space" for the test suite and is wiped - # and recreated between test runs. Don't rely on the data there! + # Turn false under Spring and add config.action_view.cache_template_loading = true. config.cache_classes = true - # Do not eager load code on boot. This avoids loading your whole application - # just for the purpose of running a single test. If you are using a tool that - # preloads Rails for running tests, you may have to set it to true. + # Eager loading loads your whole application. When running a single test locally, + # this probably isn't necessary. It's a good idea to do in a continuous integration + # system, or in some way before deploying your code. + # config.eager_load = ENV["CI"].present? config.eager_load = false # Configure public file server for tests with Cache-Control for performance. config.public_file_server.enabled = true config.public_file_server.headers = { - 'Cache-Control' => "public, max-age=#{1.hour.seconds.to_i}" + "Cache-Control" => "public, max-age=#{1.hour.to_i}" } # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false + config.cache_store = :null_store # Raise exceptions instead of rendering exception templates. config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment. config.action_controller.allow_forgery_protection = false + + # Store uploaded files on the local file system in a temporary directory. + config.active_storage.service = :test + config.action_mailer.perform_caching = false # Tell Action Mailer not to deliver emails to the real world. @@ -39,6 +49,15 @@ # Print deprecation notices to the stderr. config.active_support.deprecation = :stderr - # Raises error for missing translations - # config.action_view.raise_on_missing_translations = true + # Raise exceptions for disallowed deprecations. + config.active_support.disallowed_deprecation = :raise + + # Tell Active Support which deprecation messages to disallow. + config.active_support.disallowed_deprecation_warnings = [] + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true + + # Annotate rendered view with file names. + # config.action_view.annotate_rendered_view_with_filenames = true end diff --git a/spec/tester_mongo/config/initializers/application_controller_renderer.rb b/spec/tester_mongo/config/initializers/application_controller_renderer.rb deleted file mode 100644 index 6e2d5d2b..00000000 --- a/spec/tester_mongo/config/initializers/application_controller_renderer.rb +++ /dev/null @@ -1,8 +0,0 @@ -# frozen_string_literal: true - -# Be sure to restart your server when you modify this file. - -# ApplicationController.renderer.defaults.merge!( -# http_host: 'example.org', -# https: false -# ) diff --git a/spec/tester_mongo/config/initializers/assets.rb b/spec/tester_mongo/config/initializers/assets.rb deleted file mode 100644 index a9b0d0f1..00000000 --- a/spec/tester_mongo/config/initializers/assets.rb +++ /dev/null @@ -1,16 +0,0 @@ -# frozen_string_literal: true - -# Be sure to restart your server when you modify this file. - -# Version of your assets, change this if you want to expire all your assets. -Rails.application.config.assets.version = '1.0' - -# Add additional assets to the asset load path. -# Rails.application.config.assets.paths << Emoji.images_path -# Add Yarn node_modules folder to the asset load path. -Rails.application.config.assets.paths << Rails.root.join('node_modules') - -# Precompile additional assets. -# application.js, application.css, and all non-JS/CSS in the app/assets -# folder are already added. -# Rails.application.config.assets.precompile += %w( admin.js admin.css ) diff --git a/spec/tester_mongo/config/initializers/backtrace_silencers.rb b/spec/tester_mongo/config/initializers/backtrace_silencers.rb deleted file mode 100644 index 4b63f289..00000000 --- a/spec/tester_mongo/config/initializers/backtrace_silencers.rb +++ /dev/null @@ -1,9 +0,0 @@ -# frozen_string_literal: true - -# Be sure to restart your server when you modify this file. - -# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. -# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } - -# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. -# Rails.backtrace_cleaner.remove_silencers! diff --git a/spec/tester_mongo/config/initializers/cookies_serializer.rb b/spec/tester_mongo/config/initializers/cookies_serializer.rb deleted file mode 100644 index ee8dff9c..00000000 --- a/spec/tester_mongo/config/initializers/cookies_serializer.rb +++ /dev/null @@ -1,7 +0,0 @@ -# frozen_string_literal: true - -# Be sure to restart your server when you modify this file. - -# Specify a serializer for the signed and encrypted cookie jars. -# Valid options are :json, :marshal, and :hybrid. -Rails.application.config.action_dispatch.cookies_serializer = :json diff --git a/spec/tester_mongo/config/initializers/cors.rb b/spec/tester_mongo/config/initializers/cors.rb new file mode 100644 index 00000000..62875c1a --- /dev/null +++ b/spec/tester_mongo/config/initializers/cors.rb @@ -0,0 +1,18 @@ +# frozen_string_literal: true + +# Be sure to restart your server when you modify this file. + +# Avoid CORS issues when API is called from the frontend app. +# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests. + +# Read more: https://github.com/cyu/rack-cors + +# Rails.application.config.middleware.insert_before 0, Rack::Cors do +# allow do +# origins "example.com" +# +# resource "*", +# headers: :any, +# methods: [:get, :post, :put, :patch, :delete, :options, :head] +# end +# end diff --git a/spec/tester_mongo/config/initializers/filter_parameter_logging.rb b/spec/tester_mongo/config/initializers/filter_parameter_logging.rb index 7a4f47b4..ca55f952 100644 --- a/spec/tester_mongo/config/initializers/filter_parameter_logging.rb +++ b/spec/tester_mongo/config/initializers/filter_parameter_logging.rb @@ -2,5 +2,9 @@ # Be sure to restart your server when you modify this file. -# Configure sensitive parameters which will be filtered from the log file. -Rails.application.config.filter_parameters += [:password] +# Configure parameters to be filtered from the log file. Use this to limit dissemination of +# sensitive information. See the ActiveSupport::ParameterFilter documentation for supported +# notations and behaviors. +Rails.application.config.filter_parameters += [ + :passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn +] diff --git a/spec/tester_mongo/config/initializers/graphoid.rb b/spec/tester_mongo/config/initializers/graphoid.rb index 7e62a21b..d3a0fb06 100644 --- a/spec/tester_mongo/config/initializers/graphoid.rb +++ b/spec/tester_mongo/config/initializers/graphoid.rb @@ -1,5 +1,12 @@ # frozen_string_literal: true -Graphoid.configure do |config| - config.driver = :mongoid +Rails.application.config.after_initialize do + Graphoid.configure do |config| + config.driver = :mongoid + end + + Graphoid.initialize + Graphoid::Types.initialize(User, House, Label, Snake, Value, Person, Account, Contract) + Graphoid::Queries.generate(User, House, Label, Snake, Value, Person, Account, Contract) + Graphoid::Mutations.generate(User, House, Label, Snake, Value, Person, Account, Contract) end diff --git a/spec/tester_mongo/config/initializers/inflections.rb b/spec/tester_mongo/config/initializers/inflections.rb index dc847422..9e049dcc 100644 --- a/spec/tester_mongo/config/initializers/inflections.rb +++ b/spec/tester_mongo/config/initializers/inflections.rb @@ -6,13 +6,13 @@ # are locale specific, and you may define rules for as many different # locales as you wish. All of these examples are active by default: # ActiveSupport::Inflector.inflections(:en) do |inflect| -# inflect.plural /^(ox)$/i, '\1en' -# inflect.singular /^(ox)en/i, '\1' -# inflect.irregular 'person', 'people' +# inflect.plural /^(ox)$/i, "\\1en" +# inflect.singular /^(ox)en/i, "\\1" +# inflect.irregular "person", "people" # inflect.uncountable %w( fish sheep ) # end # These inflection rules are supported but not enabled by default: # ActiveSupport::Inflector.inflections(:en) do |inflect| -# inflect.acronym 'RESTful' +# inflect.acronym "RESTful" # end diff --git a/spec/tester_mongo/config/initializers/mime_types.rb b/spec/tester_mongo/config/initializers/mime_types.rb deleted file mode 100644 index be6fedc5..00000000 --- a/spec/tester_mongo/config/initializers/mime_types.rb +++ /dev/null @@ -1,6 +0,0 @@ -# frozen_string_literal: true - -# Be sure to restart your server when you modify this file. - -# Add new mime types for use in respond_to blocks: -# Mime::Type.register "text/richtext", :rtf diff --git a/spec/tester_mongo/config/initializers/wrap_parameters.rb b/spec/tester_mongo/config/initializers/wrap_parameters.rb deleted file mode 100644 index 5733a40c..00000000 --- a/spec/tester_mongo/config/initializers/wrap_parameters.rb +++ /dev/null @@ -1,5 +0,0 @@ -# frozen_string_literal: true - -ActiveSupport.on_load(:action_controller) do - wrap_parameters format: [:json] -end diff --git a/spec/tester_mongo/config/locales/en.yml b/spec/tester_mongo/config/locales/en.yml index decc5a85..8ca56fc7 100644 --- a/spec/tester_mongo/config/locales/en.yml +++ b/spec/tester_mongo/config/locales/en.yml @@ -4,11 +4,11 @@ # # To use the locales, use `I18n.t`: # -# I18n.t 'hello' +# I18n.t "hello" # # In views, this is aliased to just `t`: # -# <%= t('hello') %> +# <%= t("hello") %> # # To use a different locale, set it with `I18n.locale`: # @@ -24,10 +24,10 @@ # Instead, surround them with single quotes. # # en: -# 'true': 'foo' +# "true": "foo" # # To learn more, please read the Rails Internationalization guide -# available at http://guides.rubyonrails.org/i18n.html. +# available at https://guides.rubyonrails.org/i18n.html. en: hello: "Hello world" diff --git a/spec/tester_mongo/config/mongoid.yml b/spec/tester_mongo/config/mongoid.yml index 1c843572..4d1a7eed 100644 --- a/spec/tester_mongo/config/mongoid.yml +++ b/spec/tester_mongo/config/mongoid.yml @@ -1,158 +1,13 @@ -<% port = ENV['MONGODB_PORT'] || 27017 %> development: - # Configure available database clients. (required) clients: - # Defines the default client. (required) default: - # Defines the name of the default database that Mongoid can connect to. - # (required). - database: graphql_mongoid_spike2_development - # Provides the hosts the default client can connect to. Must be an array - # of host:port pairs. (required) + database: graphoid hosts: - - localhost:<%=port%> - options: - # Change the default write concern. (default = { w: 1 }) - # write: - # w: 1 + - localhost:27017 - # Change the default read preference. Valid options for mode are: :secondary, - # :secondary_preferred, :primary, :primary_preferred, :nearest - # (default: primary) - # read: - # mode: :secondary_preferred - # tag_sets: - # - use: web - - # The name of the user for authentication. - # user: 'user' - - # The password of the user for authentication. - # password: 'password' - - # The user's database roles. - # roles: - # - 'dbOwner' - - # Change the default authentication mechanism. Valid options are: :scram, - # :mongodb_cr, :mongodb_x509, and :plain. Note that all authentication - # mechanisms require username and password, with the exception of :mongodb_x509. - # Default on mongoDB 3.0 is :scram, default on 2.4 and 2.6 is :plain. - # auth_mech: :scram - - # The database or source to authenticate the user against. - # (default: the database specified above or admin) - # auth_source: admin - - # Force a the driver cluster to behave in a certain manner instead of auto- - # discovering. Can be one of: :direct, :replica_set, :sharded. Set to :direct - # when connecting to hidden members of a replica set. - # connect: :direct - - # Changes the default time in seconds the server monitors refresh their status - # via ismaster commands. (default: 10) - # heartbeat_frequency: 10 - - # The time in seconds for selecting servers for a near read preference. (default: 0.015) - # local_threshold: 0.015 - - # The timeout in seconds for selecting a server for an operation. (default: 30) - # server_selection_timeout: 30 - - # The maximum number of connections in the connection pool. (default: 5) - # max_pool_size: 5 - - # The minimum number of connections in the connection pool. (default: 1) - # min_pool_size: 1 - - # The time to wait, in seconds, in the connection pool for a connection - # to be checked in before timing out. (default: 5) - # wait_queue_timeout: 5 - - # The time to wait to establish a connection before timing out, in seconds. - # (default: 5) - # connect_timeout: 5 - - # The timeout to wait to execute operations on a socket before raising an error. - # (default: 5) - # socket_timeout: 5 - - # The name of the replica set to connect to. Servers provided as seeds that do - # not belong to this replica set will be ignored. - # replica_set: name - - # Whether to connect to the servers via ssl. (default: false) - # ssl: true - - # The certificate file used to identify the connection against MongoDB. - # ssl_cert: /path/to/my.cert - - # The private keyfile used to identify the connection against MongoDB. - # Note that even if the key is stored in the same file as the certificate, - # both need to be explicitly specified. - # ssl_key: /path/to/my.key - - # A passphrase for the private key. - # ssl_key_pass_phrase: password - - # Whether or not to do peer certification validation. (default: true) - # ssl_verify: true - - # The file containing a set of concatenated certification authority certifications - # used to validate certs passed from the other end of the connection. - # ssl_ca_cert: /path/to/ca.cert - - - # Configure Mongoid specific options. (optional) - options: - # Includes the root model name in json serialization. (default: false) - # include_root_in_json: false - - # Include the _type field in serialization. (default: false) - # include_type_for_serialization: false - - # Preload all models in development, needed when models use - # inheritance. (default: false) - # preload_models: false - - # Raise an error when performing a #find and the document is not found. - # (default: true) - # raise_not_found_error: true - - # Raise an error when defining a scope with the same name as an - # existing method. (default: false) - # scope_overwrite_exception: false - - # Raise an error when defining a field with the same name as an - # existing method. (default: false) - # duplicate_fields_exception: false - - # Use Active Support's time zone in conversions. (default: true) - # use_activesupport_time_zone: true - - # Ensure all times are UTC in the app side. (default: false) - # use_utc: false - - # Set the Mongoid and Ruby driver log levels when not in a Rails - # environment. The Mongoid logger will be set to the Rails logger - # otherwise.(default: :info) - # log_level: :info - - # Control whether `belongs_to` association is required. By default - # `belongs_to` will trigger a validation error if the association - # is not present. (default: true) - # belongs_to_required_by_default: true - - # Application name that is printed to the mongodb logs upon establishing a - # connection in server versions >= 3.4. Note that the name cannot exceed 128 bytes. - # app_name: MyApplicationName test: clients: default: - database: graphql_mongoid_spike2_test + database: graphoid_test hosts: - - localhost:<%=port%> - options: - read: - mode: :primary - max_pool_size: 1 + - localhost:27017 diff --git a/spec/tester_mongo/config/puma.rb b/spec/tester_mongo/config/puma.rb index 6ec461f5..ea3b5502 100644 --- a/spec/tester_mongo/config/puma.rb +++ b/spec/tester_mongo/config/puma.rb @@ -6,19 +6,28 @@ # the maximum value specified for Puma. Default is set to 5 threads for minimum # and maximum; this matches the default thread size of Active Record. # -threads_count = ENV.fetch('RAILS_MAX_THREADS') { 5 } -threads threads_count, threads_count +max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } +min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count } +threads min_threads_count, max_threads_count + +# Specifies the `worker_timeout` threshold that Puma will use to wait before +# terminating a worker in development environments. +# +worker_timeout 3600 if ENV.fetch("RAILS_ENV", "development") == "development" # Specifies the `port` that Puma will listen on to receive requests; default is 3000. # -port ENV.fetch('PORT') { 3000 } +port ENV.fetch("PORT") { 3000 } # Specifies the `environment` that Puma will run in. # -environment ENV.fetch('RAILS_ENV') { 'development' } +environment ENV.fetch("RAILS_ENV") { "development" } + +# Specifies the `pidfile` that Puma will use. +pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" } # Specifies the number of `workers` to boot in clustered mode. -# Workers are forked webserver processes. If using threads and workers together +# Workers are forked web server processes. If using threads and workers together # the concurrency of the application would be max `threads` * `workers`. # Workers do not work on JRuby or Windows (both of which do not support # processes). @@ -28,31 +37,9 @@ # Use the `preload_app!` method when specifying a `workers` number. # This directive tells Puma to first boot the application and load code # before forking the application. This takes advantage of Copy On Write -# process behavior so workers use less memory. If you use this option -# you need to make sure to reconnect any threads in the `on_worker_boot` -# block. +# process behavior so workers use less memory. # # preload_app! -# If you are preloading your application and using Active Record, it's -# recommended that you close any connections to the database before workers -# are forked to prevent connection leakage. -# -# before_fork do -# ActiveRecord::Base.connection_pool.disconnect! if defined?(ActiveRecord) -# end - -# The code in the `on_worker_boot` will be called if you are using -# clustered mode by specifying a number of `workers`. After each worker -# process is booted, this block will be run. If you are using the `preload_app!` -# option, you will want to use this block to reconnect to any threads -# or connections that may have been created at application boot, as Ruby -# cannot share connections between processes. -# -# on_worker_boot do -# ActiveRecord::Base.establish_connection if defined?(ActiveRecord) -# end -# - -# Allow puma to be restarted by `rails restart` command. +# Allow puma to be restarted by `bin/rails restart` command. plugin :tmp_restart diff --git a/spec/tester_mongo/config/routes.rb b/spec/tester_mongo/config/routes.rb index 70d858d6..74010493 100644 --- a/spec/tester_mongo/config/routes.rb +++ b/spec/tester_mongo/config/routes.rb @@ -1,9 +1,9 @@ # frozen_string_literal: true Rails.application.routes.draw do + post "/graphql", to: "graphql#execute" + if Rails.env.development? - mount GraphiQL::Rails::Engine, at: '/graphiql', graphql_path: '/graphql' + mount GraphiQL::Rails::Engine, at: "/graphiql", graphql_path: "/graphql" end - - post '/graphql', to: 'graphql#execute' end diff --git a/spec/tester_mongo/config/secrets.yml b/spec/tester_mongo/config/secrets.yml deleted file mode 100644 index 06233387..00000000 --- a/spec/tester_mongo/config/secrets.yml +++ /dev/null @@ -1,29 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# Make sure the secret is at least 30 characters and all random, -# no regular words or you'll be exposed to dictionary attacks. -# You can use `rails secret` to generate a secure secret key. - -# Make sure the secrets in this file are kept private -# if you're sharing your code publicly. - -# Shared secrets are available across all environments. - -# shared: -# api_key: a1B2c3D4e5F6 - -# Environmental secrets are only available for that specific environment. - -development: - secret_key_base: eb33635e0b230eca06858304c73497bdf800d175abfccede2cf8c46e269305a2edfdee88b4d0ffd379c6cb060facdd0e38a706fbb43d7e4952fd098619123c4e - -test: - secret_key_base: f4ed9c83170aefb18eff463702d2712477570944542800ea2336a6dad47a4fad5a17a699971e3304b87c751178473c8506c4722455dcf49a97c70eb04990b209 - -# Do not keep production secrets in the unencrypted secrets file. -# Instead, either read values from the environment. -# Or, use `bin/rails secrets:setup` to configure encrypted secrets -# and move the `production:` environment over there. - -production: - secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> diff --git a/spec/tester_mongo/config/spring.rb b/spec/tester_mongo/config/spring.rb deleted file mode 100644 index c5933e49..00000000 --- a/spec/tester_mongo/config/spring.rb +++ /dev/null @@ -1,8 +0,0 @@ -# frozen_string_literal: true - -%w[ - .ruby-version - .rbenv-vars - tmp/restart.txt - tmp/caching-dev.txt -].each { |path| Spring.watch(path) } diff --git a/spec/tester_mongo/config/storage.yml b/spec/tester_mongo/config/storage.yml new file mode 100644 index 00000000..4942ab66 --- /dev/null +++ b/spec/tester_mongo/config/storage.yml @@ -0,0 +1,34 @@ +test: + service: Disk + root: <%= Rails.root.join("tmp/storage") %> + +local: + service: Disk + root: <%= Rails.root.join("storage") %> + +# Use bin/rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key) +# amazon: +# service: S3 +# access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %> +# secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %> +# region: us-east-1 +# bucket: your_own_bucket-<%= Rails.env %> + +# Remember not to checkin your GCS keyfile to a repository +# google: +# service: GCS +# project: your_project +# credentials: <%= Rails.root.join("path/to/gcs.keyfile") %> +# bucket: your_own_bucket-<%= Rails.env %> + +# Use bin/rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key) +# microsoft: +# service: AzureStorage +# storage_account_name: your_account_name +# storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %> +# container: your_container_name-<%= Rails.env %> + +# mirror: +# service: Mirror +# primary: local +# mirrors: [ amazon, google, microsoft ] diff --git a/spec/tester_mongo/db/schema.rb b/spec/tester_mongo/db/schema.rb deleted file mode 100644 index 10bbffbf..00000000 --- a/spec/tester_mongo/db/schema.rb +++ /dev/null @@ -1,16 +0,0 @@ -# frozen_string_literal: true - -# This file is auto-generated from the current state of the database. Instead -# of editing this file, please use the migrations feature of Active Record to -# incrementally modify your database, and then regenerate this schema definition. -# -# Note that this schema.rb definition is the authoritative source for your -# database schema. If you need to create the application database on another -# system, you should be using db:schema:load, not running all the migrations -# from scratch. The latter is a flawed and unsustainable approach (the more migrations -# you'll amass, the slower it'll run and the greater likelihood for issues). -# -# It's strongly recommended that you check this file into your version control system. - -ActiveRecord::Schema.define(version: 0) do -end diff --git a/spec/tester_mongo/db/seeds.rb b/spec/tester_mongo/db/seeds.rb index e69de29b..65333264 100644 --- a/spec/tester_mongo/db/seeds.rb +++ b/spec/tester_mongo/db/seeds.rb @@ -0,0 +1,9 @@ +# frozen_string_literal: true + +# This file should contain all the record creation needed to seed the database with its default values. +# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup). +# +# Examples: +# +# movies = Movie.create([{ name: "Star Wars" }, { name: "Lord of the Rings" }]) +# Character.create(name: "Luke", movie: movies.first) diff --git a/spec/tester_mongo/public/apple-touch-icon-precomposed.png b/spec/tester_mongo/log/.keep similarity index 100% rename from spec/tester_mongo/public/apple-touch-icon-precomposed.png rename to spec/tester_mongo/log/.keep diff --git a/spec/tester_mongo/package.json b/spec/tester_mongo/package.json deleted file mode 100644 index c52b0a3c..00000000 --- a/spec/tester_mongo/package.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "name": "tester_mongo", - "private": true, - "dependencies": {} -} diff --git a/spec/tester_mongo/public/404.html b/spec/tester_mongo/public/404.html deleted file mode 100644 index 2be3af26..00000000 --- a/spec/tester_mongo/public/404.html +++ /dev/null @@ -1,67 +0,0 @@ - - -
-You may have mistyped the address or the page may have moved.
-If you are the application owner check the logs for more information.
-Maybe you tried to change something you didn't have access to.
-If you are the application owner check the logs for more information.
-If you are the application owner check the logs for more information.
-