I'm beginning learning Node.js and Backbone. I'd like to share some code between the server and the client (related to [1] and [2]). More in deep:


Share defaults values for a model. Defaults are used to populate forms (client-side), while they are enforced server-side
Share validation rules in order to be DRY and perform client/server validation
Share instance methods


So my idea is to use a factory object to encapsulate common code (defaults, validation rules, public instance methods) and adapt the factory object based on the environment (Node.js or AMD module).

This code is quick&amp;dirty and may not work. Is this a good approach or just a waste of time?

(function (factory) {
    if (typeof exports === 'object') { // Node.js
        var config    = require('../config/config.json'),
            Sequelize = require('sequelize'),
                    _ = require('underscore');

        var User = {
            receiveSms: {
                type: Sequelize.BOOLEAN, allowNull: false
            },
            receiveNewsletter: {
                type: Sequelize.BOOLEAN, allowNull: false
            }
        };

        // Add defaultValue for each returned by 
        _.each(factory.defaults, function (value, key) {
            if(_.has(User, key)) {
                User[key].defaultValue = value;
            }
        });

        module.exports = function () {
            (new Sequelize(config.database, config.username, config.password))
                .define('User', User);
        };
    } else if (typeof define === 'function' &amp;&amp; define.amd) { // AMD
        define(['backbone', 'uderscore'], function (Backbone, _) {
            return Backbone.Model.extend(factory);
        });
    }
}(function () {
    return { // To be adapted
        defaults: {
            receiveSms: false,
            receiveNewsletter: true
        }
    }
}));



Question: How do I tell Entity (Code First) to not send the Key ID field to the database?
Answer: If your PK is generated by the database (like an identity) you have to configure it in your Map.

public class ResourceMap : EntityTypeConfiguration&lt;Resource&gt;
{
   public ResourceMap()
   {
        // Primary Key
        this.HasKey(t =&gt; t.ID);
        this.Property(t =&gt; t.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
   }
}