Jean-Jacques Dubray SAM sample app on Node.js

Created by Jean-Jacques Dubray last modified
/* 
This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <http://unlicense.org/>
*/

var theme = require('./theme') ;

var express = require('express');
var bodyParser = require('body-parser') ;
var request = require('request');
var parseString = require('xml2js').parseString;

var config = {} ;

config.port = 5415 ;
config.portOffset = 0 ;
config.adminDirectory = './theme/html' ;


var app = express();
app.use(bodyParser.raw()) ;
app.use(bodyParser.urlencoded({ extended: true }));

var cookieParser = require('cookie-parser') ;
app.use(cookieParser()) ;

theme.addLink('html') ; 
app.use(theme.links.html, express.static(config.adminDirectory));

theme.addLink('home','') ; 
theme.addLink('contact') ; 
 
///////////////////////////////////////////////////////
// Model
//
var model = {} ;

model.title = 'Jean-Jacques Dubray' ;

model.personal = {} ;
model.personal.name = 'Jean-Jacques Dubray' ;
model.personal.tagLine = 'Platform Architect and Full Stack Developer' ;

model.about = {} ;
model.about.intro = 'Hands-on Software Architect<br>with a passion for technology, distributed systems and programming languages' ;
model.about.name = model.personal.name ;
model.about.email = 'jdubray@gmail.com' ;
model.about.phone = '+1-425-298-7823' ;
model.about.resume = '#' ;
model.about.location = 'Bellevue, WA' ;
model.about.img = model.imageDir + 'aboutbg.jpg' ;

model.counter = 0 ;
model.fetchFeed = false ;

// Mount the blog post list in the model
// Here I am illustrating the decoupling between the "API"
// and the view. There is no need to couple the view with 
// the way the blog posts are fetched, which could be 
// at periodic time

function getRssFeed(data) {
    
    var options = {
      url: 'http://www.ebpml.org/blog15/feed/',
      headers: {
        'accept': 'application/json'
      }
    };
    
    request(options, function (error, response, body) {
       if (!error && response.statusCode == 200) {
           parseString(body, function (err, result) {
               console.log(JSON.stringify(result.rss.channel[0].item[0],null,4));
               data.blog = result.rss.channel[0].item ;
               // it is better to "present" it to the model
               // as this is could easily become a system action 
               // triggered automatically
               present(data) ;
           });
       }
     });
}
const COUNTER_MAX = 1000 ;

function present(data) {
    data = data || {} ;
    if (data.blog !== undefined) {
        model.blog = data.blog ;
        model.fetchFeed = false ;
    }
    
    // we refresh the feed every so often
    model.counter += 1 ;
    model.refreshFeed = ((model.counter % COUNTER_MAX) === 0) ;
    
    if (data.contact !== undefined) {
        model.contacts[model.contacts.length] = data.contact ;
    }
}

///////////////////////////////////////////////////////
// The S() function is just responsible for rendering the view
//
// This illustrates how Front-End developers code the view
// The is no "page" concept, the Front-End developer thinks 
// in terms of rendering the model only, aka, the state representation
// The other side of the application decides how the model gets updated

function s(m,nap) {
    // compute state representation
    
    var representation = (
        theme.personal(m.personal) 
    +   theme.about(m.about)
    +   theme.blog(m.blog)
    +   theme.contact(m.contact)
    ) ;
    // next action predicate
    nap(m) ;
    return representation ;
}

// next action predicate
const COUNTER_MAX = 100 ;
function nap(m) {
    m.fetchFeed = m.fetchFeed || false ;
    
    if (m.fetchFeed) {
        // execute automatic action
        getRssFeed({}) ;
    }
}

///////////////////////////////////////////////////////
// There are only two actions
//  - get the Initial state (home page)
//  - post a contact

// theme.addLink('home','') ; 
app.get(theme.links.home, function(req,res) {

    var resp = theme.viewContainer(
                   s(model, nap)
               ) ;
    // The action is "empty", nothing to present to the model
    res.header('Content-Type', 'text/html') ;
    res.status(200).send(resp) ;

}) ;
 
 
// theme.addLink('contact') ; 
app.post(theme.links.contact, function(req,res) {
       // we are simply adding the people 
       var data = { contact: req.body } ;
       present(data) ;
       
       try {
         res.redirect(theme.links.home);
       } catch (err) {
           res.header('Content-Type', 'text/plain') ;
           res.status(500).send("server error\n"+err) ;
       }
               
  }) ;
 
 
 app.listen(config.port+config.portOffset, function() {
     console.log("registering on port: "+config.port) ;
 });
    
{
  "name": "about.me",
  "version": "1.0.0",
  "scripts": {
    "start": "node about.js"
  },
  "dependencies": {
    "body-parser": "*",
    "cookie-parser": "",
    "express": "4.13.x",
    "morgan": "1.6.x",
    "cron": "1.0.x",
    "request": "2.64.x",
    "xml2js":"0.4.15" 
  },
  "preferGlobal": false,
  "private": true
}
/* 
This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <http://unlicense.org/>
*/

var theme = {} ;

function join(arr, c) {
    c = c || '\n' ;
    arr = arr || [] ;
    var out = '' ;
    if (arr.length>0) {
        arr.forEach(function(el) {
            out += el + c ;
        });
    }
    return out ;
}


theme.links = {} ;
    
theme.addLink = function(des,path) {
    path = path || des ;
    theme.links[des] = '/'+path ;
} ;


function getClass(attributes) {
    attributes = attributes || [] ;
    var cl =  join(attributes,' ') ;
    if (attributes.length>0) {
        cl = ' class="'+cl+'"' ;
    }
    return cl ;
}

theme.html = function(mup) {
    return ('\
 <!doctype html>\n\
 <html lang="en">\n' + mup + '</html>\n') ;
} ;

theme.body = function(mup) {
    return ('<body>\n'+mup+'</body>\n') ;
} ;

theme.container = function(mup, attributes) {
    attributes = attributes || ['container'] ;
    return '<div '+getClass(attributes)+'>\n'+mup+'</div>\n' ;
} ;

theme.row = function(mup, attributes ) {
    attributes = attributes || ['row'] ;
    return theme.container(mup,attributes) ;
} ;

theme.section = function ( id, mup, attributes) {
   return '\n\n<section id="'+id+'"'+getClass(attributes)+'>\n'+mup+ '</section>\n' ;
} ;
 
theme.head = function(mup) {
    return ('<head>\n'+mup+'</head>\n') ;
} ;

theme.title = function(title) {
    return ('<title>\n'+title+'</title>\n') ;
} ;

theme.meta = function(attr,content) {
    return ('<meta name="'+attr+'" content="'+content+'">\n') ;
} ;

theme.defaultViewport = function() {
    return ('<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1" />\n') ;
} ;

theme.charset = function(cs) {
    cs = cs || 'utf-8' ;
    return ('<meta charset="'+cs+'">\n') ;
} ;

theme.link = function(rel,href) {
    var sizes = '' ;
    if (href.indexOf('72x72')) {
        sizes = 'sizes="72x72"' ;
    }
    if (href.indexOf('114x114')) {
        sizes = 'sizes="114x114"' ;
    }
    return ('<link rel="'+rel+'" '+sizes+' href="'+href+'">\n') ;
} ;

theme.cssLink = function(css) {
    return ('<link rel="stylesheet" href="'+css+'" />\n') ;
} ;

theme.favicon = function(link, type) {
    type = type || 'x-icon' ;
    return ('<link rel="shortcut icon" type="image/'+type+'" href="'+link+'" />\n') ;
}

theme.personal = function(personal) {
    personal.name = personal.name || 'NAME' ;
    personal.tagLine = personal.tagLine || 'TAG LINE' ;
    personal.intro = personal.intro || 'Hi, my name is' ; 
    return ('<section id="personal">\n\
                <div class="container">\n\
                    <div class="row">\n\
                        <div class="col-md-6 col-lg-4 col-sm-12">\n\
                             '+personal.intro+'<br>\n\
                             '+personal.name+'<br>\n\
                             '+personal.tagLine+'<br><br><br><br>\n\
                        </div>\n\
                    </div>\n\
                </div>\n\
             </section>\n') ;
} ;

theme.about = function(a) {
    a.intro = a.intro || 'INTRO' ;
    a.name = a.name || 'NAME' ;
    a.email = a.email || 'email@gmail.com' ; 
    a.phone = a.phone || '123-456-7890' ;
    a.resume = a.resume || '#contact' ; 
    a.location = a.location || 'LOCATION' ;
    a.img = a.img || 'http://placehold.it/1671x800' ;
    return ('\n\
             <section id="about" style="background-image:url(\''+a.img+'\');">\n\
                 <div class="container">\n\
                     <div class="row">\n\
                         <div class="col-md-6 col-lg-4 col-sm-12">\n\
                             <span>About Me</span>\n\
                             <p>'+a.intro+'</p>\n\
                             <ul>\n\
                                 <li><span>Name:</span>'+a.name+'</li>\n\
                                 <li><span>Email:</span><a href="mailto:'+a.email+'">'+a.email+'</a></li>\n\
                                 <li><span>Phone:</span>'+a.phone+'</li>\n\
                                 <li><span>Home:</span>'+a.location+'</li>\n\
                             </ul>\n\
                             <a href="'+a.resume+'">Request Resume</a>\n\
                         </div>\n\
                     </div>\n\
                 </div>\n\
             </section>\n'
    ) ;
} ;

theme.blog = function(feed) {
    feed = feed || [] ;
    var posts = feed.map(function(post) {
        return ('<a href="'+post.link+'">'+post.title+'</a>') ;
    }) ;
    return ('\n\
            <section id="blog">\n\
                <div class="container">\n\
                    <div class="row">\n\
                        <div class="col-md-6 col-lg-4 col-sm-12">\n\
                            ' + join(posts,'\n') + '\n\
                        </div>\n\
                    </div>\n\
                </div>\n\
            </section>\n') ;
} ;


theme.contact = function (contact) {
    contact = contact || {} ;
    contact.background = contact.background || 'http://placehold.it/1671x870' ;
    contact.address = contact.address ||  'ADDRESS' ;
    contact.email = contact.email || 'email@gmail.com' ;
    contact.action = contact.action || 'javascript:void(0)' ;
    contact.buttonColor = contact.buttonColor || 'dark' ;
    return ('\n\
             <section id="contact" style="background-image:url(\''+contact.background+'\');">\n\
                 <div class="container">\n\
                     <div class="row">\n\
                             <div class="col-md-6 col-sm-12">\n\
                                 <form id="personalcontactform" action="'+contact.action+'" method="post">\n\
                                     <br><input type="text" name="name" id="name" placeholder="* YOUR NAME"><br>\n\
                                     <input type="text" name="email" id="email" placeholder="* YOUR EMAIL"><br>\n\
                                     <textarea name="comment" id="comment" placeholder="YOUR MESSAGE"></textarea><br>\n\
                                     <button id="personal-contact-button" type="submit">Submit</button><br><br>\n\
                                 </form>\n\
                             </div>\n\
                         </div>\n\
                     </div>\n\
                 </div>\n\
             </section>\n'
    ) ; 
} ;


theme.headerLinks = function(title) {
    title = title || 'TITLE' ;
    return ('\n\
            <title>'+title+'</title>\n\
            <meta name="description" content="Resume '+title+'">\n\
            <meta name="keywords" content="resume">\n\
            <meta charset="utf-8">\n\
            <meta name="author" content="'+title+'">\n\
            <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1" />\n\
    ') ; 
} ;

theme.footer = function(footer) {
   footer = footer || {} ;
   return ('') ;
} ;


theme.lib = function(libs) {
    libs = libs || [] ;
    return (libs.map(function(lib) {
            return '<script type="text/javascript" src="'+lib+'"></script>\n' ;        
        }).join('')) ; 
} ;

theme.viewContainer = function (view,title) {
    title = title || '' ;
    console.log('viewContainer -----------------') ;
    console.log(view) ;
    var output = (theme.html(
                  theme.head(
                       theme.headerLinks(title) 
                  )
                + theme.body(
        
                            view
                        
                )
        )
    ) ;
    console.log(output) ;
    return output ;
} ;

module.exports = theme ;

Comments (1)

  1. Kelvin Ji

    SyntaxError: Identifier 'COUNTER_MAX' has already been declared

    at Object.<anonymous> (/Users/kelvinji/mitnick/study/node/SAM/nodeSample/about.js:1:11)

    at Module._compile (module.js:413:34)

    at Object.Module._extensions..js (module.js:422:10)

    at Module.load (module.js:357:32)

    at Function.Module._load (module.js:314:12)

    at Function.Module.runMain (module.js:447:10)

    at startup (node.js:141:18) at node.js:933:3