pinia-orm icon indicating copy to clipboard operation
pinia-orm copied to clipboard

Better date casting support

Open daniandl opened this issue 1 year ago • 2 comments

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

  • [X] Would you be willing to help implement this feature?

Final checks

daniandl avatar Dec 03 '23 16:12 daniandl

Nice enhancment. If you like you can make an PR or i will go to add it. I only have to think about your sorting solution.

CodeDredd avatar Jan 16 '24 22:01 CodeDredd

I currently don't have the capacity to open a PR for this, so you are welcome to do it, if you have time :) The code for my 2nd issue is not a suggestion for the library, as the date support should be implemented much higher up, inside orderBy itself.

daniandl avatar Jan 18 '24 16:01 daniandl