scotthovestadt / schema-object

Enforce schema on JavaScript objects, including type, transformation, and validation. Supports extends, sub-schemas, and arrays.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Access to raw object even if getter is defined?

jarlah opened this issue · comments

I have the following code. When I print the user with toObject I get the getter representation. But what I really want is to get the underlying object. The actual value. Even if there are a getter there. The getter is just presentation.

Is it possible somehow to get the raw object underneath? Or can i do this in some other way that solves my problem?

const SchemaObject = require('schema-object');

const Decimal = {
  type: Number,
  transform: (string) => string.replace(/,/g, '.') * 1,
  getter: (value) => (value + '').replace(/\./g, ',')
};

// Create User schema
const User = new SchemaObject({
  name: String,
  height: Decimal,
  age: Number
});

const user = new User({
  name: 'Jarl',
  height: '23,55'
});

console.log(user.toObject());

prints

Object {name: "Jarl", height: "23,55"}

but I want:

Object {name: "Jarl", height: 23.55}

Interesting question.

You can use the setter to store the original value on a different key and then override the implementation of toObject() to output the object format you need.