Skip to content

Instantly share code, notes, and snippets.

@elimence
Created May 29, 2014 22:05
Show Gist options
  • Save elimence/61423e0834912da307d3 to your computer and use it in GitHub Desktop.
Save elimence/61423e0834912da307d3 to your computer and use it in GitHub Desktop.
/**
* Parse Employee Data in CSV
* CAUTION : Do not attempt to understand this code!!!
**/
var csv = require('fast-csv')
, fs = require('fs')
, Q = require('q');
// get entity classes;
var ObjectID = require( 'mongoose' ).Types.ObjectId
, Company = require( '../entities/company' )
, Employee = require( '../entities/employee' )
, Salary = require( '../entities/salary' )
, Group = require( '../entities/group' )
, events = require( 'events' );
/**
* EmployeeParser will emit the following events
* 'error' -> when an exception is caught
* 'partial' -> upon failure to create all employees
* 'completed' -> upon successfull creation of all employees
**/
var EmployeeParser = function(){
// call event emitter constructor on EmployeeParser instance
events.EventEmitter.call( this );
// provision needed persistent data structures
this.__empList = [];
this.__failList = [];
}
// make EmployeeParser inherit from EventEmitter
require( 'util' ).inherits( EmployeeParser, events.EventEmitter );
EmployeeParser.prototype.createEmployees = function( csvFile ) {
// preserve object ref
var _this = this;
csv
.fromPath ( csvFile, { headers: true, ignoreEmpty: true, trim: true })
.validate ( _this.protocols.isValid )
.transform( _this.protocols.transform )
.on( 'data-invalid', _this.protocols.crash )
.on( 'record', _this.protocols.addEmp )
.on( 'end', _this.protocols.finish );
};
EmployeeParser.prototype.instance = {
sam : [],
ako : []
};
EmployeeParser.prototype.protocols = {
crash : function( invalidEmp ){
// employee data is invalid
// add row number to failList array
console.log( 'crash protocol initiated' );
this.ako.push( invalidEmp );
},
addEmp : function( empObj ){
// push emp into employee array
console.log( 'addEmp protocol initiated' );
console.log( 'this : ', this, ' - __empList : ', this.sam );
this.sam.push( empObj );
},
finish : function(){
// parsing completed
// emit 'completed' or 'partial'
// depending on whether failList is empty or not
console.log( 'finish protocol initiated' );
this.emit( 'completed', this.sam );
},
isValid : function( empData ){
// check if employee data is valid
// by testing for all required fields
console.log( 'isValid protocol initiated' );
var dataIsValid = true;
if( empData )
return dataIsValid;
},
transform : function( empData ){
// create employee object here
console.log( 'transform protocol initiated' );
return empData;
}
};
module.exports = EmployeeParser;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment