1.0.8 • Published 10 years ago

objectize v1.0.8

Weekly downloads
2
License
Apache-2.0
Repository
github
Last release
10 years ago

Introduction

Objectize is an easy-to-use and intelligent object mapping library for Node. Objectize can automatically maps HTTP(s) request data including query, parameters and body to an object.

  • Objectize interface aims to require very minimal code to achieve the most common cases, basic installation and configuration less to only two steps
  • Integrate perfectly with Express.js framework
  • Organize HTTP request data (Cookie, IP Address, Params)

Installation

npm install objectize

Request library (without Express Framework)

var objectize = require('objectize')();

With Express Framework

var objectize = require('objectize')(app);

Features

  1. Simpler Code, a easy-to-use data mapping API(s)
  2. Automatically handles GET query, parameters, POST body/multipart data
  3. Easy to integrate with Web Frameworks
  4. Easy to extend and reuse
  5. Model (Data Mapping) structure is flexible
  6. Filtering unnecessary request data by model-mapper class

Sample Code

File: sample.js

var TYPE = require('objectize')().TYPES;
var model = function model() {
    this.required = {
        name					: TYPE.STRING,
        uid						: TYPE.SHA1
    }
    this.reference = {
    	uid						: 'name'
    }
};
module.exports = model;

File: test.js (Integrated with Express.JS Framework)

objectize.use('/:name', function(req, res, args, end){
	res.send(objectize.map(args, sample));
	end();
});

Example: http://127.0.0.1:5000/john

{
    "name": "John",
    "uid": "06c884c70d3d783563781f20fe9849ef916480d9"
}

As mentioned, Objectize can automatically filter unnecessary request data. http://127.0.0.1:5000/john?lastname=Eaton request will return the same result because the model doesn't have lastname field.

Model

Sections

NameHow toDescription
Requiredthis.required = {}required param keys and value type are assigned here
Optionalthis.optional = {}optional param keys and value type are assigned here
Defaultsthis.defaults = {}initialization values will assigned here, a request data will replace the default value that with the same param key if duplicated
Privilegethis.privilege = {}same as defaults fields, except that no request data can replace privilege data
Referencethis.reference = {}Reference Field is required if CLONE, SHA1, MD5, DATE Model.Types is used
Functionsthis.functions = {}Functions Field is required if TYPE.FUNCTION is used.

Types

NameTypeDescription
BINARYTYPE.BINARYMultipart images, document files, a temporary file path will be returned once the file is uploaded
NUMBERTYPE.NUMBEREither float or integer type value is accepted
INTEGERTYPE.INTEGERAny integer-type value
FLOATTYPE.FLOATAny float-type value
STRINGTYPE.STRINGAny string-type value
EMAILTYPE.EMAILAny email format string
MD5TYPE.MD5Mapper will automatically convert input string to md5 string
SHA1TYPE.SHA1Mapper will automatically convert input string to sha1 string
BOOLEANTYPE.BOOLEANOnly bool-type value (true, 'true', false, 'false')
ARRAYTYPE.ARRAYArray-type data (eg. 1,2,'testing')
OBJECTTYPE.OBJECTObject-type data
JSONTYPE.JSONJSON data
GENERATETYPE.GENERATEMapper will automatically generate an uuid string to the assigned field
NOWTYPE.NOWMapper will automatically generate a current-time Date Object
DATETYPE.DATEMapper will automatically generate a Date Object by (time+/-nu) format string For example, time+2d (current time + 2 days), time-5m (current time - 5 mins), time+1s (current time + 1 sec)
IPTYPE.IPMapper will automatically assign user/guest IP to the field
CLONETYPE.CLONEMapper will clone the reference's data to the assigned field
FUNCTIONTYPE.FUNCTIONMapper will retrieve the return value of the function

Advanced

Defaults and Privilege

With Objectize, you can assign a value to defaults / privilege section by a function.

this.defaults = {
	currentDateTime: function() {
		return new Date();
	}
}

Required and Optional (Reference)

Using reference system is simple. For an example, if you want to clone a value in different name field, you can do the following

this.required = {
	name: TYPE.STRING,
	copyname: TYPE.CLONE,
}
this.reference = {
	copyname: 'name'
}

The sole thing you require to do is assign 'copyname' with TYPE.CLONE type and determine the reference key to field 'name' in the reference section.

{
    "name": "John",
    "copyname": "John"
}

Same concept as well applied to SHA1, MD5, DATE Model Types.

Required and Optional (Function)

As same as defaults / privilege function but with more features.

this.required = {
	firstname: TYPE.STRING,
	lastname: TYPE.STRING,
	reg_date: TYPE.FUNCTION
}
this.functions = {
	reg_date: function() {
		return new Date().getTime();
	}
}

The output data will look like this.

{
    "firstname": "John",
    "lastname": "Raymond",
    "reg_date": 2002349203
}

For more advanced usage, you can do the following

this.required = {
	firstname: TYPE.STRING,
	lastname: TYPE.STRING,
	reg_date: TYPE.FUNCTION,
	fullname: TYPE.FUNCTION
}
this.functions = {
	reg_date: function() {
		return new Date().getTime();
	},
	fullname:['firstname', 'lastname', function(firstname, lastname) {
		return firstname + ' ' + lastname;
	}]
}

The Mapper will automatically grab the firstname, and lastname to the function. keys, function(args)

{
    "firstname": "John",
    "lastname": "Raymond",
    "reg_date": 2002349203,
    "fullname": "John Raymond"
}

Why is Objectize so useful?

Objectize can immediately turns a input data to a valuable and usable data that could be stored in database. Below are two solutions of user register API that store user data to RethinkDB NoSQL.

Solution 1: Without Objectize

app.post('/signup', function(req, res) {
	async.parallel([
		function(callback) {
			var body = '';
			req.on('data', function(chunk) {
				body += chunk.toString();
			});
			req.on('end', function() {
				callback(null, querystring.parse(body) || {});
			});
		}
	], 
	function(err, results) {
		var params = results[0];
		var data = {};
		var emailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
		var sendError = function() {
			res.send(JSON.stringify({success:false}));
		}
		var sha1 = function(str) {
			var shasum = crypto.createHash('sha1');
			shasum.update(str);
			return shasum.digest('hex');
		}
		if (params.email && emailRegex.test(params.email)) {
			data.email = params.email;
			data.userid = sha1(params.email);
		} else {
			sendError();
		}
		if (params.password && params.password.length > 0) {
			data.password = params.password;
		} else {
			sendError();
		}
		data.reg_date = new Date();
		r.table('account').insert(data).run().then(function(result) {
			data.success = true;
			res.send(JSON.stringify(data));
		});
	});
	
});

Solution 2: With Objectize

signup.js (model)

var model = function model() {
    this.required = {
        email		: TYPE.EMAIL,
        userid		: TYPE.SHA1,
        password	: TYPE.STRING,
        reg_date	: TYPE.NOW
    }
    this.reference = {
    	userid		: 'email'
    }
};
module.exports = model;

app.js

objectize.post('/signup', function(req, res, args, end) {
	var data = objectize.map(args, signup) || this.drop({success:false});
	this.do(function() {
		r.table('account').insert(data).run().then(function(result) {
			data.success = true;
			res.send(data);
		});	
	});
	end();
});

Contributing

You want to contribute? Great! That would be awesome! Pull requests are always welcome.

1.0.8

10 years ago

1.0.7

10 years ago

1.0.6

10 years ago

1.0.5

10 years ago

1.0.4

10 years ago

1.0.3

10 years ago

1.0.2

10 years ago

1.0.1

10 years ago

1.0.0

10 years ago