objectize

1.0.8 • Public • Published

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

Name How to Description
Required this.required = {} required param keys and value type are assigned here
Optional this.optional = {} optional param keys and value type are assigned here
Defaults this.defaults = {} initialization values will assigned here, a request data will replace the default value that with the same param key if duplicated
Privilege this.privilege = {} same as defaults fields, except that no request data can replace privilege data
Reference this.reference = {} Reference Field is required if CLONE, SHA1, MD5, DATE Model.Types is used
Functions this.functions = {} Functions Field is required if TYPE.FUNCTION is used.

Types

Name Type Description
BINARY TYPE.BINARY Multipart images, document files, a temporary file path will be returned once the file is uploaded
NUMBER TYPE.NUMBER Either float or integer type value is accepted
INTEGER TYPE.INTEGER Any integer-type value
FLOAT TYPE.FLOAT Any float-type value
STRING TYPE.STRING Any string-type value
EMAIL TYPE.EMAIL Any email format string
MD5 TYPE.MD5 Mapper will automatically convert input string to md5 string
SHA1 TYPE.SHA1 Mapper will automatically convert input string to sha1 string
BOOLEAN TYPE.BOOLEAN Only bool-type value (true, 'true', false, 'false')
ARRAY TYPE.ARRAY Array-type data (eg. [1,2,'testing'])
OBJECT TYPE.OBJECT Object-type data
JSON TYPE.JSON JSON data
GENERATE TYPE.GENERATE Mapper will automatically generate an uuid string to the assigned field
NOW TYPE.NOW Mapper will automatically generate a current-time Date Object
DATE TYPE.DATE Mapper will automatically generate a Date Object by (time+/-n[u]) format string For example, time+2d (current time + 2 days), time-5m (current time - 5 mins), time+1s (current time + 1 sec)
IP TYPE.IP Mapper will automatically assign user/guest IP to the field
CLONE TYPE.CLONE Mapper will clone the reference's data to the assigned field
FUNCTION TYPE.FUNCTION Mapper 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.

Package Sidebar

Install

npm i objectize

Weekly Downloads

8

Version

1.0.8

License

Apache-2.0

Last publish

Collaborators

  • samuelngs