Sha256: 60d7cd01f8f4c06b2d55174448b53c1246120d0971b4620c7cc659c2d8be7edc
Contents?: true
Size: 1.88 KB
Versions: 1
Compression:
Stored size: 1.88 KB
Contents
# This GraphQL Schema performs operations on numbers. # It can perform operations on values you give it and return values # It also maintains some state which can be updated or read # You can reduce a list of values to a single value REDUCERS = { "SUM" => -> (values) { [values.inject(&:+)] }, "MAX" => :max.to_proc, "MIN" => :min.to_proc, } ReducerEnum = GraphQL::EnumType.define do REDUCERS.map do |op_name, op_proc| value(op_name) end end # You can make a new list by transforming each member MAPPERS = { "ADD" => -> (val, arg) { val + arg }, "SUB" => -> (val, arg) { val - arg }, "EQ" => -> (val, arg) { val == arg ? 1 : 0}, } MapperEnum = GraphQL::EnumType.define do MAPPERS.map do |op_name, op_proc| value(op_name) end end # Input a list of integers ListOfInts = GraphQL::INT_TYPE.to_list_type # Expose a list of values and perform operations ValuesType = GraphQL::ObjectType.define do field :values, ListOfInts do resolve -> (obj, _args, _ctx) { obj } end # Get a single value based on the values in this list field :reduce, types.Int do argument :operation, !ReducerEnum resolve -> (obj, args, ctx) { reduce_name = args[:operation] reduce_fn = REDUCERS[reduce_name] reduce_fn.call(obj) } end # Handle self-referential fields by wrapping the type in a proc. # It will be lazy-eval'ed field :map, -> { ValuesType } do argument :operation, !MapperEnum argument :argument, !types.Int resolve -> (obj, args, ctx) { op_arg = args[:argument] op_name = args[:operation] op_func = MAPPERS[op_name] obj.map { |item| op_func.call(item, op_arg) } } end end QueryType = GraphQL::ObjectType.define do name("Query") field :perform, ValuesType do argument :initial, !ListOfInts resolve -> (obj, args, ctx) { args[:initial] } end end CalculatorSchema = GraphQL::Schema.new(query: QueryType)
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
graphql-0.10.2 | spec/support/calculator_schema.rb |