reforms / ts-jenum

TypeScript Enum like java.lang.Enum

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to use with mongoose?

totoblabla3 opened this issue · comments

I got confused when I didn't see my comment
I did not immediately understand that the topic was concretized :)

I sat, thought and came up with a crutch solution 👍 👍 💯

@Enum("id")
export class PeriodUnit extends EnumType<PeriodUnit>() {

    static readonly DAY = new PeriodUnit('d');

    protected constructor(readonly id: string) {
        super()
    }
}
@Schema()
export class Period {
    
    @EnumProp(PeriodUnit,{
        required: true
    })
    unit: PeriodUnit
}
abstract class JenumClass extends EnumType<JenumClass>() {
    private constructor(
        readonly id: string,
        ...args: any[]
    ) {
        super()
    }
}

export function EnumProp<T extends typeof JenumClass>(
    jenumCls: T,
    options?: PropOptions
) {
    return (target: {}, propertyKey: string) => {
        Prop({
            ...(options as object),
            type: String,
            set: (v: JenumClass) => v.id,
            get: (v: string) => jenumCls.valueOf(v)
        })(target, propertyKey);
    }
}