Permalink
Browse files

feat: toJSON of yukari

  • Loading branch information...
XadillaX committed Sep 22, 2016
1 parent 8257a67 commit d4e41e12c0b6d64180976b0eb0969c26f2268f4b
Showing with 70 additions and 2 deletions.
  1. +1 −1 lib/query.js
  2. +21 −0 lib/yukari.js
  3. +48 −1 test/query.js
@@ -154,7 +154,7 @@ class ToshihikoQuery {
if(options.single && row) {
if(row instanceof Yukari && toJSON) {
row = row.toJSON();
} else {
} else if(row instanceof Yukari) {
const yukari = new Yukari(self.model, "query");
yukari.fillRowFromSource(row, true);
row = yukari;
@@ -204,6 +204,27 @@ class Yukari {
return callback(undefined, self, extra);
});
}

toJSON(old) {
const obj = old ? this.$origData : this;
const result = {};

for(let key in obj) {
if(!obj.hasOwnProperty(key)) continue;
if(key.length && key[0] !== "$" && typeof obj[key] !== "function") {
result[key] = obj[key];

// if it has a certain `toJSON` function
// call it!
const idx = this.fieldAt(key);
if(idx !== -1 && typeof this.$schema[idx].type.toJSON === "function") {
result[key] = this.$schema[idx].type.toJSON(result[key]);
}
}
}

return result;
}
}

module.exports = Yukari;
@@ -10,10 +10,11 @@ const should = require("should");

const Query = require("../lib/query");
const Toshihiko = require("../lib/toshihiko");
const Yukari = require("../lib/yukari");

describe("🐣 query", function() {
const toshihiko = new Toshihiko("base");
const model = toshihiko.define("model", []);
const model = toshihiko.define("model", [ { name: "key1" } ]);

it("should create instance", function() {
const query = new Query(model);
@@ -253,5 +254,51 @@ describe("🐣 query", function() {
done();
});
});

it("should get yukari", function(done) {
const find = toshihiko.adapter.find;
toshihiko.adapter.find = function(_query, callback) {
return callback(undefined, [ { key1: "13" } ]);
};
query.find(function(err, rows) {
should.ifError(err);
toshihiko.adapter.find = find;
rows.length.should.equal(1);
const row = rows[0];
row.should.be.instanceof(Yukari);
row.key1.should.equal("13");
done();
});
});

it("should get JSON", function(done) {
const find = toshihiko.adapter.find;
toshihiko.adapter.find = function(_query, callback) {
return callback(undefined, [ { key1: "13" } ]);
};
query.find(function(err, rows) {
should.ifError(err);
toshihiko.adapter.find = find;
rows.length.should.equal(1);
const row = rows[0];
row.should.not.be.instanceof(Yukari);
row.should.match({ key1: "13" });
done();
}, true);
});

it("should get single", function(done) {
const find = toshihiko.adapter.find;
toshihiko.adapter.find = function(_query, callback) {
return callback(undefined, { key1: "13" });
};
query.find(function(err, row) {
should.ifError(err);
toshihiko.adapter.find = find;
row.should.not.be.instanceof(Yukari);
row.should.match({ key1: "13" });
done();
}, true, { single: true });
});
});
});

0 comments on commit d4e41e1

Please sign in to comment.