11

AWS AppSync allow to define default values in schema like that

type Foo {
  bar(
    arg: Int = 20
  ): Bar!
}

or that

type Foo {
  bar(
    arg: Int! = 20
  ): Bar!
}

But either way when the value is not explicitly defined, the default value is not passed to the resolver.

Is there something I should opt-in to activate the default value to be passed? Is that an AWS bug? If so, is there a workaround?

PS: In the GraphQL specs

If no value is provided for a defined input object field and that field definition provides a default value, the default value should be used. If no default value is provided and the input object field’s type is non‐null, an error should be thrown. Otherwise, if the field is not required, then no entry is added to the coerced unordered map.

Yves M.
  • 29,855
  • 23
  • 108
  • 144
  • I've created an issue in the official AWS AppSync repository https://github.com/aws/aws-appsync-community/issues/59 – Yves M. Oct 07 '19 at 17:03

1 Answers1

10

Default arguments are currently a known issue and the best way to get around them is to use the $util.defaultIfNull() velocity helper function. For example, you can default arguments for limit and next token doing something like this:

{
  "version": "2017-02-28",
  "operation": "Scan",
  "limit": $util.defaultIfNull($ctx.args.first, 20),
  "nextToken": $util.toJson($util.defaultIfNullOrEmpty($ctx.args.after, null)),
}
Yves M.
  • 29,855
  • 23
  • 108
  • 144
mparis
  • 3,623
  • 1
  • 17
  • 16
  • 1
    Yep I'm already using a default value at the resolver level (using Lambda instead of velocity templating). But I'm not happy with that because I'm setting the default value directly in the schema `arg: Int = 20` and I don't want to redundant definitions in both the schema and the resolver. I expected the default to be set, and managed, directly in AppSync.. not in the resolver – Yves M. Jul 12 '18 at 14:04
  • 3
    You are correct. It's a known issue and will be fixed in the future. – mparis Jul 13 '18 at 08:52
  • 4
    @mparis any updates on this as it seems like this is still not working as intended by the specs? – Stefan Fabian Dec 25 '18 at 12:59
  • Question: If the limit is passed as a graphQL argument, then what's to stop an API consumer from requesting data with a limit of "1000000"? Doesn't that defeat the purpose of API pagination? – bryanbraun Jul 28 '20 at 22:26
  • 2
    if you wait 6 more years rumor has it AppSync team will fix this. – EralpB Sep 15 '20 at 15:32
  • is it fixed yet? – Raph Feb 07 '23 at 20:41
  • Just verified that this has not been fixed yet as of March 2023. Really surprised this has been an issue for over 5 years now when it's a fairly basic GraphQL feature – Turner Houghton Mar 05 '23 at 07:06