Skip to content

Commit

Permalink
feat: make compile() return a full ES6 class for improved inheritance
Browse files Browse the repository at this point in the history
Fix #9
  • Loading branch information
vkarpov15 committed Feb 10, 2019
1 parent 7b99d33 commit d3e873e
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 21 deletions.
50 changes: 34 additions & 16 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,26 +15,44 @@ class Archetype {
compile(name) {
const _this = this;
this._paths = visitor(this._obj);
const type = function(obj, projection) {
if (!(this instanceof type)) {
return new type(obj, projection);

class Type {
constructor(obj, projection) {
Object.assign(this, unmarshal(cloneDeep(obj), _this, projection));
}

static paths() {
return _this.paths();
}

static path(path, props, opts) {
return _this.path(path, props, opts);
}

static omit(paths) {
return _this.omit(paths);
}

static pick(paths) {
return _this.pick(paths);
}

static transform(fn) {
return _this.transform(fn);
}

static eachPath(fn) {
return _this.eachPath(fn);
}
Object.assign(this, unmarshal(cloneDeep(obj), _this, projection));
};
type.schema = this;
if (name) {
type.toString = () => name;
Object.defineProperty(type, 'name', { value: name });
}
type.paths = () => this.paths();

type.path = (path, props, opts) => this.path(path, props, opts);
type.omit = path => this.omit(path);
type.pick = paths => this.pick(paths);
type.transform = fn => this.transform(fn);
type.eachPath = fn => this.eachPath(fn);
Type.schema = this;
if (name != null) {
Type.toString = () => name;
Object.defineProperty(Type, 'name', { value: name });
}

return type;
return Type;
}

json() {
Expand Down
13 changes: 8 additions & 5 deletions test/unit.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -544,11 +544,14 @@ describe('unmarshal()', function() {
assert.equal(new Person({}).constructor.name, 'PersonModel');
});

it('compiled function can be called without "new" keyword', function() {
const Person = new Archetype({
name: 'string'
}).compile('Person');
assert.ok(Person({}) instanceof Person);
it('handles inheritance correctly with path(), etc.', function() {
const ABase = new Archetype({ x: { $type: 'string' } }).compile('ABase');

class A extends ABase {}

const B = A.path('y', { $type: 'string' }).compile('B');

assert.deepEqual(new B({ x: 1, y: 2 }), { x: '1', y: '2' });
});

it('validation with arrays and nested objects', function() {
Expand Down

0 comments on commit d3e873e

Please sign in to comment.