diff --git a/src/index.d.ts b/src/index.d.ts index f572f16..dbda441 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -9,8 +9,12 @@ export declare interface Model { is(thing: any): boolean } +export declare type ModelOptions = { + auto: boolean, +} export declare function model(target: T): T & Model & PropertyDecorator -export declare function model(name: string): typeof model +export declare function model(name?: string, options?: ModelOptions): typeof model +export declare function model(options?: ModelOptions): typeof model export declare function prop(...args: any[]): any export declare const view: MethodDecorator diff --git a/src/index.js b/src/index.js index 391d1d5..98d7369 100644 --- a/src/index.js +++ b/src/index.js @@ -24,7 +24,16 @@ const ExcludeKeys = [ TypeKey, PropsKey, ViewsKey, ] -export const model = classDecorator((Class, name = Class.name) => { +export const model = classDecorator(( + Class, + name = Class.name, + options = {auto: false}, +) => { + if (is.obj(name)) { + options = merge(options, name) + name = Class.name + } + const {preProcessSnapshot, postProcessSnapshot} = Class // TS class property initializers and defaults from constructor const values = new Class() @@ -67,7 +76,10 @@ export const model = classDecorator((Class, name = Class.name) => { Model = Model.preProcessSnapshot(snapshot => { snapshot = preProcessSnapshot ? preProcessSnapshot(snapshot) : snapshot - if (!is.obj(snapshot)) return snapshot + if (!is.obj(snapshot)) { + if (!options.auto) return snapshot + snapshot = {} + } return merge(values, snapshot) }) diff --git a/test/js/basic.js b/test/js/basic.js index a116f84..230d6a6 100644 --- a/test/js/basic.js +++ b/test/js/basic.js @@ -110,6 +110,20 @@ describe('basic', () => { getMembers(base).name.should.be.equal('User') }) + it('auto model', () => { + @model({auto: true}) class Base { + @t.str str = 'str' + } + + @model class Container { + @Base base + } + + const cont = Container.create() + cont.should.have.property('base') + cont.base.str.should.be.equal('str') + }) + it('prop', () => { @model class Base { @prop(t.str) prop diff --git a/test/ts/basic.ts b/test/ts/basic.ts index 65a8df7..c8d721d 100644 --- a/test/ts/basic.ts +++ b/test/ts/basic.ts @@ -113,6 +113,22 @@ describe('basic', () => { getMembers(base).name.should.be.equal('User') }) + it('auto model', () => { + class MBase { + @t.str str = 'str' + } + const Base = model({auto: true})(MBase) + + class MContainer { + @Base base + } + const Container = model(MContainer) + + const cont = Container.create() + cont.should.have.property('base') + cont.base.str.should.be.equal('str') + }) + it('prop', () => { class MBase { @prop(t.str) prop