Clojure

provide a way to write a map spec that disallows extra keys

Details

  • Type: Enhancement Enhancement
  • Status: Closed Closed
  • Priority: Minor Minor
  • Resolution: Declined
  • Affects Version/s: None
  • Fix Version/s: None
  • Component/s: None
  • Labels:
    None

Description

After reading the initial docs and tutorials, I was expecting that calling `conform` or `valid` with a `key` spec and a map that contained extra keys would indicate a spec failure, but it doesn't:

```clj
(spec/conform
(spec/keys :req [::foo ::bar])
{::foo "foo" ::bar "bar" ::baz "baz"})
=>
{:user.swagger-ui-service/foo "foo",
:user.swagger-ui-service/bar "bar",
:user.swagger-ui-service/baz "baz"}
```

Obviously this behavior is desirable in many situations, but perhaps there could also be another spec type, called `exact-keys` or something, that would fail in the above example because of the presence of the non-specified `::baz` key.

This seems like it would be particularly useful when specifying the return value for a function that is returning data for an HTTP endpoint, to make sure that the program isn't violating the API specification by including extraneous data in the response.

This can be achieved with the current `spec` by `and`ing together a `keys` spec with a custom predicate that does some set logic on the keys, but that is a little unwieldy and repetitive, and doesn't produce as nice of an error message as what could probably be done if it were built in.

Activity

Hide
Alex Miller added a comment -

I am declining this ticket as this was considered and intentionally not provided. Rich believes that maps should be open containers and that extra attributes should be allowed (similar philosophy behind having open records).

As you mention, there are other ways to add this constraint if desired.

Show
Alex Miller added a comment - I am declining this ticket as this was considered and intentionally not provided. Rich believes that maps should be open containers and that extra attributes should be allowed (similar philosophy behind having open records). As you mention, there are other ways to add this constraint if desired.
Hide
Jan-Paul Bultmann added a comment -

I hope you guys reconsider at some point, this is the only reason why I'll stick with schema.

Show
Jan-Paul Bultmann added a comment - I hope you guys reconsider at some point, this is the only reason why I'll stick with schema.
Hide
Tommi Reiman added a comment -
Show
Tommi Reiman added a comment - https://dev.clojure.org/jira/browse/CLJ-2116 would solve this too.

People

Vote (0)
Watch (2)

Dates

  • Created:
    Updated:
    Resolved: