Skip to content

Better date casting support #1747

@daniandl

Description

@daniandl

Describe the feature

I have two small improvement suggestions regarding dates.

  • DateCast setter should understand how to parse numbers too (simply new Date(value).toISOString())
  • .orderBy() on date fields sorts by the string value, not by the actual timestamp

Number one can be fixed by updating the DateCast class setter a bit

export class DateCast extends CastAttribute {
  /**
   * Create a new String attribute instance.
   */
  constructor(attributes: ModelFields) {
    super(attributes)
  }

  get(value: string | null): Date | null {
    return value ? new Date(value) : null
  }

  set(value: string | number | Date | null): string | null {
    if (value === null) return null

    if (typeof value === 'number') return new Date(value).toISOString()
    if (typeof value === 'string') return new Date(Date.parse(value)).toISOString()
    return value.toISOString()
  }
}

Number 2 I have temporarily resolved like this

function sortByDate<Model, Key extends keyof Model>(key: Key) {
  return (obj: Model) => obj[key] ? new Date(obj[key] as string).getTime() : 0
}

return useRepo(ChatMessage).query()
        .with('user')
        .where('room', this.currentRoom)
        .orderBy(sortByDate('createdAt'), 'asc')
        .get()

I'm using the decorator model definition, maybe this is only a bug with those?
I haven't tested the other way yet.

Additional information

  • Would you be willing to help implement this feature?

Final checks

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions