Skip to content

Commit

Permalink
fix #174
Browse files Browse the repository at this point in the history
  • Loading branch information
icebob committed Apr 4, 2017
1 parent 596b302 commit d939c95
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
12 changes: 9 additions & 3 deletions src/utils/schema.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
import {get, set, each} from "lodash";
import {get, set, each, isObject, isArray, isFunction, cloneDeep} from "lodash";

// Create a new model by schema default values
module.exports.createDefaultObject = function (schema, obj = {}){
each(schema.fields, (field) => {
if (get(obj, field.model) === undefined && field.default !== undefined)
set(obj, field.model, field.default);
if (get(obj, field.model) === undefined && field.default !== undefined) {
if (isFunction(field.default)) {
set(obj, field.model, field.default(field, schema, obj));
} else if (isObject(field.default) || isArray(field.default)) {
set(obj, field.model, cloneDeep(field.default));
} else
set(obj, field.model, field.default);
}
});
return obj;
};
Expand Down
20 changes: 18 additions & 2 deletions test/unit/specs/utils/schema.spec.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* global sinon */
import { expect } from "chai";
import { clone } from "lodash";

Expand All @@ -7,14 +8,21 @@ describe("SchemaUtils", () => {

describe("test createDefaultObject function", () => {

let obj = { a: 5 };
let arr = [5, 3];

let cb = sinon.stub().returns(100);

let schema = {
fields: [
{ model: "id" },
{ model: "name", default: "Anonymous" },
{ model: "password" },
{ model: "age", default: 30 },
{ model: "email" },
{ model: "skills", default: [] },
{ model: "skills", default: arr },
{ model: "data", default: obj },
{ model: "fromFn", default: cb },
{ model: "status", default: true }
]
};
Expand All @@ -28,9 +36,17 @@ describe("SchemaUtils", () => {
id: 5,
name: "Anonymous",
age: 45,
skills: [],
skills: [5, 3],
data: { a: 5 },
fromFn: 100,
status: true
});

// Need to clone Object & Array
expect(res.skills).to.not.equal(arr);
expect(res.data).to.not.equal(obj);

expect(cb.calledOnce).to.be.true;
});


Expand Down

0 comments on commit d939c95

Please sign in to comment.