├── .gitignore ├── .rubocop.yml ├── .ruby-version ├── Gemfile ├── Gemfile.lock ├── LICENSE.txt ├── README.md ├── Rakefile ├── app ├── assets │ └── config │ │ └── manifest.js ├── controllers │ ├── application_controller.rb │ └── graphql_controller.rb ├── graphql │ ├── graphql_tutorial_schema.rb │ ├── mutations │ │ ├── .keep │ │ ├── base_mutation.rb │ │ ├── create_link.rb │ │ ├── create_user.rb │ │ ├── create_vote.rb │ │ └── sign_in_user.rb │ ├── resolvers │ │ ├── base.rb │ │ └── links_search.rb │ └── types │ │ ├── .keep │ │ ├── auth_provider_credentials_input.rb │ │ ├── base_enum.rb │ │ ├── base_input_object.rb │ │ ├── base_interface.rb │ │ ├── base_node.rb │ │ ├── base_object.rb │ │ ├── base_scalar.rb │ │ ├── base_union.rb │ │ ├── date_time_type.rb │ │ ├── link_type.rb │ │ ├── mutation_type.rb │ │ ├── query_meta_type.rb │ │ ├── query_type.rb │ │ ├── user_type.rb │ │ └── vote_type.rb └── models │ ├── auth_token.rb │ ├── link.rb │ ├── user.rb │ └── vote.rb ├── bin ├── bundle ├── rails ├── rake ├── setup ├── update └── yarn ├── config.ru ├── config ├── application.rb ├── boot.rb ├── cable.yml ├── database.yml ├── environment.rb ├── environments │ ├── development.rb │ ├── production.rb │ └── test.rb ├── initializers │ ├── assets.rb │ ├── cookies_serializer.rb │ ├── filter_parameter_logging.rb │ └── wrap_parameters.rb ├── puma.rb ├── routes.rb ├── secrets.yml ├── spring.rb └── storage.yml ├── db ├── migrate │ └── 20170621145055_create_users_links_and_votes.rb ├── schema.rb └── seeds.rb ├── lib └── tasks │ ├── .keep │ └── graphql.rake ├── log └── .keep ├── package.json ├── public ├── 404.html ├── 422.html ├── 500.html ├── apple-touch-icon-precomposed.png ├── apple-touch-icon.png ├── favicon.ico └── robots.txt ├── test ├── factories │ ├── links.rb │ ├── users.rb │ └── votes.rb ├── graphql │ ├── mutations │ │ ├── create_link_test.rb │ │ ├── create_user_test.rb │ │ ├── create_vote_test.rb │ │ └── sign_in_user_test.rb │ └── resolvers │ │ └── links_search_test.rb └── test_helper.rb └── vendor └── .keep /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files for more about ignoring files. 2 | # 3 | # If you find yourself ignoring temporary files generated by your text editor 4 | # or operating system, you probably want to add a global ignore instead: 5 | # git config --global core.excludesfile '~/.gitignore_global' 6 | 7 | # Ignore bundler config. 8 | /.bundle 9 | 10 | # Ignore the default SQLite database. 11 | /db/*.sqlite3 12 | /db/*.sqlite3-journal 13 | 14 | # Ignore all logfiles and tempfiles. 15 | /log/* 16 | /tmp/* 17 | !/log/.keep 18 | !/tmp/.keep 19 | 20 | /node_modules 21 | /yarn-error.log 22 | 23 | .byebug_history 24 | -------------------------------------------------------------------------------- /.rubocop.yml: -------------------------------------------------------------------------------- 1 | AllCops: 2 | Exclude: 3 | - bin/**/* 4 | - db/**/* 5 | 6 | # Disables "Line is too long" 7 | LineLength: 8 | Enabled: false 9 | 10 | # Disables "Module has too many lines" 11 | ModuleLength: 12 | Enabled: false 13 | 14 | # Disables "Method has too many lines." 15 | MethodLength: 16 | Enabled: false 17 | 18 | # Disables "Block has too many lines." 19 | Metrics/BlockLength: 20 | Enabled: false 21 | 22 | # Disables "Missing frozen string literal comment." 23 | Style/FrozenStringLiteralComment: 24 | Enabled: false 25 | 26 | # Disables "%w-literals should be delimited by [ and ]" 27 | Style/PercentLiteralDelimiters: 28 | Enabled: false 29 | 30 | # Disables "Use nested module/class definitions instead of compact style." 31 | Style/ClassAndModuleChildren: 32 | Enabled: false 33 | 34 | # Disables "Missing top-level class documentation comment." 35 | Style/Documentation: 36 | Enabled: false 37 | -------------------------------------------------------------------------------- /.ruby-version: -------------------------------------------------------------------------------- 1 | 2.6.5 2 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | git_source(:github) do |repo_name| 4 | repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include? '/' 5 | "https://github.com/#{repo_name}.git" 6 | end 7 | 8 | ruby '2.6.5' 9 | 10 | gem 'bcrypt' 11 | gem 'bootsnap', require: false 12 | gem 'puma', '~> 3.12' 13 | gem 'rack-cors', require: 'rack/cors' 14 | gem 'rails', '~> 6.0.2.1' 15 | gem 'sqlite3' 16 | gem 'validate_url' 17 | 18 | gem 'graphql' 19 | gem 'graphql-query-resolver' 20 | gem 'search_object' 21 | gem 'search_object_graphql' 22 | 23 | group :development, :test do 24 | gem 'byebug', platforms: %i(mri mingw x64_mingw) 25 | gem 'factory_bot_rails' 26 | gem 'graphiql-rails', '1.5.0' 27 | gem 'rubocop' 28 | end 29 | 30 | group :development do 31 | gem 'listen', '>= 3.0.5', '< 3.2' 32 | gem 'spring' 33 | gem 'spring-watcher-listen', '~> 2.0.0' 34 | gem 'web-console', '>= 3.3.0' 35 | end 36 | -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | actioncable (6.0.2.1) 5 | actionpack (= 6.0.2.1) 6 | nio4r (~> 2.0) 7 | websocket-driver (>= 0.6.1) 8 | actionmailbox (6.0.2.1) 9 | actionpack (= 6.0.2.1) 10 | activejob (= 6.0.2.1) 11 | activerecord (= 6.0.2.1) 12 | activestorage (= 6.0.2.1) 13 | activesupport (= 6.0.2.1) 14 | mail (>= 2.7.1) 15 | actionmailer (6.0.2.1) 16 | actionpack (= 6.0.2.1) 17 | actionview (= 6.0.2.1) 18 | activejob (= 6.0.2.1) 19 | mail (~> 2.5, >= 2.5.4) 20 | rails-dom-testing (~> 2.0) 21 | actionpack (6.0.2.1) 22 | actionview (= 6.0.2.1) 23 | activesupport (= 6.0.2.1) 24 | rack (~> 2.0, >= 2.0.8) 25 | rack-test (>= 0.6.3) 26 | rails-dom-testing (~> 2.0) 27 | rails-html-sanitizer (~> 1.0, >= 1.2.0) 28 | actiontext (6.0.2.1) 29 | actionpack (= 6.0.2.1) 30 | activerecord (= 6.0.2.1) 31 | activestorage (= 6.0.2.1) 32 | activesupport (= 6.0.2.1) 33 | nokogiri (>= 1.8.5) 34 | actionview (6.0.2.1) 35 | activesupport (= 6.0.2.1) 36 | builder (~> 3.1) 37 | erubi (~> 1.4) 38 | rails-dom-testing (~> 2.0) 39 | rails-html-sanitizer (~> 1.1, >= 1.2.0) 40 | activejob (6.0.2.1) 41 | activesupport (= 6.0.2.1) 42 | globalid (>= 0.3.6) 43 | activemodel (6.0.2.1) 44 | activesupport (= 6.0.2.1) 45 | activerecord (6.0.2.1) 46 | activemodel (= 6.0.2.1) 47 | activesupport (= 6.0.2.1) 48 | activestorage (6.0.2.1) 49 | actionpack (= 6.0.2.1) 50 | activejob (= 6.0.2.1) 51 | activerecord (= 6.0.2.1) 52 | marcel (~> 0.3.1) 53 | activesupport (6.0.2.1) 54 | concurrent-ruby (~> 1.0, >= 1.0.2) 55 | i18n (>= 0.7, < 2) 56 | minitest (~> 5.1) 57 | tzinfo (~> 1.1) 58 | zeitwerk (~> 2.2) 59 | ast (2.4.0) 60 | bcrypt (3.1.13) 61 | bindex (0.8.1) 62 | bootsnap (1.4.5) 63 | msgpack (~> 1.0) 64 | builder (3.2.4) 65 | byebug (11.1.0) 66 | concurrent-ruby (1.1.5) 67 | crass (1.0.6) 68 | erubi (1.9.0) 69 | factory_bot (5.1.1) 70 | activesupport (>= 4.2.0) 71 | factory_bot_rails (5.1.1) 72 | factory_bot (~> 5.1.0) 73 | railties (>= 4.2.0) 74 | ffi (1.12.1) 75 | globalid (0.4.2) 76 | activesupport (>= 4.2.0) 77 | graphiql-rails (1.5.0) 78 | railties 79 | sprockets-rails 80 | graphql (1.10.0) 81 | graphql-query-resolver (0.2.0) 82 | graphql (~> 1.0, >= 1.0.0) 83 | i18n (1.8.2) 84 | concurrent-ruby (~> 1.0) 85 | jaro_winkler (1.5.4) 86 | listen (3.1.5) 87 | rb-fsevent (~> 0.9, >= 0.9.4) 88 | rb-inotify (~> 0.9, >= 0.9.7) 89 | ruby_dep (~> 1.2) 90 | loofah (2.4.0) 91 | crass (~> 1.0.2) 92 | nokogiri (>= 1.5.9) 93 | mail (2.7.1) 94 | mini_mime (>= 0.1.1) 95 | marcel (0.3.3) 96 | mimemagic (~> 0.3.2) 97 | method_source (0.9.2) 98 | mimemagic (0.3.10) 99 | nokogiri (~> 1) 100 | rake 101 | mini_mime (1.0.2) 102 | mini_portile2 (2.4.0) 103 | minitest (5.14.0) 104 | msgpack (1.3.1) 105 | nio4r (2.5.2) 106 | nokogiri (1.10.8) 107 | mini_portile2 (~> 2.4.0) 108 | parallel (1.19.1) 109 | parser (2.7.0.2) 110 | ast (~> 2.4.0) 111 | public_suffix (4.0.3) 112 | puma (3.12.6) 113 | rack (2.2.3) 114 | rack-cors (1.1.1) 115 | rack (>= 2.0.0) 116 | rack-test (1.1.0) 117 | rack (>= 1.0, < 3) 118 | rails (6.0.2.1) 119 | actioncable (= 6.0.2.1) 120 | actionmailbox (= 6.0.2.1) 121 | actionmailer (= 6.0.2.1) 122 | actionpack (= 6.0.2.1) 123 | actiontext (= 6.0.2.1) 124 | actionview (= 6.0.2.1) 125 | activejob (= 6.0.2.1) 126 | activemodel (= 6.0.2.1) 127 | activerecord (= 6.0.2.1) 128 | activestorage (= 6.0.2.1) 129 | activesupport (= 6.0.2.1) 130 | bundler (>= 1.3.0) 131 | railties (= 6.0.2.1) 132 | sprockets-rails (>= 2.0.0) 133 | rails-dom-testing (2.0.3) 134 | activesupport (>= 4.2.0) 135 | nokogiri (>= 1.6) 136 | rails-html-sanitizer (1.3.0) 137 | loofah (~> 2.3) 138 | railties (6.0.2.1) 139 | actionpack (= 6.0.2.1) 140 | activesupport (= 6.0.2.1) 141 | method_source 142 | rake (>= 0.8.7) 143 | thor (>= 0.20.3, < 2.0) 144 | rainbow (3.0.0) 145 | rake (13.0.1) 146 | rb-fsevent (0.10.3) 147 | rb-inotify (0.10.1) 148 | ffi (~> 1.0) 149 | rubocop (0.79.0) 150 | jaro_winkler (~> 1.5.1) 151 | parallel (~> 1.10) 152 | parser (>= 2.7.0.1) 153 | rainbow (>= 2.2.2, < 4.0) 154 | ruby-progressbar (~> 1.7) 155 | unicode-display_width (>= 1.4.0, < 1.7) 156 | ruby-progressbar (1.10.1) 157 | ruby_dep (1.5.0) 158 | search_object (1.2.3) 159 | search_object_graphql (0.3.1) 160 | graphql (~> 1.8) 161 | search_object (~> 1.2.2) 162 | spring (2.1.0) 163 | spring-watcher-listen (2.0.1) 164 | listen (>= 2.7, < 4.0) 165 | spring (>= 1.2, < 3.0) 166 | sprockets (4.0.0) 167 | concurrent-ruby (~> 1.0) 168 | rack (> 1, < 3) 169 | sprockets-rails (3.2.1) 170 | actionpack (>= 4.0) 171 | activesupport (>= 4.0) 172 | sprockets (>= 3.0.0) 173 | sqlite3 (1.4.2) 174 | thor (1.0.1) 175 | thread_safe (0.3.6) 176 | tzinfo (1.2.6) 177 | thread_safe (~> 0.1) 178 | unicode-display_width (1.6.1) 179 | validate_url (1.0.8) 180 | activemodel (>= 3.0.0) 181 | public_suffix 182 | web-console (4.0.1) 183 | actionview (>= 6.0.0) 184 | activemodel (>= 6.0.0) 185 | bindex (>= 0.4.0) 186 | railties (>= 6.0.0) 187 | websocket-driver (0.7.1) 188 | websocket-extensions (>= 0.1.0) 189 | websocket-extensions (0.1.5) 190 | zeitwerk (2.2.2) 191 | 192 | PLATFORMS 193 | ruby 194 | 195 | DEPENDENCIES 196 | bcrypt 197 | bootsnap 198 | byebug 199 | factory_bot_rails 200 | graphiql-rails (= 1.5.0) 201 | graphql 202 | graphql-query-resolver 203 | listen (>= 3.0.5, < 3.2) 204 | puma (~> 3.12) 205 | rack-cors 206 | rails (~> 6.0.2.1) 207 | rubocop 208 | search_object 209 | search_object_graphql 210 | spring 211 | spring-watcher-listen (~> 2.0.0) 212 | sqlite3 213 | validate_url 214 | web-console (>= 3.3.0) 215 | 216 | RUBY VERSION 217 | ruby 2.6.5p114 218 | 219 | BUNDLED WITH 220 | 1.17.2 221 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) [2017] [Graphcool] 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # graphql-ruby 2 | 3 | ## Installation 4 | 5 | Install dependencies: 6 | 7 | ``` 8 | bundle install 9 | 10 | rails db:setup 11 | ``` 12 | 13 | Starting the server: 14 | 15 | ``` 16 | rails server 17 | ``` 18 | 19 | Opening the application: 20 | 21 | ``` 22 | open http://localhost:3000/ 23 | ``` 24 | 25 | ## Interesting Files: 26 | 27 | - [GraphqlController](https://github.com/howtographql/graphql-ruby/blob/master/app/controllers/graphql_controller.rb) - GraphQL controller (api entry point) 28 | - [GraphqlTutorialSchema](https://github.com/howtographql/graphql-ruby/blob/master/app/graphql/graphql_tutorial_schema.rb) - the schema definition 29 | - [Mutations](https://github.com/howtographql/graphql-ruby/blob/master/app/graphql/types/mutation_type.rb) - root mutations 30 | - [Queries](https://github.com/howtographql/graphql-ruby/blob/master/app/graphql/types/query_type.rb) - root queries 31 | - [UserType](https://github.com/howtographql/graphql-ruby/blob/master/app/graphql/types/user_type.rb) - record type 32 | - [VoteType](https://github.com/howtographql/graphql-ruby/blob/master/app/graphql/types/vote_type.rb) - record type 33 | - [LinkType](https://github.com/howtographql/graphql-ruby/blob/master/app/graphql/types/link_type.rb) - record type 34 | - [DateTimeType](https://github.com/howtographql/graphql-ruby/blob/master/app/graphql/types/date_time_type.rb) - scalar type 35 | - [LinksSearch](https://github.com/howtographql/graphql-ruby/blob/master/app/graphql/resolvers/links_search.rb) - complex search resolver and its [tests](https://github.com/howtographql/graphql-ruby/blob/master/test/graphql/resolvers/links_search_test.rb) 36 | - [CreateLink](https://github.com/howtographql/graphql-ruby/blob/master/app/graphql/mutations/create_link.rb) - mutation and its [tests](https://github.com/howtographql/graphql-ruby/blob/master/test/graphql/mutations/create_link_test.rb) 37 | - [CreateUser](https://github.com/howtographql/graphql-ruby/blob/master/app/graphql/mutations/create_user.rb) - mutation and its [tests](https://github.com/howtographql/graphql-ruby/blob/master/test/graphql/mutations/create_user_test.rb) 38 | - [CreateVote](https://github.com/howtographql/graphql-ruby/blob/master/app/graphql/mutations/create_vote.rb) - mutation and its [tests](https://github.com/howtographql/graphql-ruby/blob/master/test/graphql/mutations/create_vote_test.rb) 39 | - [SignInUser](https://github.com/howtographql/graphql-ruby/blob/master/app/graphql/mutations/sign_in_user.rb) - mutation and its [tests](https://github.com/howtographql/graphql-ruby/blob/master/test/graphql/mutations/sign_in_user_test.rb) 40 | 41 | ## Sample GraphQL Queries 42 | 43 | List first 10 links, containing "example": 44 | 45 | ```graphql 46 | { 47 | allLinks(first: 10, filter: {descriptionContains: "example"}) { 48 | id 49 | url 50 | description 51 | createdAt 52 | postedBy { 53 | id 54 | name 55 | } 56 | } 57 | } 58 | 59 | ``` 60 | 61 | Creates new user: 62 | 63 | ```graphql 64 | mutation { 65 | createUser( 66 | name: "Radoslav Stankov", 67 | authProvider: { 68 | credentials: { email: "rado@example.com", password: "123456" } 69 | } 70 | ) { 71 | id 72 | email 73 | name 74 | } 75 | } 76 | ``` 77 | 78 | Creates new user token: 79 | 80 | ```graphql 81 | mutation { 82 | signinUser(credentials: {email: "rado@example.com", password: "123456"}) { 83 | token 84 | user { 85 | id 86 | email 87 | name 88 | } 89 | } 90 | } 91 | ``` 92 | 93 | Creates new link: 94 | 95 | ```graphql 96 | mutation { 97 | createLink(url:"http://example.com", description:"Example") { 98 | id 99 | url 100 | description 101 | postedBy { 102 | id 103 | name 104 | } 105 | } 106 | } 107 | ``` 108 | 109 | Creates new vote: 110 | 111 | ```graphql 112 | mutation { 113 | createVote(linkId:"TGluay0yMQ==") { 114 | user { 115 | id 116 | name 117 | } 118 | link { 119 | id 120 | url 121 | description 122 | } 123 | } 124 | } 125 | ``` 126 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | # Add your own tasks in files placed in lib/tasks ending in .rake, 2 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. 3 | 4 | require_relative 'config/application' 5 | 6 | Rails.application.load_tasks 7 | -------------------------------------------------------------------------------- /app/assets/config/manifest.js: -------------------------------------------------------------------------------- 1 | //= link graphiql/rails/application.css 2 | //= link graphiql/rails/application.js 3 | -------------------------------------------------------------------------------- /app/controllers/application_controller.rb: -------------------------------------------------------------------------------- 1 | class ApplicationController < ActionController::Base 2 | # NOTE(rstankov): Disable for purposes of this showcase 3 | # protect_from_forgery with: :exception 4 | end 5 | -------------------------------------------------------------------------------- /app/controllers/graphql_controller.rb: -------------------------------------------------------------------------------- 1 | class GraphqlController < ApplicationController 2 | def execute 3 | result = GraphqlTutorialSchema.execute(query, variables: variables, context: context, operation_name: operation_name) 4 | render json: result 5 | rescue StandardError => e 6 | raise e unless Rails.env.development? 7 | 8 | handle_error_in_development e 9 | end 10 | 11 | private 12 | 13 | def query 14 | params[:query] 15 | end 16 | 17 | def variables 18 | ensure_hash params[:variables] 19 | end 20 | 21 | def operation_name 22 | params[:operationName] 23 | end 24 | 25 | def context 26 | { 27 | session: session, 28 | current_user: AuthToken.user_from_token(session[:token]) 29 | } 30 | end 31 | 32 | def ensure_hash(ambiguous_param) 33 | case ambiguous_param 34 | when String 35 | if ambiguous_param.present? 36 | ensure_hash(JSON.parse(ambiguous_param)) 37 | else 38 | {} 39 | end 40 | when Hash, ActionController::Parameters 41 | ambiguous_param 42 | when nil 43 | {} 44 | else 45 | raise ArgumentError, "Unexpected parameter: #{ambiguous_param}" 46 | end 47 | end 48 | 49 | def handle_error_in_development(error) 50 | logger.error error.message 51 | logger.error error.backtrace.join("\n") 52 | 53 | render json: { error: { message: error.message, backtrace: error.backtrace }, data: {} }, status: 500 54 | end 55 | end 56 | -------------------------------------------------------------------------------- /app/graphql/graphql_tutorial_schema.rb: -------------------------------------------------------------------------------- 1 | class GraphqlTutorialSchema < GraphQL::Schema 2 | query Types::QueryType 3 | mutation Types::MutationType 4 | 5 | def self.resolve_type(_type, object, _ctx) 6 | type_class = "::Types::#{object.class}Type".safe_constantize 7 | 8 | raise ArgumentError, "Cannot resolve type for class #{object.class.name}" unless type_class.present? 9 | 10 | type_class 11 | end 12 | 13 | def self.object_from_id(node_id, _ctx) 14 | return unless node_id.present? 15 | 16 | record_class_name, record_id = GraphQL::Schema::UniqueWithinType.decode(node_id) 17 | record_class = record_class_name.safe_constantize 18 | record_class&.find_by id: record_id 19 | end 20 | 21 | def self.id_from_object(object, _type, _ctx) 22 | GraphQL::Schema::UniqueWithinType.encode(object.class.name, object.id) 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /app/graphql/mutations/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/howtographql/graphql-ruby/be6f4e1e7bf0fd055f28324090dc11251befae65/app/graphql/mutations/.keep -------------------------------------------------------------------------------- /app/graphql/mutations/base_mutation.rb: -------------------------------------------------------------------------------- 1 | module Mutations 2 | class BaseMutation < GraphQL::Schema::Mutation 3 | null false 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /app/graphql/mutations/create_link.rb: -------------------------------------------------------------------------------- 1 | module Mutations 2 | class CreateLink < BaseMutation 3 | argument :description, String, required: true 4 | argument :url, String, required: true 5 | 6 | type Types::LinkType 7 | 8 | def resolve(description: nil, url: nil) 9 | Link.create!( 10 | description: description, 11 | url: url, 12 | user: context[:current_user] 13 | ) 14 | rescue ActiveRecord::RecordInvalid => e 15 | GraphQL::ExecutionError.new("Invalid input: #{e.record.errors.full_messages.join(', ')}") 16 | end 17 | end 18 | end 19 | -------------------------------------------------------------------------------- /app/graphql/mutations/create_user.rb: -------------------------------------------------------------------------------- 1 | module Mutations 2 | class CreateUser < BaseMutation 3 | class AuthProviderSignupData < Types::BaseInputObject 4 | argument :credentials, Types::AuthProviderCredentialsInput, required: false 5 | end 6 | 7 | argument :name, String, required: true 8 | argument :auth_provider, AuthProviderSignupData, required: false 9 | 10 | type Types::UserType 11 | 12 | def resolve(name: nil, auth_provider: nil) 13 | User.create!( 14 | name: name, 15 | email: auth_provider&.[](:credentials)&.[](:email), 16 | password: auth_provider&.[](:credentials)&.[](:password) 17 | ) 18 | rescue ActiveRecord::RecordInvalid => e 19 | GraphQL::ExecutionError.new("Invalid input: #{e.record.errors.full_messages.join(', ')}") 20 | end 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /app/graphql/mutations/create_vote.rb: -------------------------------------------------------------------------------- 1 | module Mutations 2 | class CreateVote < BaseMutation 3 | argument :link_id, ID, required: false 4 | 5 | type Types::VoteType 6 | 7 | def resolve(link_id: nil) 8 | Vote.create!( 9 | link: GraphqlTutorialSchema.object_from_id(link_id, context), 10 | user: context[:current_user] 11 | ) 12 | rescue ActiveRecord::RecordInvalid => e 13 | GraphQL::ExecutionError.new("Invalid input: #{e.record.errors.full_messages.join(', ')}") 14 | end 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /app/graphql/mutations/sign_in_user.rb: -------------------------------------------------------------------------------- 1 | module Mutations 2 | class SignInUser < BaseMutation 3 | null true 4 | 5 | argument :credentials, Types::AuthProviderCredentialsInput, required: false 6 | 7 | field :token, String, null: true 8 | field :user, Types::UserType, null: true 9 | 10 | def resolve(credentials: nil) 11 | return unless credentials 12 | 13 | user = User.find_by email: credentials[:email] 14 | 15 | return unless user 16 | return unless user.authenticate(credentials[:password]) 17 | 18 | token = AuthToken.token_for_user(user) 19 | 20 | context[:session][:token] = token 21 | 22 | { user: user, token: token } 23 | end 24 | end 25 | end 26 | -------------------------------------------------------------------------------- /app/graphql/resolvers/base.rb: -------------------------------------------------------------------------------- 1 | module Resolvers 2 | class Base < GraphQL::Schema::Resolver 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /app/graphql/resolvers/links_search.rb: -------------------------------------------------------------------------------- 1 | require 'search_object/plugin/graphql' 2 | require 'graphql/query_resolver' 3 | 4 | class Resolvers::LinksSearch < GraphQL::Schema::Resolver 5 | include SearchObject.module(:graphql) 6 | 7 | scope { Link.all } 8 | 9 | type [Types::LinkType] 10 | 11 | class LinkFilter < ::Types::BaseInputObject 12 | argument :OR, [self], required: false 13 | argument :description_contains, String, required: false 14 | argument :url_contains, String, required: false 15 | end 16 | 17 | class LinkOrderBy < ::Types::BaseEnum 18 | value 'createdAt_ASC' 19 | value 'createdAt_DESC' 20 | end 21 | 22 | option :filter, type: LinkFilter, with: :apply_filter 23 | option :first, type: types.Int, with: :apply_first 24 | option :skip, type: types.Int, with: :apply_skip 25 | option :orderBy, type: LinkOrderBy, default: 'createdAt_DESC' 26 | 27 | def apply_filter(scope, value) 28 | branches = normalize_filters(value).reduce { |a, b| a.or(b) } 29 | scope.merge branches 30 | end 31 | 32 | def normalize_filters(value, branches = []) 33 | scope = Link.all 34 | scope = scope.where('description LIKE ?', "%#{value[:description_contains]}%") if value[:description_contains] 35 | scope = scope.where('url LIKE ?', "%#{value[:url_contains]}%") if value[:url_contains] 36 | 37 | branches << scope 38 | 39 | value[:OR].reduce(branches) { |s, v| normalize_filters(v, s) } if value[:OR].present? 40 | 41 | branches 42 | end 43 | 44 | def apply_first(scope, value) 45 | scope.limit(value) 46 | end 47 | 48 | def apply_skip(scope, value) 49 | scope.offset(value) 50 | end 51 | 52 | def apply_order_by_with_created_at_asc(scope) 53 | scope.order('created_at ASC') 54 | end 55 | 56 | def apply_order_by_with_created_at_desc(scope) 57 | scope.order('created_at DESC') 58 | end 59 | 60 | def fetch_results 61 | # NOTE: Don't run QueryResolver during tests 62 | return super unless context.present? 63 | 64 | GraphQL::QueryResolver.run(Link, context, Types::LinkType) do 65 | super 66 | end 67 | end 68 | end 69 | -------------------------------------------------------------------------------- /app/graphql/types/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/howtographql/graphql-ruby/be6f4e1e7bf0fd055f28324090dc11251befae65/app/graphql/types/.keep -------------------------------------------------------------------------------- /app/graphql/types/auth_provider_credentials_input.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class AuthProviderCredentialsInput < BaseInputObject 3 | graphql_name 'AUTH_PROVIDER_CREDENTIALS' 4 | 5 | argument :email, String, required: true 6 | argument :password, String, required: true 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /app/graphql/types/base_enum.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class BaseEnum < GraphQL::Schema::Enum 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /app/graphql/types/base_input_object.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class BaseInputObject < GraphQL::Schema::InputObject 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /app/graphql/types/base_interface.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | module BaseInterface 3 | include GraphQL::Schema::Interface 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /app/graphql/types/base_node.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class BaseNode < BaseObject 3 | implements GraphQL::Relay::Node.interface 4 | 5 | global_id_field :id 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /app/graphql/types/base_object.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class BaseObject < GraphQL::Schema::Object 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /app/graphql/types/base_scalar.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class BaseScalar < GraphQL::Schema::Scalar 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /app/graphql/types/base_union.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class BaseUnion < GraphQL::Schema::Union 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /app/graphql/types/date_time_type.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class DateTimeType < Types::BaseScalar 3 | def self.coerce_input(value, _context) 4 | Time.zone.parse(value) 5 | end 6 | 7 | def self.coerce_result(value, _context) 8 | value.utc.iso8601 9 | end 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /app/graphql/types/link_type.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class LinkType < BaseNode 3 | field :created_at, DateTimeType, null: false 4 | field :url, String, null: false 5 | field :description, String, null: false 6 | field :posted_by, UserType, null: false, method: :user 7 | field :votes, [Types::VoteType], null: false 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /app/graphql/types/mutation_type.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class MutationType < BaseObject 3 | field :create_user, mutation: Mutations::CreateUser 4 | field :create_link, mutation: Mutations::CreateLink 5 | field :create_vote, mutation: Mutations::CreateVote 6 | field :signin_user, mutation: Mutations::SignInUser 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /app/graphql/types/query_meta_type.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class QueryMetaType < BaseObject 3 | graphql_name '_QueryMeta' 4 | 5 | field :count, Int, null: false 6 | 7 | def count 8 | object 9 | end 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /app/graphql/types/query_type.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class QueryType < BaseObject 3 | add_field GraphQL::Types::Relay::NodeField 4 | add_field GraphQL::Types::Relay::NodesField 5 | 6 | field :all_links, resolver: Resolvers::LinksSearch 7 | field :_all_links_meta, QueryMetaType, null: false 8 | 9 | def _all_links_meta 10 | Link.count 11 | end 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /app/graphql/types/user_type.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class UserType < BaseNode 3 | field :created_at, DateTimeType, null: false 4 | field :name, String, null: false 5 | field :email, String, null: false 6 | field :votes, [VoteType], null: false 7 | field :links, [LinkType], null: false 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /app/graphql/types/vote_type.rb: -------------------------------------------------------------------------------- 1 | module Types 2 | class VoteType < BaseNode 3 | field :created_at, DateTimeType, null: false 4 | field :user, UserType, null: false 5 | field :link, LinkType, null: false 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /app/models/auth_token.rb: -------------------------------------------------------------------------------- 1 | module AuthToken 2 | module_function 3 | 4 | PREFIX = 'user-id'.freeze 5 | 6 | def token_for_user(user) 7 | crypt.encrypt_and_sign("#{PREFIX}#{user.id}") 8 | end 9 | 10 | def user_from_token(token) 11 | return if token.blank? 12 | 13 | user_id = crypt.decrypt_and_verify(token).gsub(PREFIX, '').to_i 14 | User.find_by id: user_id 15 | rescue ActiveSupport::MessageVerifier::InvalidSignature 16 | nil 17 | end 18 | 19 | def crypt 20 | ActiveSupport::MessageEncryptor.new( 21 | Rails.application.secrets.secret_key_base.byteslice(0..31) 22 | ) 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /app/models/link.rb: -------------------------------------------------------------------------------- 1 | class Link < ActiveRecord::Base 2 | belongs_to :user, validate: true 3 | 4 | has_many :votes, dependent: :destroy 5 | 6 | validates :url, presence: true, url: true, length: { minimum: 3 } 7 | validates :description, presence: true, length: { minimum: 3 } 8 | end 9 | -------------------------------------------------------------------------------- /app/models/user.rb: -------------------------------------------------------------------------------- 1 | class User < ActiveRecord::Base 2 | has_secure_password 3 | 4 | has_many :links, dependent: :destroy 5 | has_many :votes, dependent: :destroy 6 | 7 | validates :name, presence: true, length: { minimum: 3 } 8 | validates :email, presence: true, uniqueness: true, length: { minimum: 3 } 9 | end 10 | -------------------------------------------------------------------------------- /app/models/vote.rb: -------------------------------------------------------------------------------- 1 | class Vote < ActiveRecord::Base 2 | belongs_to :user, validate: true 3 | belongs_to :link, validate: true 4 | 5 | validates :user_id, uniqueness: { scope: :link_id } 6 | end 7 | -------------------------------------------------------------------------------- /bin/bundle: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) 3 | load Gem.bin_path('bundler', 'bundle') 4 | -------------------------------------------------------------------------------- /bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | APP_PATH = File.expand_path('../config/application', __dir__) 3 | require_relative '../config/boot' 4 | require 'rails/commands' 5 | -------------------------------------------------------------------------------- /bin/rake: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require_relative '../config/boot' 3 | require 'rake' 4 | Rake.application.run 5 | -------------------------------------------------------------------------------- /bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require 'fileutils' 3 | 4 | # path to your application root. 5 | APP_ROOT = File.expand_path('..', __dir__) 6 | 7 | def system!(*args) 8 | system(*args) || abort("\n== Command #{args} failed ==") 9 | end 10 | 11 | FileUtils.chdir APP_ROOT do 12 | # This script is a way to setup or update your development environment automatically. 13 | # This script is idempotent, so that you can run it at anytime and get an expectable outcome. 14 | # Add necessary setup steps to this file. 15 | 16 | puts '== Installing dependencies ==' 17 | system! 'gem install bundler --conservative' 18 | system('bundle check') || system!('bundle install') 19 | 20 | # Install JavaScript dependencies 21 | # system('bin/yarn') 22 | 23 | # puts "\n== Copying sample files ==" 24 | # unless File.exist?('config/database.yml') 25 | # FileUtils.cp 'config/database.yml.sample', 'config/database.yml' 26 | # end 27 | 28 | puts "\n== Preparing database ==" 29 | system! 'bin/rails db:prepare' 30 | 31 | puts "\n== Removing old logs and tempfiles ==" 32 | system! 'bin/rails log:clear tmp:clear' 33 | 34 | puts "\n== Restarting application server ==" 35 | system! 'bin/rails restart' 36 | end 37 | -------------------------------------------------------------------------------- /bin/update: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require 'fileutils' 3 | include FileUtils 4 | 5 | # path to your application root. 6 | APP_ROOT = File.expand_path('..', __dir__) 7 | 8 | def system!(*args) 9 | system(*args) || abort("\n== Command #{args} failed ==") 10 | end 11 | 12 | chdir APP_ROOT do 13 | # This script is a way to update your development environment automatically. 14 | # Add necessary update steps to this file. 15 | 16 | puts '== Installing dependencies ==' 17 | system! 'gem install bundler --conservative' 18 | system('bundle check') || system!('bundle install') 19 | 20 | # Install JavaScript dependencies if using Yarn 21 | # system('bin/yarn') 22 | 23 | puts "\n== Updating database ==" 24 | system! 'bin/rails db:migrate' 25 | 26 | puts "\n== Removing old logs and tempfiles ==" 27 | system! 'bin/rails log:clear tmp:clear' 28 | 29 | puts "\n== Restarting application server ==" 30 | system! 'bin/rails restart' 31 | end 32 | -------------------------------------------------------------------------------- /bin/yarn: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | APP_ROOT = File.expand_path('..', __dir__) 3 | Dir.chdir(APP_ROOT) do 4 | begin 5 | exec "yarnpkg", *ARGV 6 | rescue Errno::ENOENT 7 | $stderr.puts "Yarn executable was not detected in the system." 8 | $stderr.puts "Download Yarn at https://yarnpkg.com/en/docs/install" 9 | exit 1 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /config.ru: -------------------------------------------------------------------------------- 1 | # This file is used by Rack-based servers to start the application. 2 | 3 | require_relative 'config/environment' 4 | 5 | run Rails.application 6 | -------------------------------------------------------------------------------- /config/application.rb: -------------------------------------------------------------------------------- 1 | require_relative 'boot' 2 | 3 | require 'rails/all' 4 | 5 | # Require the gems listed in Gemfile, including any gems 6 | # you've limited to :test, :development, or :production. 7 | Bundler.require(*Rails.groups) 8 | 9 | module GraphqlRuby 10 | class Application < Rails::Application 11 | # Initialize configuration defaults for originally generated Rails version. 12 | config.load_defaults 6.0 13 | 14 | # Settings in config/environments/* take precedence over those specified here. 15 | # Application configuration should go into files in config/initializers 16 | # -- all .rb files in that directory are automatically loaded. 17 | 18 | # see https://github.com/cyu/rack-cors 19 | config.middleware.insert_before 0, Rack::Cors do 20 | allow do 21 | origins '*' 22 | resource '*', headers: :any, methods: %i[get post options] 23 | end 24 | end 25 | end 26 | end 27 | -------------------------------------------------------------------------------- /config/boot.rb: -------------------------------------------------------------------------------- 1 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) 2 | 3 | require 'bundler/setup' # Set up gems listed in the Gemfile. 4 | require 'bootsnap/setup' # Speed up boot time by caching expensive operations. 5 | -------------------------------------------------------------------------------- /config/cable.yml: -------------------------------------------------------------------------------- 1 | development: 2 | adapter: async 3 | 4 | test: 5 | adapter: test 6 | 7 | production: 8 | adapter: redis 9 | url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %> 10 | channel_prefix: graphql_ruby_production 11 | -------------------------------------------------------------------------------- /config/database.yml: -------------------------------------------------------------------------------- 1 | # SQLite version 3.x 2 | # gem install sqlite3 3 | # 4 | # Ensure the SQLite 3 gem is defined in your Gemfile 5 | # gem 'sqlite3' 6 | # 7 | default: &default 8 | adapter: sqlite3 9 | pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> 10 | timeout: 5000 11 | 12 | development: 13 | <<: *default 14 | database: db/development.sqlite3 15 | 16 | # Warning: The database defined as "test" will be erased and 17 | # re-generated from your development database when you run "rake". 18 | # Do not set this db to the same as development or production. 19 | test: 20 | <<: *default 21 | database: db/test.sqlite3 22 | 23 | production: 24 | <<: *default 25 | database: db/production.sqlite3 26 | -------------------------------------------------------------------------------- /config/environment.rb: -------------------------------------------------------------------------------- 1 | # Load the Rails application. 2 | require_relative 'application' 3 | 4 | # Initialize the Rails application. 5 | Rails.application.initialize! 6 | -------------------------------------------------------------------------------- /config/environments/development.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # In the development environment your application's code is reloaded on 5 | # every request. This slows down response time but is perfect for development 6 | # since you don't have to restart the web server when you make code changes. 7 | config.cache_classes = false 8 | 9 | # Do not eager load code on boot. 10 | config.eager_load = false 11 | 12 | # Show full error reports. 13 | config.consider_all_requests_local = true 14 | 15 | # Enable/disable caching. By default caching is disabled. 16 | # Run rails dev:cache to toggle caching. 17 | if Rails.root.join('tmp', 'caching-dev.txt').exist? 18 | config.action_controller.perform_caching = true 19 | config.action_controller.enable_fragment_cache_logging = true 20 | 21 | config.cache_store = :memory_store 22 | config.public_file_server.headers = { 23 | 'Cache-Control' => "public, max-age=#{2.days.to_i}" 24 | } 25 | else 26 | config.action_controller.perform_caching = false 27 | 28 | config.cache_store = :null_store 29 | end 30 | 31 | # Store uploaded files on the local file system (see config/storage.yml for options). 32 | config.active_storage.service = :local 33 | 34 | # Don't care if the mailer can't send. 35 | config.action_mailer.raise_delivery_errors = false 36 | 37 | config.action_mailer.perform_caching = false 38 | 39 | # Print deprecation notices to the Rails logger. 40 | config.active_support.deprecation = :log 41 | 42 | # Raise an error on page load if there are pending migrations. 43 | config.active_record.migration_error = :page_load 44 | 45 | # Highlight code that triggered database queries in logs. 46 | config.active_record.verbose_query_logs = true 47 | 48 | # Debug mode disables concatenation and preprocessing of assets. 49 | # This option may cause significant delays in view rendering with a large 50 | # number of complex assets. 51 | config.assets.debug = true 52 | 53 | # Suppress logger output for asset requests. 54 | config.assets.quiet = true 55 | 56 | # Raises error for missing translations. 57 | # config.action_view.raise_on_missing_translations = true 58 | 59 | # Use an evented file watcher to asynchronously detect changes in source code, 60 | # routes, locales, etc. This feature depends on the listen gem. 61 | config.file_watcher = ActiveSupport::EventedFileUpdateChecker 62 | end 63 | -------------------------------------------------------------------------------- /config/environments/production.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # Code is not reloaded between requests. 5 | config.cache_classes = true 6 | 7 | # Eager load code on boot. This eager loads most of Rails and 8 | # your application in memory, allowing both threaded web servers 9 | # and those relying on copy on write to perform better. 10 | # Rake tasks automatically ignore this option for performance. 11 | config.eager_load = true 12 | 13 | # Full error reports are disabled and caching is turned on. 14 | config.consider_all_requests_local = false 15 | config.action_controller.perform_caching = true 16 | 17 | # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] 18 | # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). 19 | # config.require_master_key = true 20 | 21 | # Disable serving static files from the `/public` folder by default since 22 | # Apache or NGINX already handles this. 23 | config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? 24 | 25 | # Compress CSS using a preprocessor. 26 | # config.assets.css_compressor = :sass 27 | 28 | # Do not fallback to assets pipeline if a precompiled asset is missed. 29 | config.assets.compile = false 30 | 31 | # Enable serving of images, stylesheets, and JavaScripts from an asset server. 32 | # config.action_controller.asset_host = 'http://assets.example.com' 33 | 34 | # Specifies the header that your server uses for sending files. 35 | # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache 36 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX 37 | 38 | # Store uploaded files on the local file system (see config/storage.yml for options). 39 | config.active_storage.service = :local 40 | 41 | # Mount Action Cable outside main process or domain. 42 | # config.action_cable.mount_path = nil 43 | # config.action_cable.url = 'wss://example.com/cable' 44 | # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] 45 | 46 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 47 | # config.force_ssl = true 48 | 49 | # Use the lowest log level to ensure availability of diagnostic information 50 | # when problems arise. 51 | config.log_level = :debug 52 | 53 | # Prepend all log lines with the following tags. 54 | config.log_tags = [:request_id] 55 | 56 | # Use a different cache store in production. 57 | # config.cache_store = :mem_cache_store 58 | 59 | # Use a real queuing backend for Active Job (and separate queues per environment). 60 | # config.active_job.queue_adapter = :resque 61 | # config.active_job.queue_name_prefix = "graphql_ruby_production" 62 | 63 | config.action_mailer.perform_caching = false 64 | 65 | # Ignore bad email addresses and do not raise email delivery errors. 66 | # Set this to true and configure the email server for immediate delivery to raise delivery errors. 67 | # config.action_mailer.raise_delivery_errors = false 68 | 69 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 70 | # the I18n.default_locale when a translation cannot be found). 71 | config.i18n.fallbacks = true 72 | 73 | # Send deprecation notices to registered listeners. 74 | config.active_support.deprecation = :notify 75 | 76 | # Use default logging formatter so that PID and timestamp are not suppressed. 77 | config.log_formatter = ::Logger::Formatter.new 78 | 79 | # Use a different logger for distributed setups. 80 | # require 'syslog/logger' 81 | # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') 82 | 83 | if ENV['RAILS_LOG_TO_STDOUT'].present? 84 | logger = ActiveSupport::Logger.new(STDOUT) 85 | logger.formatter = config.log_formatter 86 | config.logger = ActiveSupport::TaggedLogging.new(logger) 87 | end 88 | 89 | # Do not dump schema after migrations. 90 | config.active_record.dump_schema_after_migration = false 91 | 92 | # Inserts middleware to perform automatic connection switching. 93 | # The `database_selector` hash is used to pass options to the DatabaseSelector 94 | # middleware. The `delay` is used to determine how long to wait after a write 95 | # to send a subsequent read to the primary. 96 | # 97 | # The `database_resolver` class is used by the middleware to determine which 98 | # database is appropriate to use based on the time delay. 99 | # 100 | # The `database_resolver_context` class is used by the middleware to set 101 | # timestamps for the last write to the primary. The resolver uses the context 102 | # class timestamps to determine how long to wait before reading from the 103 | # replica. 104 | # 105 | # By default Rails will store a last write timestamp in the session. The 106 | # DatabaseSelector middleware is designed as such you can define your own 107 | # strategy for connection switching and pass that into the middleware through 108 | # these configuration options. 109 | # config.active_record.database_selector = { delay: 2.seconds } 110 | # config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver 111 | # config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session 112 | end 113 | -------------------------------------------------------------------------------- /config/environments/test.rb: -------------------------------------------------------------------------------- 1 | # The test environment is used exclusively to run your application's 2 | # test suite. You never need to work with it otherwise. Remember that 3 | # your test database is "scratch space" for the test suite and is wiped 4 | # and recreated between test runs. Don't rely on the data there! 5 | 6 | Rails.application.configure do 7 | # Settings specified here will take precedence over those in config/application.rb. 8 | 9 | config.cache_classes = false 10 | 11 | # Do not eager load code on boot. This avoids loading your whole application 12 | # just for the purpose of running a single test. If you are using a tool that 13 | # preloads Rails for running tests, you may have to set it to true. 14 | config.eager_load = false 15 | 16 | # Configure public file server for tests with Cache-Control for performance. 17 | config.public_file_server.enabled = true 18 | config.public_file_server.headers = { 19 | 'Cache-Control' => "public, max-age=#{1.hour.to_i}" 20 | } 21 | 22 | # Show full error reports and disable caching. 23 | config.consider_all_requests_local = true 24 | config.action_controller.perform_caching = false 25 | config.cache_store = :null_store 26 | 27 | # Raise exceptions instead of rendering exception templates. 28 | config.action_dispatch.show_exceptions = false 29 | 30 | # Disable request forgery protection in test environment. 31 | config.action_controller.allow_forgery_protection = false 32 | 33 | # Store uploaded files on the local file system in a temporary directory. 34 | config.active_storage.service = :test 35 | 36 | config.action_mailer.perform_caching = false 37 | 38 | # Tell Action Mailer not to deliver emails to the real world. 39 | # The :test delivery method accumulates sent emails in the 40 | # ActionMailer::Base.deliveries array. 41 | config.action_mailer.delivery_method = :test 42 | 43 | # Print deprecation notices to the stderr. 44 | config.active_support.deprecation = :stderr 45 | 46 | # Raises error for missing translations. 47 | # config.action_view.raise_on_missing_translations = true 48 | end 49 | -------------------------------------------------------------------------------- /config/initializers/assets.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Version of your assets, change this if you want to expire all your assets. 4 | Rails.application.config.assets.version = '1.0' 5 | 6 | # Add additional assets to the asset load path. 7 | # Rails.application.config.assets.paths << Emoji.images_path 8 | # Add Yarn node_modules folder to the asset load path. 9 | Rails.application.config.assets.paths << Rails.root.join('node_modules') 10 | 11 | # Precompile additional assets. 12 | # application.js, application.css, and all non-JS/CSS in the app/assets 13 | # folder are already added. 14 | # Rails.application.config.assets.precompile += %w( admin.js admin.css ) 15 | -------------------------------------------------------------------------------- /config/initializers/cookies_serializer.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Specify a serializer for the signed and encrypted cookie jars. 4 | # Valid options are :json, :marshal, and :hybrid. 5 | Rails.application.config.action_dispatch.cookies_serializer = :json 6 | -------------------------------------------------------------------------------- /config/initializers/filter_parameter_logging.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Configure sensitive parameters which will be filtered from the log file. 4 | Rails.application.config.filter_parameters += [:password] 5 | -------------------------------------------------------------------------------- /config/initializers/wrap_parameters.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # This file contains settings for ActionController::ParamsWrapper which 4 | # is enabled by default. 5 | 6 | # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. 7 | ActiveSupport.on_load(:action_controller) do 8 | wrap_parameters format: [:json] 9 | end 10 | 11 | # To enable root element in JSON for ActiveRecord objects. 12 | # ActiveSupport.on_load(:active_record) do 13 | # self.include_root_in_json = true 14 | # end 15 | -------------------------------------------------------------------------------- /config/puma.rb: -------------------------------------------------------------------------------- 1 | # Puma can serve each request in a thread from an internal thread pool. 2 | # The `threads` method setting takes two numbers: a minimum and maximum. 3 | # Any libraries that use thread pools should be configured to match 4 | # the maximum value specified for Puma. Default is set to 5 threads for minimum 5 | # and maximum; this matches the default thread size of Active Record. 6 | # 7 | max_threads_count = ENV.fetch('RAILS_MAX_THREADS') { 5 } 8 | min_threads_count = ENV.fetch('RAILS_MIN_THREADS') { max_threads_count } 9 | threads min_threads_count, max_threads_count 10 | 11 | # Specifies the `port` that Puma will listen on to receive requests; default is 3000. 12 | # 13 | port ENV.fetch('PORT') { 3000 } 14 | 15 | # Specifies the `environment` that Puma will run in. 16 | # 17 | environment ENV.fetch('RAILS_ENV') { 'development' } 18 | 19 | # Specifies the `pidfile` that Puma will use. 20 | pidfile ENV.fetch('PIDFILE') { 'tmp/pids/server.pid' } 21 | 22 | # Specifies the number of `workers` to boot in clustered mode. 23 | # Workers are forked web server processes. If using threads and workers together 24 | # the concurrency of the application would be max `threads` * `workers`. 25 | # Workers do not work on JRuby or Windows (both of which do not support 26 | # processes). 27 | # 28 | # workers ENV.fetch("WEB_CONCURRENCY") { 2 } 29 | 30 | # Use the `preload_app!` method when specifying a `workers` number. 31 | # This directive tells Puma to first boot the application and load code 32 | # before forking the application. This takes advantage of Copy On Write 33 | # process behavior so workers use less memory. 34 | # 35 | # preload_app! 36 | 37 | # Allow puma to be restarted by `rails restart` command. 38 | plugin :tmp_restart 39 | -------------------------------------------------------------------------------- /config/routes.rb: -------------------------------------------------------------------------------- 1 | Rails.application.routes.draw do 2 | post '/graphql', to: 'graphql#execute' 3 | 4 | if Rails.env.development? 5 | mount GraphiQL::Rails::Engine, at: '/graphiql', graphql_path: '/graphql' 6 | 7 | root to: redirect('/graphiql') 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /config/secrets.yml: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Your secret key is used for verifying the integrity of signed cookies. 4 | # If you change this key, all old signed cookies will become invalid! 5 | 6 | # Make sure the secret is at least 30 characters and all random, 7 | # no regular words or you'll be exposed to dictionary attacks. 8 | # You can use `rails secret` to generate a secure secret key. 9 | 10 | # Make sure the secrets in this file are kept private 11 | # if you're sharing your code publicly. 12 | 13 | # Shared secrets are available across all environments. 14 | 15 | # shared: 16 | # api_key: a1B2c3D4e5F6 17 | 18 | # Environmental secrets are only available for that specific environment. 19 | 20 | development: 21 | secret_key_base: ac39391f50298c3466ac55bb85bfc5ad24dadeca1022ea10bd4b5374b37ef23dc231d78c6a0a7788363c1b8ace1d4416f2ad9d90413b444d7836a609da2825c3 22 | 23 | test: 24 | secret_key_base: 323fbf81da2c3f62d044c8ad9c5713ca3dedd712ca15bb8afc48c5b14a2859e1c857eca4ac7c8aaf7aceef37125229f8381dcabe2eda1f567d99c839f3b53e99 25 | 26 | # Do not keep production secrets in the unencrypted secrets file. 27 | # Instead, either read values from the environment. 28 | # Or, use `bin/rails secrets:setup` to configure encrypted secrets 29 | # and move the `production:` environment over there. 30 | 31 | production: 32 | secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> 33 | -------------------------------------------------------------------------------- /config/spring.rb: -------------------------------------------------------------------------------- 1 | Spring.watch( 2 | '.ruby-version', 3 | '.rbenv-vars', 4 | 'tmp/restart.txt', 5 | 'tmp/caching-dev.txt' 6 | ) 7 | -------------------------------------------------------------------------------- /config/storage.yml: -------------------------------------------------------------------------------- 1 | test: 2 | service: Disk 3 | root: <%= Rails.root.join("tmp/storage") %> 4 | 5 | local: 6 | service: Disk 7 | root: <%= Rails.root.join("storage") %> 8 | 9 | # Use rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key) 10 | # amazon: 11 | # service: S3 12 | # access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %> 13 | # secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %> 14 | # region: us-east-1 15 | # bucket: your_own_bucket 16 | 17 | # Remember not to checkin your GCS keyfile to a repository 18 | # google: 19 | # service: GCS 20 | # project: your_project 21 | # credentials: <%= Rails.root.join("path/to/gcs.keyfile") %> 22 | # bucket: your_own_bucket 23 | 24 | # Use rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key) 25 | # microsoft: 26 | # service: AzureStorage 27 | # storage_account_name: your_account_name 28 | # storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %> 29 | # container: your_container_name 30 | 31 | # mirror: 32 | # service: Mirror 33 | # primary: local 34 | # mirrors: [ amazon, google, microsoft ] 35 | -------------------------------------------------------------------------------- /db/migrate/20170621145055_create_users_links_and_votes.rb: -------------------------------------------------------------------------------- 1 | class CreateUsersLinksAndVotes < ActiveRecord::Migration[5.1] 2 | def change 3 | create_table :users do |t| 4 | t.string :name, null: false 5 | t.string :email, null: false 6 | t.string :password_digest, null: false 7 | t.index :email, unique: true 8 | t.timestamps 9 | end 10 | 11 | create_table :links do |t| 12 | t.references :user, null: false, foreign_key: true 13 | t.string :url, null: false 14 | t.string :description, null: false 15 | t.timestamps 16 | end 17 | 18 | create_table :votes do |t| 19 | t.references :user, null: false, foreign_key: true 20 | t.references :link, null: false, foreign_key: true 21 | t.index %i(user_id link_id), unique: true 22 | t.timestamps 23 | end 24 | end 25 | end 26 | -------------------------------------------------------------------------------- /db/schema.rb: -------------------------------------------------------------------------------- 1 | # This file is auto-generated from the current state of the database. Instead 2 | # of editing this file, please use the migrations feature of Active Record to 3 | # incrementally modify your database, and then regenerate this schema definition. 4 | # 5 | # This file is the source Rails uses to define your schema when running `rails 6 | # db:schema:load`. When creating a new database, `rails db:schema:load` tends to 7 | # be faster and is potentially less error prone than running all of your 8 | # migrations from scratch. Old migrations may fail to apply correctly if those 9 | # migrations use external dependencies or application code. 10 | # 11 | # It's strongly recommended that you check this file into your version control system. 12 | 13 | ActiveRecord::Schema.define(version: 2017_06_21_145055) do 14 | 15 | create_table "links", force: :cascade do |t| 16 | t.integer "user_id", null: false 17 | t.string "url", null: false 18 | t.string "description", null: false 19 | t.datetime "created_at", null: false 20 | t.datetime "updated_at", null: false 21 | t.index ["user_id"], name: "index_links_on_user_id" 22 | end 23 | 24 | create_table "users", force: :cascade do |t| 25 | t.string "name", null: false 26 | t.string "email", null: false 27 | t.string "password_digest", null: false 28 | t.datetime "created_at", null: false 29 | t.datetime "updated_at", null: false 30 | t.index ["email"], name: "index_users_on_email", unique: true 31 | end 32 | 33 | create_table "votes", force: :cascade do |t| 34 | t.integer "user_id", null: false 35 | t.integer "link_id", null: false 36 | t.datetime "created_at", null: false 37 | t.datetime "updated_at", null: false 38 | t.index ["link_id"], name: "index_votes_on_link_id" 39 | t.index ["user_id", "link_id"], name: "index_votes_on_user_id_and_link_id", unique: true 40 | t.index ["user_id"], name: "index_votes_on_user_id" 41 | end 42 | 43 | add_foreign_key "links", "users" 44 | add_foreign_key "votes", "links" 45 | add_foreign_key "votes", "users" 46 | end 47 | -------------------------------------------------------------------------------- /db/seeds.rb: -------------------------------------------------------------------------------- 1 | require 'factory_bot' 2 | 3 | if Vote.count.zero? 4 | 20.times do 5 | FactoryBot.create :vote 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /lib/tasks/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/howtographql/graphql-ruby/be6f4e1e7bf0fd055f28324090dc11251befae65/lib/tasks/.keep -------------------------------------------------------------------------------- /lib/tasks/graphql.rake: -------------------------------------------------------------------------------- 1 | namespace :graphql do 2 | task export: [:environment] do 3 | schema = GraphqlTutorialSchema.execute(GraphQL::Introspection::INTROSPECTION_QUERY, variables: {}, context: {}) 4 | 5 | File.write(Rails.root.join('graphql.json'), JSON.pretty_generate(schema)) 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /log/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/howtographql/graphql-ruby/be6f4e1e7bf0fd055f28324090dc11251befae65/log/.keep -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "graphql-ruby", 3 | "private": true, 4 | "dependencies": {} 5 | } 6 | -------------------------------------------------------------------------------- /public/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The page you were looking for doesn't exist (404) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

The page you were looking for doesn't exist.

62 |

You may have mistyped the address or the page may have moved.

63 |
64 |

If you are the application owner check the logs for more information.

65 |
66 | 67 | 68 | -------------------------------------------------------------------------------- /public/422.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The change you wanted was rejected (422) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

The change you wanted was rejected.

62 |

Maybe you tried to change something you didn't have access to.

63 |
64 |

If you are the application owner check the logs for more information.

65 |
66 | 67 | 68 | -------------------------------------------------------------------------------- /public/500.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | We're sorry, but something went wrong (500) 5 | 6 | 55 | 56 | 57 | 58 | 59 |
60 |
61 |

We're sorry, but something went wrong.

62 |
63 |

If you are the application owner check the logs for more information.

64 |
65 | 66 | 67 | -------------------------------------------------------------------------------- /public/apple-touch-icon-precomposed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/howtographql/graphql-ruby/be6f4e1e7bf0fd055f28324090dc11251befae65/public/apple-touch-icon-precomposed.png -------------------------------------------------------------------------------- /public/apple-touch-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/howtographql/graphql-ruby/be6f4e1e7bf0fd055f28324090dc11251befae65/public/apple-touch-icon.png -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/howtographql/graphql-ruby/be6f4e1e7bf0fd055f28324090dc11251befae65/public/favicon.ico -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file 2 | -------------------------------------------------------------------------------- /test/factories/links.rb: -------------------------------------------------------------------------------- 1 | FactoryBot.define do 2 | factory :link do 3 | user 4 | sequence(:url) { |i| "http://example#{i}.com" } 5 | sequence(:description) { |i| "Link #{i} description" } 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /test/factories/users.rb: -------------------------------------------------------------------------------- 1 | FactoryBot.define do 2 | factory :user do 3 | sequence(:name) { |i| "User #{i}" } 4 | sequence(:email) { |i| "user#{i}@example.com" } 5 | password { '123456' } 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /test/factories/votes.rb: -------------------------------------------------------------------------------- 1 | FactoryBot.define do 2 | factory :vote do 3 | user 4 | link 5 | end 6 | end 7 | -------------------------------------------------------------------------------- /test/graphql/mutations/create_link_test.rb: -------------------------------------------------------------------------------- 1 | require 'test_helper' 2 | 3 | class Mutations::CreateLinkTest < ActiveSupport::TestCase 4 | def perform(user: nil, **args) 5 | Mutations::CreateLink.new(object: nil, field: nil, context: { current_user: user }).resolve(args) 6 | end 7 | 8 | test 'success' do 9 | user = create :user 10 | 11 | link = perform( 12 | url: 'http://example.com', 13 | description: 'description', 14 | user: user 15 | ) 16 | 17 | assert link.persisted? 18 | assert_equal link.description, 'description' 19 | assert_equal link.url, 'http://example.com' 20 | assert_equal link.user, user 21 | end 22 | 23 | test 'failure' do 24 | assert perform.is_a? GraphQL::ExecutionError 25 | end 26 | end 27 | -------------------------------------------------------------------------------- /test/graphql/mutations/create_user_test.rb: -------------------------------------------------------------------------------- 1 | require 'test_helper' 2 | 3 | class Mutations::CreateUserTest < ActiveSupport::TestCase 4 | def perform(args = {}) 5 | Mutations::CreateUser.new(object: nil, field: nil, context: {}).resolve(args) 6 | end 7 | 8 | test 'success' do 9 | user = perform( 10 | name: 'Test User', 11 | auth_provider: { 12 | credentials: { 13 | email: 'email@example.com', 14 | password: '[omitted]' 15 | } 16 | } 17 | ) 18 | 19 | assert user.persisted? 20 | assert_equal user.name, 'Test User' 21 | assert_equal user.email, 'email@example.com' 22 | end 23 | 24 | test 'failure' do 25 | assert perform.is_a? GraphQL::ExecutionError 26 | end 27 | end 28 | -------------------------------------------------------------------------------- /test/graphql/mutations/create_vote_test.rb: -------------------------------------------------------------------------------- 1 | require 'test_helper' 2 | 3 | class Mutations::CreateVoteTest < ActiveSupport::TestCase 4 | def perform(user: nil, **args) 5 | Mutations::CreateVote.new(object: nil, field: nil, context: { current_user: user }).resolve(args) 6 | end 7 | 8 | def record_id(record) 9 | GraphqlTutorialSchema.id_from_object(record, nil, nil) 10 | end 11 | 12 | test 'success' do 13 | user = create :user 14 | link = create :link 15 | 16 | vote = perform( 17 | user: user, 18 | link_id: record_id(link) 19 | ) 20 | 21 | assert vote.persisted? 22 | assert_equal vote.user, user 23 | assert_equal vote.link, link 24 | end 25 | 26 | test 'failure' do 27 | assert perform.is_a? GraphQL::ExecutionError 28 | end 29 | end 30 | -------------------------------------------------------------------------------- /test/graphql/mutations/sign_in_user_test.rb: -------------------------------------------------------------------------------- 1 | require 'test_helper' 2 | 3 | class Mutations::SignInUserTest < ActiveSupport::TestCase 4 | def perform(args = {}) 5 | Mutations::SignInUser.new(object: nil, field: nil, context: { session: {} }).resolve(args) 6 | end 7 | 8 | test 'success' do 9 | user = create :user 10 | 11 | result = perform( 12 | credentials: { 13 | email: user.email, 14 | password: user.password 15 | } 16 | ) 17 | 18 | assert result[:token].present? 19 | assert_equal result[:user], user 20 | end 21 | 22 | test 'failure because no credentials' do 23 | assert_nil perform 24 | end 25 | 26 | test 'failure because wrong email' do 27 | create :user 28 | assert_nil perform(credentials: { email: 'wrong' }) 29 | end 30 | 31 | test 'failure because wrong password' do 32 | user = create :user 33 | assert_nil perform(credentials: { email: user.email, password: 'wrong' }) 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /test/graphql/resolvers/links_search_test.rb: -------------------------------------------------------------------------------- 1 | require 'test_helper' 2 | 3 | class Resolvers::LinksSearchTest < ActiveSupport::TestCase 4 | def find(args) 5 | Resolvers::LinksSearch.call(nil, args, nil) 6 | end 7 | 8 | test 'skip option' do 9 | link = create :link, description: 'old' 10 | create :link, description: 'new' 11 | 12 | assert_equal find(skip: 1), [link] 13 | end 14 | 15 | test 'first option' do 16 | create :link, description: 'old' 17 | link = create :link, description: 'new' 18 | 19 | assert_equal find(first: 1), [link] 20 | end 21 | 22 | test 'filter option' do 23 | link1 = create :link, description: 'test1', url: 'http://test1.com' 24 | link2 = create :link, description: 'test2', url: 'http://test2.com' 25 | link3 = create :link, description: 'test3', url: 'http://test3.com' 26 | create :link, description: 'test4', url: 'http://test4.com' 27 | 28 | result = find( 29 | filter: { 30 | description_contains: 'test1', 31 | OR: [{ 32 | url_contains: 'test2', 33 | OR: [{ 34 | url_contains: 'test3' 35 | }] 36 | }, { 37 | description_contains: 'test2' 38 | }] 39 | } 40 | ) 41 | 42 | assert_equal result.map(&:description).sort, [link1, link2, link3].map(&:description).sort 43 | end 44 | 45 | test 'order by createdAt_ASC' do 46 | new = create :link, created_at: 1.week.ago 47 | old = create :link, created_at: 1.month.ago 48 | 49 | assert_equal find(orderBy: 'createdAt_ASC'), [old, new] 50 | end 51 | 52 | test 'order by createdAt_DESC' do 53 | new = create :link, created_at: 1.week.ago 54 | old = create :link, created_at: 1.month.ago 55 | 56 | assert_equal find(orderBy: 'createdAt_DESC'), [new, old] 57 | end 58 | end 59 | -------------------------------------------------------------------------------- /test/test_helper.rb: -------------------------------------------------------------------------------- 1 | require File.expand_path('../config/environment', __dir__) 2 | require 'rails/test_help' 3 | 4 | class ActiveSupport::TestCase 5 | # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. 6 | fixtures :all 7 | 8 | include FactoryBot::Syntax::Methods 9 | end 10 | -------------------------------------------------------------------------------- /vendor/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/howtographql/graphql-ruby/be6f4e1e7bf0fd055f28324090dc11251befae65/vendor/.keep --------------------------------------------------------------------------------