Add a toJSON method to the hook context (#63)

This commit is contained in:
David Luecke 2017-11-19 17:13:28 -08:00
parent c5a038a408
commit c325a3cf81
5 changed files with 41 additions and 3 deletions

View File

@ -1,4 +1,4 @@
const { each } = require('./utils')._;
const { each, pick } = require('./utils')._;
function convertGetOrRemove (args) {
const [ id, params = {} ] = args;
@ -35,6 +35,13 @@ exports.converters = {
exports.createHookObject = function createHookObject (method, args, data = {}) {
const hook = exports.converters[method](args);
Object.defineProperty(hook, 'toJSON', {
value () {
return pick(this, 'type', 'method', 'path',
'params', 'id', 'data', 'result', 'error');
}
});
return Object.assign(hook, data, {
method,
// A dynamic getter that returns the path of the service

View File

@ -58,7 +58,9 @@ const _ = exports._ = {
pick (source, ...keys) {
const result = {};
keys.forEach(key => {
result[key] = source[key];
if (source[key] !== undefined) {
result[key] = source[key];
}
});
return result;
},

View File

@ -134,6 +134,24 @@ describe('hook utilities', () => {
};
const hookData = { app, service };
it('.toJSON', () => {
let hookObject = utils.createHookObject('find', [
{ some: 'thing' }
], hookData);
expect(hookObject.toJSON()).to.deep.equal({
params: { some: 'thing' },
method: 'find',
path: 'testing'
});
expect(JSON.stringify(hookObject)).to.equal(JSON.stringify({
method: 'find',
path: 'testing',
params: { some: 'thing' }
}));
});
it('for find', () => {
let hookObject = utils.createHookObject('find', [
{ some: 'thing' }

View File

@ -4,7 +4,7 @@ const { _ } = require('../lib/commons');
describe('module', () => {
it('is commonjs compatible', () => {
let commons = require('../lib/commons');
console.log(commons);
expect(typeof commons).to.equal('object');
expect(typeof commons.stripSlashes).to.equal('function');
expect(typeof commons.sorter).to.equal('function');

View File

@ -46,6 +46,10 @@ describe('@feathersjs/commons utils', () => {
expect(key).to.equal(0);
expect(value).to.equal('hi');
});
_.each('moo', value => expect(false)
.to.equal(true, 'Should never get here')
);
});
it('some', () => {
@ -113,6 +117,13 @@ describe('@feathersjs/commons utils', () => {
first: 1,
second: 2
});
expect(_.pick({
name: 'David',
first: 1
}, 'first', 'second')).to.deep.equal({
first: 1
});
});
it('merge', () => {