Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: Date support in forValue(..) #324

Closed
SanderElias opened this issue Oct 18, 2020 · 1 comment
Closed

Feature request: Date support in forValue(..) #324

SanderElias opened this issue Oct 18, 2020 · 1 comment

Comments

@SanderElias
Copy link

SanderElias commented Oct 18, 2020

See this sample:

import avro from 'avsc';

const data = {
  city: 'Cambridge',
  date: new Date(),
};

const type = avro.Type.forValue(data);
const buf = type.toBuffer(data);
const result = type.fromBuffer(buf)
console.log(JSON.stringify(data)===JSON.stringify(result))
/** retuns false! */
console.log(result);
/** { city: 'Cambridge', date: {} } */

I would expect that dates would be handled properly. Or did I misunderstood something?
I'm willing to create a PR for this if there is an interest.

@SanderElias SanderElias changed the title Feature request: Date support in fromValue(..) Feature request: Date support in forValue(..) Oct 18, 2020
@mtth
Copy link
Owner

mtth commented Oct 19, 2020

Hi @SanderElias. By default, forValue only supports the standard Avro types. You can extend type inference via the valueHook option, often in combination with a logical type.

For example, to infer Dates:

/** Minimal date logical type. */
class DateType extends avro.types.LogicalType {
  _fromValue(val) { return new Date(val); }
  _toValue(date) { return date instanceof Date ? +date : undefined; }
}

// Type where all `Date` fields are represented as `DateType`s.
const type = avro.Type.forValue(data, {
  valueHook: (val, opts) => {
    if (val instanceof Date) {
      return new DateType({type: 'long', logicalType: 'timestamp-millis'}, opts);
    }
    // Optionally add more logic here... Returning `undefined` falls back to
    // default inference.
  },
});
console.log(type.clone(data)); // { city: 'Cambridge', date: 2020-10-19T15:52:29.621Z }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants