Graphql-ruby setup
From wikinotes
Documentation
execution docs https://graphql-ruby.org/queries/executing_queries.html
Sample API
${PROJECT}/lib/graphql_intro.rb
require_relative 'graphql_intro/schema'
${PROJECT}/lib/graphql_intro/schema.rb
# ${PROJECT}/lib/schema.rb require 'graphql' require_relative 'query_root' require_relative 'mutation_root' class Schema < GraphQL::Schema query QueryRoot mutation MutationRoot end
${PROJECT}/lib/graphql_intro/query_root.rb
require 'graphql' class QueryRoot < GraphQL::Schema::Object field :hello, String, "Says hello", null: false def hello return "Hi there" end end
${PROJECT}/lib/graphql_intro/mutation_root.rb
require 'graphql' require_relative 'mutations/write_file' class MutationRoot < GraphQL::Schema::Object field :write_file, mutation: Mutations::WriteFile end
${PROJECT}/lib/graphql_intro/mutations/write_file.rb
require 'graphql' require 'digest' module Mutations class WriteFile < GraphQL::Schema::Mutation argument :path, String, required: true argument :contents, String, required: true field :checksum, String, null: false field :existed_before_write, Boolean, null: false def resolve(path:, contents:) abspath = File.expand_path(path) existed_before_write = File.exist?(abspath) write_file(abspath, contents) { checksum: file_checksum(abspath), existed_before_write: existed_before_write, } end private def write_file(path, contents) dirpath = File.dirname(path) Dir.mkdir(dirpath) unless Dir.exist?(dirpath) File.open(path, "w") do |fd| fd.write(contents) end end def file_checksum(path) File.open(path, "r") do |fd| Digest::MD5.hexdigest(fd.read) end end end end
nix project
Include these files in addition to the above sample project to build a contained nix environment.
${PROJECT}/default.nix
# ${package}/default.nix # # first run: # nix-shell -p bundler --run 'bundle lock' # nix-shell -p bundix --run 'bundix -m' # nix-shell # bundle install # bundle exec irb # require 'graphql' { pkgs ? import <nixpkgs> {} }: pkgs.stdenv.mkDerivation { pname = "ruby-graphql-intro"; version = "0.0.1"; env = pkgs.bundlerEnv { name = "ruby-graphql-intro"; ruby = pkgs.ruby; gemdir = ./.; }; buildInputs = [ pkgs.ruby pkgs.bundler ]; }
${PROJECT}/Gemfile
source 'https://rubygems.org' gem 'graphql' gem 'pry'
${PROJECT}/Makefile
build: clean nix-shell -p bundler --run 'bundle lock' nix-shell -p bundix --run 'bundix -m' nix-shell -p bundler --run 'bundle install' echo "use_nix" > .envrc echo 'PATH=$$PATH:$$PWD/bin' >> .envrc clean: test -d vendor && rm -rf vendor || true test -d .bundle && rm -rf .bundle || true test -f gemset.nix && rm gemset.nix || true test -f Gemfile.lock && rm Gemfile.lock || true test -f .envrc && rm .envrc || true
nix-env -i direnv make direnv allow bundle exec pryrequire_relative 'lib/graphql_schema' Schema.execute("query { hello }")