Search code examples
constraintstraits

How do I add a constraint for a list to not be empty in smithy?


How do I add a constraint for a list to not be empty in smithy? I have a smithy list as below -

list CarsList {
    member: Car
}

struct Car {
    @required
    Name: CarName
}

@length(min: 1)
string CarName

I want to add a constraint/trait to the list CarList to not allow it to be empty.

I tried to add @required to CarName in struct Car and @length(min: 1) to string Carname as shown above but it did not do any work.


Solution

  • You can use the @min trait for such requirements.

    list CarsList {
        @min(1)
        member: Car
    }
    
    struct Car {
        @required
        Name: CarName
    }
    
    @length(min: 1)
    string CarName
    

    If you create an instance of CarsList with no elements, it will be considered invalid. @min trait specifies a minimum amount of elements that the list must have, here we have at least 1 is required.