var collection_json = require('collection_json') , pg = require('pg').native , _ = require('underscore'); var now='2000-01-01'; function mapRow(row) { var data = _.map(row, function(value, key) { return {name: key, value: value}; }); return { data: data }; } exports.departments = function(req, res){ pg.connect(process.env.DATABASE_URL, function(err, client) { if(err) throw err; var departments = []; client.query('SELECT dept_no, dept_name FROM departments'). on('row', function(row) { departments.push(row); }). on('end', function() { client.end(); res.render('departments', { title: 'Departments', departments: departments }); }); }); }; exports.department = function(req, res){ pg.connect(process.env.DATABASE_URL, function(err, client) { if(err) throw err; var dept_no = req.params.dept_no; var employees = []; // TODO: // TODO: Add dept_name to view // TODO: Add manager as a link client.query('SELECT employees.* FROM employees, dept_emp WHERE employees.emp_no=dept_emp.emp_no AND dept_emp.dept_no=$1 AND dept_emp.to_date > now() AND now() > dept_emp.from_date', [ dept_no ]). on('row', function(row) { employees.push(row); }). on('end', function() { client.end(); if(req.accepts('application/vnd.collection+json')) { var object = collection_json.fromObject({}); res.contentType('application/vnd.collection+json'); res.send(object); } else res.render('department', { title: 'Department ' + dept_no, employees: employees }); }); }); }; exports.employee = function(req, res){ pg.connect(process.env.DATABASE_URL, function(err, client) { if(err) throw err; var emp_no = req.params.emp_no; var employee; client.query('SELECT * FROM employees WHERE employees.emp_no=$1', [ emp_no ]). on('row', function(row) { employee = row; }). on('end', function() { client.end(); if(req.accepts('application/vnd.collection+json')) { var items = [ mapRow(employee) ]; var object = collection_json.fromObject({collection: {items: items}}); res.contentType('application/vnd.collection+json'); res.send(JSON.stringify(object), 200); } else res.render('employee', { title: 'Employee ' + emp_no, employee: employee }); }); }); };