vulcainjs / vulcain-corejs

Microservice framework for nodejs
https://vulcainjs.github.io
Apache License 2.0
11 stars 3 forks source link

Array of enum on Property ? #21

Closed workfel closed 7 years ago

workfel commented 7 years ago

Hey,

I would like to know if it's possible to have an Array of enum on the Property. I have this

@Property({ type: 'enum', required: true, values: ['value1', 'value2'] })
    userType: string;

Can do have an property type like

@Property({ type: 'Array<enum>', required: true, values: ['value1', 'value2'] })
    userType: Array<string>;

Thx

malain commented 7 years ago

You must define a custom type. Since vulcainjs v1.1.140, you can create a type with annotation like this:

@SchemaTypeDefinition()
export class ArrayOfEnum implements ISchemaTypeDefinition {
    // Overrided properties
    $values: any[];
    validate(val) {
        if (!this.$values) 
          return "You must define array item type with the 'items' property.";
        if (!Array.isArray(val)) 
          return "Invalid value '{$value}' for '{$propertyName}', value must be an array.";
        let error = false;
        for(let e of val) {
            if (this.$values.indexOf(val) === -1) {
                error = true;
                break;
            }
        }
        if (error) 
          return "Invalid value '{$value}' for '{$propertyName}', all values must be one of [{$values}].";
    }

    // bind(val: any): any {}
}

and use it like that:

    @Property({type: "ArrayOfEnum",  values: ["a", "b"]})
    enums: string[];