npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

auto-type-cast

v0.5.0

Published

Simple, lightweight type casting of JSON objects to classes. Use it on the JSON response from your server to deal with proper model classes on the frontend. No dependencies

Downloads

152

Readme

Description

Simple, lightweight type casting of JSON objects to classes. Use it on the JSON response from your server to so you can use proper model classes on the frontend in one function call.

Your server has model classes. Your frontend has model classes. But, there isn't a great way to get instances of your Javascript model classes from the JSON objects in your responses. This package gives you an easy way to do so, without integrating with a complex Javascript framework, tying you to a specific server framework, or pulling in many dependencies (this package has none).

Example

Given a JSON structure that looks like this:

var homer = {
  name: "Homer Simpson",
  __type: "Person",
  foods: [
    { name: "Jelly", category: "donut", favorite: true, __type: "Food" }
  ]
}

and some model classes that look like this:

@Register('Person')
class Person {
  getFavoriteFood() { return this.foods.find(f => f.favorite); }
}

@Register('Food')
class Food {
  getFullName() { return `${this.name} ${this.category}`; }
}

you can easily cast your JSON objects to instances of their respective classes:

autoTypeCast(homer);
homer.getFavoriteFood().getFullName(); // "Jelly donut"

Does this function mutate the original objects? Yes, and it uses setPrototypeOf to do so. Mozilla claims this is much slower than Object.assign, and also a dangerous operation. My benchmarks show the opposite, but I am actively looking for counterexamples.

Doesn't this mean I need to add an attribute to my JSON objects being sent from the server? Yes. This is simple enough for my use cases. If this does not fit for you, you should find a more complex framework. For example, class-transformer is non-intrusive through use of type decorators.

Usage

Installation

First, add the package to your project:

npm install auto-type-cast --save

Next, register your model classes using the @Register decorator:

import { Register } from 'auto-type-cast';

@Register('Person')
class Person {
  // ... your class implementation
}

The @Register decorator takes a string parameter that specifies the type name to use for this class. This is particularly useful when your class names might be minified or obfuscated in production, as it allows you to maintain a consistent type name regardless of code transformation.

Make sure your server sends a __type attribute matching the registered name, or augment the Javascript once you have it on the client. You're on your own with this, but here's an example from Ruby using ActiveModelSerializers:

class ApplicationSerializer < ActiveModel::Serializer
  attribute(:__type) { model.class.name }
  #assumes model class on server has same name as registered on frontend
end

class PersonSerializer < ApplicationSerializer; end

Configure autoTypeCast. See Configuration below.

Finally, call autoTypeCast on the object. Arrays and deeply-nested structures will be scanned and cast as well, if found.

import autoTypeCast from 'auto-type-cast';

var response = fetch(...);
autoTypeCast(response.data);

Alternative Registration Methods

While using the @Register decorator is the recommended approach, you can also register classes manually:

import { registerClass } from 'auto-type-cast';

class Person {
  // ... your class implementation
}

registerClass(Person);  // Will use the class name as the type

Property Transformations

You can use the @Transform decorator to automatically transform property values during type casting. This is particularly useful for converting date strings to Date objects, formatting strings, or transforming nested data structures:

import { Register, Transform } from 'auto-type-cast';

@Register('Person')
class Person {
  @Transform(date => new Date(date))
  birthDate;

  @Transform(str => str.toUpperCase())
  name;
}

const data = {
  __type: 'Person',
  birthDate: '1990-01-01',
  name: 'Homer Simpson',
};

autoTypeCast(data);
// data.birthDate is now a Date object (1990-01-01)
// data.name is now 'HOMER SIMPSON'

The Transform decorator takes a function that receives the property's value and returns the transformed value. The transformation is applied during the type casting process, after the object's prototype is set but before any afterTypeCast hooks are called.

Transform Error Handling

Transform functions are executed in a safe manner - if a transform throws an error, the original value is preserved and the type casting process continues. This ensures that your application won't break even if a transform fails:

@Register("User")
class User {
  @Transform((value) => new Date(value)) // If this fails, original string is kept
  createdAt;

  @Transform((str) => str.toUpperCase()) // This will still run even if createdAt transform failed
  name;
}

You can configure how transform errors are handled either globally or per-call:

// Global error handling configuration
import config from "auto-type-cast/config";

config.onTransformError = (error, propertyKey, value, transformFn, type) => {
  ErrorMonitoring.capture(error, {
    context: {
      type, // The class type (e.g., 'User')
      property: propertyKey, // The property that failed (e.g., 'createdAt')
      value, // The original value that caused the error
    },
  });
};

// Per-call error handling
autoTypeCast(data, {
  onTransformError: (error, propertyKey, value, transformFn, type) => {
    console.warn(`Transform failed for ${type}.${propertyKey}:`, error);
  },
});

The error handler receives:

  • error: The error that was thrown
  • propertyKey: The name of the property being transformed
  • value: The original value that caused the error
  • transformFn: The transform function that failed
  • type: The class type name

Customization

You can control the name of the attribute that specifies the class name:

var myObject = { "name": "Homer", myType: 'Person' };
autoTypeCast(myObject, { typeKey: 'myType' });
// myType was used to convert the object to instance of Person

If you need more granular or dynamic control of the class registry, import it directly:

import { classRegistry } from 'auto-type-cast';
delete classRegistry['Person'];
autoTypeCast({ __type: 'Person'}); // no conversion

Configuration

| Parameter | Description | Default | | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | | config.typeKey | Determines the attribute name that specifies the object's type | __type | | config.getObjectType | Returns the object's type. Used to look up the correct class in the registry. Uses config.typeKey by default, but if you need more control, you can override this | (object, options) => object[options.typeKey \|\| config.typeKey] | | config.getClassType | Returns the class's "type" name. Used to map objects to this class. The object type and the class type must match in order for autoTypeCast to work. | (klass) => klass.registeredName \|\| klass.name | | config.beforeTypeCast | Called with the object as a parmeter immediately before type casting it. You can use this if you need to transform it (e.g. manipulating __type) before it is ready for type cast. | No-op (object) => {} | | config.afterTypeCast | Called with the object as a parmeter immediately after type casting it. You can use this if you need to transform it after it has taken on its new class (e.g. calling a function from the new class like object.mySpecialInit()) | No-op (object) => {} | | config.onTransformError | Called when a transform function throws an error. Receives the error, property key, original value, transform function, and class type. | Logs warning and preserves original value |

Development

Testing

  • npm run watch
  • Edit base code and observe test results

Building

  • npm run prod Runs tests, lints, and builds the module
  • npm version patch (or minor/major etc.)
  • npm publish