Research
Security News
Malicious npm Packages Inject SSH Backdoors via Typosquatted Libraries
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
node-entity
Advanced tools
An Entity is a high level business unit. Entities are supersets of models and resources. They are persistent storage agnostic and provide a normalized CRUD API with which your consuming services can perform business logic actions.
The Entity Object on itself is nothing but an extension of EventEmitter
. It can be easily extended to create the Interfaces and base classes from where your business logic entities can inherit.
Entities come with a normalized CRUD interface which plugs into [now] two ORM packages, Mongoose and Sequelize.
npm install node-entity --save
Entity uses the Cip package for inheritance, it implements the pseudo-classical inheritance pattern packed in a convenient and easy to use API.
The extend()
method is the basic tool for extending, it accepts a constructor.
var entity = require('node-entity');
var EntityChild = entity.extend(function() {
this.a = 1;
});
var EntityGrandChild = EntityChild.extend();
var EntityGreatGrandChild = EntityGrandChild.extend(function() {
this.b = 2;
});
var greatGrandChild = new EntityGreatGrandChild();
greatGrandChild.a === 1; // true
greatGrandChild.b === 2; // true
Read more about extend() at Cip's documentation.
Use the extendSingleton()
method to create singleton constructors, use the getInstance()
method to always get the same exact instance of the entity.
var entity = require('entity');
var UserEntity = entity.extendSingleton(function() {});
/* ... */
var userEnt = UserEntity.getInstance();
While the use of singletons has been fairly criticized, it is our view that in modern day web applications, the instance role has moved up to the node process. Your web application will naturally run on multiple cores (instances) and thus each instance is a single unit in the whole that comprises your web service. Entities need to emit and listen to local events, PubSub, create Jobs, send email and generally have bindings to other services (RPC, AWS, whatnot).
Those events, PubSub etc have a lifetime equal to the runtime of the core the application is running on. This requires for a single entity to exist and manage all those bindings, applying the business logic and performing the required high level operations.
The current implementation offers a normalized CRUD Interface with a selected set of operations. The purpose of having a normalized interface is to decouple the business logic from storage, models. ORM Adaptors implement the CRUD Interface giving you a vast array of options for the underlying persistent storage. As mentioned above, currently two ORM packages are supported, Mongoose and Sequelize. This pretty much covers all the popular databases like mongodb, Postgres, MySQL, Redis, SQLite and MariaDB.
The CRUD Interface offers the following primitive operations:
These primitives will transparently adapt to the most optimized operations on the ORM of your choosing and guarantee the outcome will always be the same no matter the underlying ORM.
All primitive methods offer Before/After/Last hooks and return a Promise to determine resolution.
Object
The Data Object representing the Entity you wish created.Object
The newly created item, in the type of the underlying ORM.The create()
method will create a new item, you need to provide an Object containing key/value pairs.
entity.create({name: 'thanasis'})
.then(function(document) {
document.name === 'thanasis'; // true
})
.catch(function(error) {
// deal with error.
});
Check out the entity.create()
tests
Object|string
Optional A query or an id.Array.<Object>
An array of documents.The read()
method will query for items. If the query argument is omitted, all the items will be returned. If the query argument is an Object, it will be passed as is to the underlying ORM. Entity guarantees that key/value type queries will work and will also transport any idiomatic ORM query types.
entity.read()
.then(function(documents) {
// All documents
});
entity.read({networkId: '47'})
.then(function(documents) {
// All documents whose "networkId" equals 47
});
Any additional key/value pairs you add to your query will be added with the AND
operator.
The query for the read()
method supports any of the gt, gte, lt, lte, ne, in
by using an Object literal as the value for the attribute you want to query:
entity.read({
name: 'sam',
age: {
gt: 8
},
attr3: {
lte: 10
}
});
gt
Greater Than, expects a numerical value.gte
Greater Than Equals, expects a numerical value.lt
Less Than, expects a numerical value.lt
Less Than Equals, expects a numerical value.ne
Not Equal, expects a numerical value.in
Query a Set of items, expects an array of values: {age: {in: [10,11,12]}}
, uses OR for all the items defined.and
Query a Set of items, expects an array of values: {age: {and: [10,11,12]}}
, uses AND for all the items defined, only applies to mongoose adapter and more specifically to attributes that are of type array (i.e relation references).Check out the entity.read()
tests
Object|string
A query or an id, required.Object
A single Document.The readOne()
method guarantees that you will get one and only one item. It is the method intended to be used by single item views. The query argument has the same attributes as read()
.
entity.read({name: 'thanasis'})
.then(function(document) {
document.name === 'thanasis'; // true
});
entity.read('42')
.then(function(document) {
document.id === '42'; // true
});
Object|string|null
A query or an id, if null
will fetch all.number
Starting position.number
Number of items to fetch.Array.<Object>
An array of Documents.Will fetch the items based on query, limiting the results by the offset and limit defined. The query argument shares the same attributes as read()
, if null
all the items will be fetched.
entity.readLimit(null, 0, 10)
.then(function(documents) {
// fetched the first 10 items
});
entity.readLimit({networkId: '42'}, 10, 10)
.then(function(documents) {
// fetched records whose networkId equels '42
// And started from the 10th item,
// limiting the total records to 10
});
Object|string
A query or an id, required.Object
An Object with key/value pairs to update.Object=
The updated document of Mongoose ORM is used or nothing if Sequelize.Will perform an update operation on an item or set of item as defined by the query. The query argument can be a single id or an Object with key/value pairs.
entity.update('99', {name: 'John')
.then(function(document) {
document.name === 'John'; // true only for Mongoose
});
entity.update({networkId: '42'}, {isActive: false})
.then(function(documents) {
// deactive all items with network id that equals 42
});
Check out the entity.update()
tests
Object|string
A query or an id, required.Will perform an delete operation as defined by the query. The query argument can be a single id or an Object with key/value pairs.
entity.delete('99')
.then(function() {
// job done
});
entity.delete({networkId: '42'})
.then(function() {
// all gone
});
Check out the entity.delete()
tests
Object|string
Optional A query or an id, if omitted all items will be count.number
The count.Will perform a count operation as defined by the query. The query argument can be a single id or an Object with key/value pairs, if empty it will count all the items.
entity.count()
.then(function(count) {
typeof count === 'number'; // true, all the items.
});
entity.count({networkId: '42'})
.then(function() {
typeof count === 'number'; // true
});
Check out the entity.count()
tests
Every CRUD operation offers Before/After/Last hooks courtesy of Middlewarify. Each middleware will receive the same exact arguments. To pass control to the next middleware you need to return a promise that conforms to the Promises/A+ spec.
// a middleware with synchronous resolution
entity.create.before(function(data){
if (!data.name) {
throw new TypeError('No go my friend');
}
});
// then...
entity.create({}).then(function(document) {
// you'll never get here
}, function(err) {
err instanceof Error; // true
err.message === 'No go my friend'; // true
});
An Asynchronous middleware
// a middleware with asynchronous resolution
entity.create.before(function(data){
return somepackage.promise(function(resolve, reject) {
// perform an async op
readTheStars(function(err, omen) {
if (err) { return reject(err); }
if (omen === 'thou shall not pass') {
reject('Meh');
} else {
resolve();
}
});
});
});
The two currently available adaptors are available through these properties of the entity module
entity.Mongoose
For the Mongoose ORMentity.Sequelize
For the Sequelize ORMAll adaptors expose the setModel()
method. Before that method is successfully invoked all CRUD operations will fail, the Model required is an instantiated model of each respective ORM.
models/user.model.js
var mongoose = require('mongoose');
var userModel = module.exports = {};
userModel.schema = new mongoose.Schema({
name: {type: String, trim: true, required: true},
_isActive: {type: Boolean, required: true, default: true},
});
// This module now exposes the Mongoose
// User model on the "Model" property
userModel.Model = mongoose.model('user', userModel.schema);
entities/user.ent.js
var EntityMongoose = require('entity').Mongoose;
var UserModel = require('../models/user.model');
var UserEntity = module.exports = EntityMongoose.extend(function(){
// pass the Mongoose User Model
this.setModel(UserModel.Model);
});
models/user.model.js
var Sequelize = require('sequelize');
// typically you have this in another module
var seqInstance = new Sequelize(
'database',
'postgres',
'',
{
host: '127.0.0.1',
port: '5432',
dialect: 'postgres',
logging: false,
}
);
var userModel = module.exports = {};
// This module now exposes the Sequelize
// User model on the "Model" property
userModel.Model = seqInstance.define('user', {
name: {type: Sequelize.STRING, allowNull: false},
_isActive: {type: Sequelize.BOOLEAN, allowNull: false, defaultValue: true},
});
entities/user.ent.js
var EntitySequelize = require('entity').Sequelize;
var UserModel = require('../models/user.model');
var UserEntity = module.exports = EntitySequelize.extend(function(){
// pass the Sequelize User Model
this.setModel(UserModel.Model);
});
That was it, from here on, irrespective of adaptor and ORM, you can instantiate a new entity or use the singleton to perform CRUD operations.
controllers/user.ctrl.js
var BaseController = require('./base-controller.js');
var userEnt = require('../entities/user.ent').getInstance();
// The BaseController uses the "cip" package for inheritance
var UserCtrl = module.exports = BaseController.extend();
UserCtrl.prototype.createNew = function(req, res) {
// pass the submited parameters
// validation happens on the model.
userEnt.create(req.body)
.then(function(udo){
// send the User Data Object
res.json(udo);
}, function(error) {
res.json(501, error);
});
};
The base entity class inherits from Node's standard EventEmitter. The CRUD interface provides 3 convenient events that get triggered after each corresponding operation and all its' middleware have finished invocation.
create
Triggers after a create OP finished, arguments:
Object
The data provided by the user to create the record.Object
The result as provided by the underlying ORM.update
Triggers after an update OP finished, arguments:
Object|string
The query used to define which record to update.delete
Triggers after a delete OP finished, arguments:
Object|string
The query used to define which record to delete.string
An attempt to provide the ID of the deleted record.Example:
var EntitySequelize = require('entity').Sequelize;
var UserModel = require('../models/user.model');
var UserEntity = module.exports = Entity.Sequelize.extend(function(){
// pass the Sequelize User Model
this.setModel(UserModel.Model);
});
/* ... */
var userEntity = UserEntity.getInstance();
userEntity.on('create', function(data, result) {/* ... */});
userEntity.on('update', function(query) {/* ... */});
userEntity.on('delete', function(query, id) {/* ... */});
Entities offer a schema API. CRUD Adaptors will automatically translate the underlying ORM's schema to a normalized mschema compliant schema.
mschema
The normalized schema.getSchema()
is synchronous, it will return a key/value dictionary where value will always contain the following properties
string
The name of the attribute.string
The full path of the attribute (used by document stores)boolean
A boolean that determines View visibility.string
An mschema type, possible types are:
string
number
object
boolean
any
var userModel = require('../entities/user.ent').getInstance();
userModel.getSchema();
Outputs:
{
"name": {
"name": "name",
"path": "name",
"canShow": true,
"type": "string"
},
"_isActive": {
"name": "_isActive",
"path": "_isActive",
"canShow": false,
"type": "boolean"
}
}
The path
property will be useful when you use nested Objects in your Schema, something only possible with the Mongoose adaptor. So if the address is an object that contains the attribute city
here's how that would look like:
{
"address.city": {
"name": "city",
"path": "address.city",
"canShow": true,
"type": "string"
}
}
Check out the CRUD Schema method tests
Object|string
The name of the attribute to add or an Object with key/value pairs.Object|string
The type or an Object with key/value pairs representing the attributes values.The addSchema()
method allows you to add attributes to the entity's schema. Any of the following combinations are acceptable.
entity.addSchema('name', 'string');
entity.addSchema('name', {type: 'string', cahShow: false});
entity.addSchema({
name: 'string'
});
entity.addSchema({
name: {
type: 'string'
}
});
string
The name of the attribute to remove.Remove an attribute from the schema.
entity.remSchema('name');
Check out the Schema basic methods tests
string
The name of the attribute to sort.string
The order of sorting. Either 'ASC' or 'DESC'.Sort attributed.
this.sort('createdAt', 'DESC');
Will prepopulate related models on all operations that return item or items.
Available only for the Mongoose adapter, the arguments of this method will be provided to the Mongoose populate method.
// Load the linked User Data Object when fetching records from this entity.
this.eagerLoad('user');
Normalize is a middleware only available for the Mongoose adaptor and it's main purpose is to provide a normalized way of data representation. More specifically the normalize method will:
item.toObject({getters: true})
id
will be available._id
and __v
.The normalize()
should be added manually as a middleware on the after()
hook of every operation!
// A normal read operation
entity.read()
.then(function(results) {
console.log(results);
// [{
// _id: '55c9e772856763a729654b99',
// __v: 0,
// name: 'one',
// }]
});
// Now add the normalize middleware
entity.read.after(entity.normalize);
entity.read()
.then(function(results) {
console.log(results);
// [{
// id: '55c9e772856763a729654b99',
// name: 'one',
// }]
});
and
operator for mongoose queries, allows for explicit querying of array attributes.^4.0.0
.between
selector.gt, gte, lt, lte, ne
getSchema()
.Copyright ©2015 Thanasis Polychronakis
Licensed under the MIT License
FAQs
The MVCe implementation for Node.js
The npm package node-entity receives a total of 10 weekly downloads. As such, node-entity popularity was classified as not popular.
We found that node-entity demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.