npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

objectize

v1.0.8

Published

Objectize is an easy-to-use and intelligent object mapping library for Node.

Downloads

6

Readme

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.