Skip to content

Commit

Permalink
graphql: consider default values for graphql execution
Browse files Browse the repository at this point in the history
Note: there is a difference between explicitly passed "null" value
and just omitted variable. See graphql/graphql-spec#418

Closes #866
  • Loading branch information
olegrok committed Jun 30, 2020
1 parent e9f25bd commit 2d4e8de
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 2 deletions.
13 changes: 11 additions & 2 deletions cartridge/graphql/execute.lua
Original file line number Diff line number Diff line change
Expand Up @@ -240,16 +240,25 @@ local function getFieldEntry(objectType, object, fields, context)
argumentMap[argument.name.value] = argument
end

local defaultValues = {}
if context.operation.variableDefinitions ~= nil then
for _, value in ipairs(context.operation.variableDefinitions) do
if value.defaultValue ~= nil then
defaultValues[value.variable.name.value] = value.defaultValue.value
end
end
end

local arguments = util.map(fieldType.arguments or {}, function(argument, name)
local supplied = argumentMap[name] and argumentMap[name].value

supplied = util.coerceValue(supplied, argument, context.variables,
{strict_non_null = true})
if supplied ~= nil then
if type(supplied) ~= 'nil' then
return supplied
end

return argument.defaultValue
return defaultValues[name]
end)

--[[
Expand Down
48 changes: 48 additions & 0 deletions test/integration/graphql_test.lua
Original file line number Diff line number Diff line change
Expand Up @@ -779,3 +779,51 @@ function g.test_middleware()
}
)
end

g.test_default_values = function()
local server = cluster.main_server

server.net_box:eval([[
package.loaded['test'] = package.loaded['test'] or {}
package.loaded['test']['test_default_value'] = function(_, args)
if args.arg == nil then
return 'nil'
end
return args.arg
end
local graphql = require('cartridge.graphql')
local types = require('cartridge.graphql.types')
graphql.add_callback({
name = 'test_default_value',
args = {
arg = types.string,
},
kind = types.string,
callback = 'test.test_default_value',
})
]])

t.assert_equals(
server:graphql({
query = [[
query($arg: String = "default_value") {
test_default_value(arg: $arg)
}
]],
variables = {}}
).data.test_default_value, 'default_value'
)

t.assert_equals(
server:graphql({
query = [[
query($arg: String = "default_value") {
test_default_value(arg: $arg)
}
]],
variables = {arg = box.NULL}}
).data.test_default_value, 'nil'
)
end

0 comments on commit 2d4e8de

Please sign in to comment.