Skip to content

Querying with custom types #739

@adamburgess

Description

@adamburgess

Is your feature request related to a problem? Please describe.
Using custom types currently works when inserting/updating, but I can't query with them.

I want to use this for Date <--> unix timestamp (number).
Describe the solution you'd like

@Entity()
class Foo {
    @PrimaryKey()
    id!: number

    @Property({ type: UnixTimestamp })
    bar!: Date
}

class UnixTimestamp extends Type<Date, number> {
    convertToDatabaseValue(value: Date | number) {
        console.log('converting', value);
        if (value instanceof Date)
            return value.getTime();
        return value;
    }
    convertToJSValue(value: Date | number) {
        if (value instanceof Date)
            return value;
        return new Date(value);
    }
    getColumnType() {
        return 'number';
    }
}

em.find(Foo, { bar: new Date(1000) });
// converting 1970-01-01T00:00:01.000Z
// [query] select `e0`.* from `foo` as `e0` where `e0`.`bar` = 1000

Currently:

// [query] select `e0`.* from `foo` as `e0` where `e0`.`bar` = '1970-01-01 00:00:01.000'

Describe alternatives you've considered
It does work doing something like:

em.find(Foo, { bar: new UnixTimestamp().convertToDatabaseValue(new Date(1000)) as unknown as Date });

... which provides the correct type... but I'd prefer not to do this...

Additional context
This example here is not necessary for databases other than sqlite as they have working datetimes, but say I instead used a truly custom JS type such as dayjs or moment instance, then I'd always have to do the conversion manually

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions