Skip to content

Commit

Permalink
Add @Transform decorator to transform (e.g. parse) properties during …
Browse files Browse the repository at this point in the history
…type cast
  • Loading branch information
joshjordan committed Nov 10, 2024
1 parent 2abeb67 commit 81b2244
Show file tree
Hide file tree
Showing 7 changed files with 144 additions and 6 deletions.
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,41 @@ class Person {
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;
// Transform can also handle nested objects
@Transform(foods => foods.map(f => ({ ...f, __type: 'Food' })))
foods;
}
const data = {
__type: 'Person',
birthDate: '1990-01-01',
name: 'Homer Simpson',
foods: [{ category: 'DONUT', name: 'Jelly' }]
};
autoTypeCast(data);
// data.birthDate is now a Date object (1990-01-01)
// data.name is now 'HOMER SIMPSON'
// data.foods[0] will be cast to Food class
```

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.

### Customization

You can control the name of the attribute that specifies the class name:
Expand Down
18 changes: 15 additions & 3 deletions src/autoTypeCast.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { classRegistry } from './classRegistry';
import config from './config';
import { getTransforms } from './transformRegistry';

function autoTypeCast(obj, options = {}) {
if (obj === null || obj === undefined) {
Expand All @@ -21,6 +22,17 @@ function autoTypeCast(obj, options = {}) {
// todo: class could specify before/after/around autoTypeCast
(options.beforeTypeCast || config.beforeTypeCast)(obj);
Object.setPrototypeOf(obj, objectClass.prototype);

// Apply any registered transformations
const transforms = getTransforms(type);
const transformedProps = {};
Object.entries(transforms).forEach(([prop, transformFn]) => {
if (obj[prop] !== undefined) {
transformedProps[prop] = transformFn(obj[prop]);
}
});
Object.assign(obj, transformedProps);

(options.afterTypeCast || config.afterTypeCast)(obj);
}
// todo: else if has key but no type found and option is set, throw error
Expand All @@ -29,7 +41,7 @@ function autoTypeCast(obj, options = {}) {
return obj;
}

// thanks jayrowe!
// thanks @jayrowe!
function autoTypeCastIterable(iterable, options) {
const iterator = iterable[Symbol.iterator]();
let current;
Expand All @@ -41,5 +53,5 @@ function autoTypeCastIterable(iterable, options) {
return iterable;
}

export default autoTypeCast;
export { classRegistry };
export { classRegistry, autoTypeCast as default };

8 changes: 7 additions & 1 deletion src/decorators.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { registerClass } from './classRegistry';
import { registerTransform } from './transformRegistry';

const Register = name => function decorator(target) {
// Store the registration name on the class
Expand All @@ -14,4 +15,9 @@ const Register = name => function decorator(target) {
return target;
};

export default Register;
const Transform = transformFn => function decorator(target, propertyKey) {
// Register the transformation function for this property
registerTransform(target, propertyKey, transformFn);
};

export { Register, Transform };
6 changes: 5 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import autoTypeCast from './autoTypeCast';
import { classRegistry, registerClass } from './classRegistry';
import config, { defaultConfig } from './config';
import { Register, Transform } from './decorators';

export default autoTypeCast;
export {
classRegistry,
registerClass,
config,
defaultConfig,
Register,
registerClass,
Transform
};

15 changes: 15 additions & 0 deletions src/transformRegistry.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Store transformations for each class's properties
// Format: { className: { propertyName: transformFn } }
const transformRegistry = {};

export function registerTransform(target, propertyKey, transformFn) {
const className = target.constructor.name;
transformRegistry[className] = transformRegistry[className] || {};
transformRegistry[className][propertyKey] = transformFn;
}

export function getTransforms(className) {
return transformRegistry[className] || {};
}

export { transformRegistry };
2 changes: 1 addition & 1 deletion test/unit/specs/classRegistry.spec.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { classRegistry, registerClass } from '../../../src/classRegistry';
import config from '../../../src/config';
import Register from '../../../src/decorators';
import { Register } from '../../../src/decorators';

describe('classRegistry', () => {
test('object exists', () => {
Expand Down
66 changes: 66 additions & 0 deletions test/unit/specs/transformRegistry.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import autoTypeCast from '../../../src/autoTypeCast';
import { classRegistry } from '../../../src/classRegistry';
import { Register, Transform } from '../../../src/decorators';
import { transformRegistry } from '../../../src/transformRegistry';

describe('Transform decorator', () => {
beforeEach(() => {
// Clear registries before each test
Object.keys(classRegistry).forEach(key => delete classRegistry[key]);
Object.keys(transformRegistry).forEach(key => delete transformRegistry[key]);
});

it('transforms properties using the specified function', () => {
@Register('Person')
class Person {
@Transform(dateStr => {
const date = new Date(dateStr);
// Ensure timezone doesn't affect the test
date.setUTCHours(0, 0, 0, 0);
return date;
})
birthDate;

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

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

autoTypeCast(data);

expect(data.birthDate instanceof Date).toBe(true);
expect(data.birthDate.getUTCFullYear()).toBe(1990);
expect(data.name).toBe('HOMER SIMPSON');
});

it('handles nested objects with transformations', () => {
@Register('Food')
class Food {
@Transform(str => str.toLowerCase())
category;
}

@Register('Person')
class Person {
foods;
}

const data = {
__type: 'Person',
foods: [
{ __type: 'Food', category: 'DONUT', name: 'Jelly' },
{ __type: 'Food', category: 'PIZZA', name: 'Pepperoni' },
],
};

autoTypeCast(data);

expect(data.foods[0].category).toBe('donut');
expect(data.foods[1].category).toBe('pizza');
});
});

0 comments on commit 81b2244

Please sign in to comment.