Skip to content

Commit

Permalink
api: add helper to create object that is passed as locals to render
Browse files Browse the repository at this point in the history
the automessages/manual messages
  • Loading branch information
prateekbhatt committed May 25, 2014
1 parent 3f80dbe commit 277334b
Show file tree
Hide file tree
Showing 2 changed files with 131 additions and 0 deletions.
68 changes: 68 additions & 0 deletions apps/api/helpers/get-render-data.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// this module returns an object of variables that will be passed as locals
// to render the body/subject of an automessage / manual message

/**
* npm dependencies
*/

var _ = require('lodash');



/**
* The 'meta' array must have been converted toObject before calling this function
* The 'email' and 'user_id' are passed alongwith the all the metadata keys
*
* INPUT:
*
user: {
_id: 42389472398472839,
user_id: 'prateekbhatt',
email: 'prattbhatt@gmail.com',
meta: {
name: 'Prateek',
status: 'Free',
amount: 49
}
}
*
* OUTPUT:
*
user: {
email: 'prattbhatt@gmail.com',
user_id: 'prateekbhatt',
name: 'Prateek',
status: 'Free',
amount: 49
}
*
*
*/

function getRenderData(user) {

// if user is in BSON format, convert it into JSON
if (user.toJSON) {
user = user.toJSON();
}

var meta = user.meta;

if (_.isArray(meta)) {
throw new Error('getRenderData "user.meta" must be an object');
}

// add the email and user_id properties to the meta object
meta.email = user.email;
meta.user_id = user.user_id;

var locals = {
user: meta
};

return locals;

}


module.exports = getRenderData;
63 changes: 63 additions & 0 deletions apps/api/test/unit/helpers/get-render-data.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
describe('Helper get-render-data', function () {

/**
* Helpers
*/

var getRenderData = require('../../../helpers/get-render-data');
var metadata = require('../../../helpers/metadata');


before(function (done) {
setupTestDb(done);
});

describe('()', function () {

var user;

var output;

beforeEach(function () {
user = saved.users.first.toJSON();
user.meta = metadata.toObject(user.meta);

output = {
user: {
user_id: user.user_id,
email: user.email,
name: user.meta.name
}
}
});


it('should throw error if user.meta is array, not object', function () {

function metaArray() {
getRenderData({
email: 'randomemail@example.com',
meta: [{
k: 'name',
v: 'Prateek'
}]
})
}

expect(metaArray).to.throw('getRenderData "user.meta" must be an object');

});


it('should create locals object for automessage', function () {

var locals = getRenderData(user);

expect(locals)
.to.have.property("user")
.that.is.an("object")
.that.deep.equals(output.user);
});

});
});

0 comments on commit 277334b

Please sign in to comment.