@itrocks/data-to-object
v0.2.0
Published
Transforms raw string-based data into a business object with type-safe values
Maintainers
Readme
data-to-object
Transforms raw input data into a business object with type-safe values.
Installation
npm i @itrocks/data-to-objectUsage
import { dataToObject } from '@itrocks/data-to-object'
class User {
name!: string
age!: number
}
const rawData = {
name: 'John Doe',
age: '30'
}
const user = new User()
await dataToObject(user, rawData)
console.log(user)
// { name: 'John Doe', age: 30 }dataToObject()
dataToObject<T extends object>(object: T, data: RecursiveValueObject): Promise<T>Converts raw data (JSON payloads, form inputs, query params…) into a business object by applying type-aware transformations on each input key that resolves to a property declared on the target object.
Parameters
object: Target business object to populate.data: Raw input data. Values may be strings or already-typed values.
(RecursiveValueObject)
Behaviour
- Only properties declared on the target object are assigned.
- Input keys are normalised from form field to property names using
@itrocks/rename(toProperty). - Fields ending with
_idfall back to their base field name (e.g.user_id→user) only when the_idproperty does not exist on the target object, and only if the base field name is not already present in the input data. - Each value is transformed using its matching transformer
(@itrocks/transformer)
with the
HTMLandINPUTcontexts. - The transformer may return a value to be assigned, or mutate the target object directly and return IGNORE to prevent any automatic assignment.
Typical use cases
- Processing web form submissions safely.
- Mapping request payloads to domain objects.
- Centralising input sanitisation and type coercion.
This function is commonly used by higher-level helpers such as @itrocks/save.
