Your browser doesn't support the features required by impress.js, so you are presented with a simplified version of this presentation.
For the best experience please use the latest Chrome, Safari or Firefox browser.
Node.js/Browser re-usable Entities
for consistency of interfaces and data validation
Sydney, 19th September 2013
Nik Butenko
With HTML5 validation
function isValid($form) {
var id = $form.find('[name=id]').val(),
name = $form.find('[name=name]').val();
return id.length && id.match('/^[a-z_-0-9]+/$') && name.length;
}
function onSubmit() {
var $form = $(this);
if (isValid($form)) {
sendToServer($form);
}
}
function isValid(data) {
return data.id
&& data.id.length
&& data.id.match('/^[a-z_-0-9]+/$')
&& data.name
&& data.name.length;
}
function chatAdd(req, res) {
if (isValid(req.body)) {
return saveToDb(
normalize(req.body),
renderResponse(res)
);
}
return renderResponse(res)({
error: true,
message: "OMG!"
});
}
Pic by The Mary Sue www.themarysue.com
Yes, yes, I am paranoic about data consistency
Pic by The Mary Sue www.themarysue.com
// Install Gleam first "npm install nkbt/gleam"
// or add as dependency - "gleam": "nkbt/gleam"
// ./app.js
// Require and configure Gleam
var gleam = require('gleam');
gleam.setRoot(path.join(__dirname, 'gleams'));
// [...] Do some ExpressJS configuration
// Add entity-serving middle-ware
// somewhere after static middleware
app.use(express.static(path.join(__dirname, 'public')));
app.use('/js/entity', gleam.serveEntity);
// ./gleams/chat.js
'use strict';
var ChatEntity = {
id: null,
name: null,
createdOn: null
};
// You need to export "Entity"
exports.Entity = ChatEntity;
// ./gleams/chat.js
var ChatEntity = {
//...
validateId: function (value) {
return !_.isEmpty(value)
&& _.isEqual(value, value.replace(/[^a-z_\-0-9]+/, ''));
},
validateName: function (value) {
return !_.isEmpty(value);
}
};
// ./gleams/chat.js
var ChatEntity = {
//...
getCreatedOn: function () {
if (!this.createdOn) {
var now = new Date();
return now.getTime();
}
return this.createdOn;
}
};
"use strict";
define(['entity/chat'], function (ChatEntity) {
var chatEntity = new ChatEntity();
try {
chatEntity.set(getValues($form));
} catch (error) {
return alert(error.message);
}
// Submit to server
});
"use strict";
define(['entity/from-json'], function (fromJson) {
$.ajax({
url: '', data: {/* some data */},
dataType: 'text', // We need text!
success: function (jsonString) {
return fromJson(jsonString, function(error, entity) {
console.log(entity);
});
}
});
});
"use strict";
var gleam = require('gleam');
function addChat(req, res) {
try {
var chatEntity = gleam.entity('chat', req.body);
} catch (error) {
// handle
}
// save chatEntity in DB
db.save(chatEntity.get());
};
"use strict";
var gleam = require('gleam');
function getChat(req, res) {
db.get(req.param.id, function(json) {
try {
var chatEntity = gleam.fromJson(json);
} catch (error) {
// handle
}
res.json(chatEntity.get());
})
};