Class: Hunt

Hunt

new Hunt(config)

HuntJS framework module

Parameters:
Name Type Description
config config

key-value object with settings

Classes

errorResponses

Members

app

ExpressJS application instance

async :Object

Embedded npm module of async of 1.2.1 version for better workflow

Type:
  • Object

config :config

Object that represents current config object of HuntJS application

Type:

express

ExpressJS framework constructor with static methods exposed, for example core.express.static is middleware used for serving css, client side javascripts, images.

http :Object

Embedded nodejs http module, that is used by socket.io and http server.

Type:
  • Object

httpServer

http server class, used by socket.io and expressJS objects

See:

io

Ready to use http://socket.io object with passport.js integration

model :model

Class to hold data models of Hunt application, they are injected into request object of controller.

Type:
See:

mongoConnection

Mongoose connection object

See:

mongoose

Mongoose object, used for object relation maping to mongo database Official Mongoose Documentation

Q :Object

Embedded npm module of Q of 1.4.1 version for better workflow

Type:
  • Object

redisClient

Ready to use redis client with connection parameters taken from config object. Additional info on redis client

Sequilize

SQL database object relational mapper constructor, that is used only when config option of sequilizeUrl is defined.

See:

sessionStorage

validator :Object

Embedded npm module of validator for better workflow

Type:
  • Object

version :string

Current HuntJS version

Type:
  • string

Methods

cachingMiddleware(ttlopt)

Generate caching middleware for this route

Parameters:
Name Type Attributes Default Description
ttl number | null <optional>
60

cache invalidation time, default is 60 seconds

Example
Hunt.extendRoutes(core){
 core.app.use('/cacheForTenSeconds', Hunt.cachingMiddleware(10000));
 core.app.use('/cacheForSixtySeconds', Hunt.cachingMiddleware(60000));
 core.app.get('*', function(request, response){
   response.send('Current time is '+new Date());
 });
}

createRedisClient()

Creates redis client

See:

decrypt(text, secretopt) → {string}

Decrypt the given text using config.SECRET by default or using the custom given secret

Parameters:
Name Type Attributes Description
text string

text to decrypt

secret string <optional>

secret to use for decryption, if absent, the value of config.secret is used

See:
Returns:
  • decrypted string
Type
string

doHttpError(response, statusCode, message)

Helper to make erroneous html response in controller.

Parameters:
Name Type Description
response Response
statusCode Number
message string

emit(eventName, payload, additionalOptionalPayloadopt, oneMoreAdditionalOptionalPayloadopt, evenOneMoreAdditionalOptionalPayloadopt)

Makes Hunt emit an event. Returns true if event had listeners, false otherwise. Hunt object is a standard nodejs event emitter object , so it supports all event emitter methods. Also Hunt object possess the functions of EventEmitter2 The default delimiter is ":"

Parameters:
Name Type Attributes Description
eventName string | Array.<string>
payload object
additionalOptionalPayload object <optional>
oneMoreAdditionalOptionalPayload object <optional>
evenOneMoreAdditionalOptionalPayload object <optional>
Returns:

boolean

Example
var hunt = require('./index.js')();
hunt.extendCore('a', 'b');
console.log('hunt.a=', hunt.a);

hunt.on('ping', function (msg, msg1) {
 console.log('+++ping+++', this.event, msg, msg1, '+++ping+++');
});

hunt.on('ping:2', function (msg, msg1) {
 console.log('+++ping:2+++', this.event, msg, msg1, '+++ping:2+++');
});

hunt.on('ping:*', function (msg, msg1) {
 console.log('+++ping:*+++', this.event, msg, msg1, '+++ping:*+++');
});


hunt.once('start', function (type) {
 console.log('Starting to send events...');
 hunt.emit(['ping', '2'], 'pong', 'lll');
});
hunt.startBackGround();

encrypt(text, secretopt) → {string}

Encrypt the given text by default or using the custom given secret

Parameters:
Name Type Attributes Description
text string

text to encrypt

secret string <optional>

secret to use for encryption, if absent, the value of config#secret is used

See:
Returns:
  • encrypted string
Type
string

exportModelToRest(parameters)

Export models as REST api, exposed by current http server

Parameters:
Name Type Description
parameters ExportModelToRestParameters

for exporting model to REST interface properly

extendApp(environment, settingsFunction) → {Hunt}

Set expressJS application parameters - template engine, variables, locals template engines, locals and other settings. In code it is called after setting logging middleware and port.

Parameters:
Name Type Description
environment string | Array | null

application environment to use, can be something like 'development', ['development','staging'] or null

settingsFunction function

function(core){....}

Tutorials:
See:
Returns:

hunt object

Type
Hunt
Example
//example of setting template engine
    hunt.extendApp = function (core) {
      core.app.set('views', __dirname + '/views');
      core.app.set('view engine', 'ejs');
      core.app.set('layout', 'layout');
      core.app.enable('view cache');
      core.app.engine('ejs', require('ejs'));
    };

extendController(mountPoint, settingsFunction) → {Hunt}

Add custom router for expressjs application

Parameters:
Name Type Description
mountPoint string
settingsFunction function
Since:
  • 0.2.2
Tutorials:
See:
Returns:

hunt object

Type
Hunt
Example
hunt.extendController('/', function(core, router){
 router.get('/', function(request,response){
   response.render('index',{'title':'Hello!'});
 });
});
//this controller overwrites the first one!
hunt.extendController('/', function(core, router){
 router.get('/', function(request,response){
   response.render('index2',{'title':'Hello!'});
 });
});

extendCore(field, value) → {Hunt}

Inject public property to hunt core. If value is function, the value injected is result of value(hunt), else value injected is AS IS.

Parameters:
Name Type Description
field string

property name to assign to hunt.[fieldName]

value string | object | Date | Array | function

value to assign

Returns:

hunt object for functions chaining

Type
Hunt
Example
var Hunt = require('hunt')(configObj);

   //extending application core

   //assign value to field
   Hunt.extendCore('someVar', 42);

   //assign factory function to field and this field value
   //is result of this function
   Hunt.extendCore('someFuncToGetSomeVar', function (core) {
     return core.someVar;
   });

   //assign function to a core
   Hunt.extendCore('getSumWithSomeVar', function (core) {
     return function (a, b) {
       return a + b + core.someFuncToGetSomeVar;
     };
   });

   //Hunt core works after extending
   console.log('Sum of 2, 2 and 42 is ' + Hunt.getSumWithSomeVar(2, 2));

extendModel(modelName, modelConstructor) → {Hunt}

Inject public property with model object to hunt.model.

Parameters:
Name Type Description
modelName string

property name to assign to hunt.model[modelName]

modelConstructor function

factory function to generate model using Hunt kernel

See:
Returns:

hunt object

Type
Hunt
Example
//for mongoose model
   if (Hunt.config.enableMongoose) { //verify that we enabled mongoose
     Hunt.extendModel('Trophy', function (core) {
       var TrophySchema = new core.mongoose.Schema({
         'name': {type: String, unique: true},
         'scored': Boolean
       });

       TrophySchema.index({
         name: 1
       });
//this step is very important - bind mongoose model to current mongo database connection
// and assign it to collection in mongo database
       return core.mongoConnection.model('Trophy', TrophySchema);
      });
// So, this model is accessible by
// Hunt.model.Trophy
    };

//sequilize model
Hunt.extendModel('Planet', function (core) {
    var Planet = core.sequelize.define('Planet', {
      name: core.Sequelize.STRING //note that core.Sequilize != core.sequilize
    });
    return Planet;
  });

extendStrategy(Strategy) → {Hunt}

Add new passportJS strategy to application by adding them to Hunt.passport object All strategies have to redirect to /auth/success on success or /auth/failure

Parameters:
Name Type Description
Strategy object

object

Tutorials:
See:
Returns:

hunt object

Type
Hunt
Example
var HashStrategy = require('passport-hash').Strategy;
   //used for verify account by email
   exports.strategy = function (core) {
     return new HashStrategy(function (hash, done) {
       core.model.User.findOneByHuntKeyAndVerifyEmail(hash, function (err, userFound) {
         done(err, userFound);
       });
     });
   };

   exports.routes = function (core) {
     core.app.get('/auth/confirm/:hash', core.passport.authenticate('hash', {
       successRedirect: '/auth/success',
       failureRedirect: '/auth/failure'
     }));
   };

extendTelnet(command, callback) → {Hunt}

Adds new behavior to telnet server. The callback has 2 arguments, first one is core object, and second one is RAI client object

Parameters:
Name Type Description
command string

command name

callback function

function(core, client, payload){}

Since:
  • 0.0.18
Tutorials:
Returns:

hunt object

Type
Hunt
Example
hunt.extendTelnet('version', function(core, client){
     client.send('HuntJS version is '+core.version);
    });
    hunt.extendTelnet('echo', function(core, client, payload){
     client.send(payload);
    });

forceHttps()

Middleware to ensure that connection is done via HTTPS protocol only. If request is done via HTTP protocol, user is redirected to HTTPS on the same url. This middleware do nothing if application environment is not production

See:
  • config#env
Returns:

function(request,response,next)

injectCssFromDirectory(arrayOfPatterns)

Automatically load css files from directory and load in hunt.app.locals.css

Parameters:
Name Type Description
arrayOfPatterns String

array of patterns for css files to load.

Example
Hunt.injectCssFromDirectory(["public/custom/*.css","public/vendor/*.css"])

injectJsFromDirectory(arrayOfPatterns)

Automatically load client side javascript files from directory and load in hunt.app.locals.javascripts

Parameters:
Name Type Description
arrayOfPatterns String

array of patterns for css files to load.

Example
Hunt.injectJsFromDirectory(["public/custom/*.js","public/vendor/*.js"])

loadControllersFromDirectory(dirname)

Automatically load custom controllers from directory.

Parameters:
Name Type Description
dirname String

path to directoriy with controller files.

Example
```javascript
//file `controllers/something.controller.js
"use strict";
exports.mountpoint = '/';
exports.handler = function (core, router) {
  router.get('/', function(req,res){
    res.send('Doing something...');
  });
}

//file index.js - main entry point
hunt.loadControllersFromDirectory('./controllers');
hunt.startWebServer();
```

loadModelsFromDirectory(dirname)

Automatically load custom models from directory.

Parameters:
Name Type Description
dirname String

path to directoriy with model files.

See:
Example
//file `models/Trophy.model.js
'use strict';

 exports.modelName = 'Trophy';
 exports.mountPoints = ['/api/v1/trophy', '/api/v1/trophies'];
 exports.exportModel = true;
 exports.ownerId = 'author';

 exports.init = function (core) {
  var TrophySchema = new core.mongoose.Schema({
  //other model initialization code
  })
 };
//file index.js - main entry point
hunt.loadModelsFromDirectory('./models');
hunt.startWebServer();

many(eventName, howManyTimesToFire, listener) → {Hunt}

Adds a listener to the end of the listeners array for the specified event that will execute n times for the event before being removed. The listener is invoked only the first n times the event is fired, after which it is removed. Calls can be chained. Hunt object is a standard nodejs event emitter object , so it supports all event emitter methods. Also Hunt object possess the functions of EventEmitter2 The default delimiter is ":"

Parameters:
Name Type Description
eventName string
howManyTimesToFire Number
listener function
See:
Returns:
Type
Hunt
Example
hunt
     .once('start', function (params) {
       console.log('Hunt is started as '+params.type+' on port '+params.port);
     })
     .many('httpError', 1, console.error); //1 error is enough :-)

md5(str) → {string}

Decrypt the given text using config.SECRET by default or using the custom given secret

Parameters:
Name Type Description
str string

text to decrypt

Returns:
  • decrypted string
Type
string

multipart()

Return connect-multiparty middleware to parse uploaded data and populate request.files with data. For example, when we submit form like this

  <form action="/upload" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="file" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
   </form>

the request.files is dictionary like this:

 {
   file: {
        fieldName: 'file',
       originalFilename: 'Kate Moss.jpg',
       path: '/tmp/4235-1yw9ixo.jpg',
       size: 61030,
       name: 'Kate Moss.jpg',
       type: 'image/jpeg',
       headers: {
        'content-disposition': 'form-data; name="file"; filename="Kate Moss.jpg"',
        'content-type': 'image/jpeg'
     },
     ws: {
      _writableState: [Object],
      writable: true,
      domain: [Object],
      _events: [Object],
      _maxListeners: 10,
      path: '/tmp/4235-1yw9ixo.jpg',
      fd: null,
      flags: 'w',
      mode: 438,
      start: undefined,
      pos: undefined,
      bytesWritten: 61030,
      closed: true
      }
   }
 }

It is worth noting, that files are cleared after response is send to user!

Returns:

function(request,response,next)

offAny(payload, additionalOptionalPayloadopt, oneMoreAdditionalOptionalPayloadopt, evenOneMoreAdditionalOptionalPayloadopt)

Removes the listener that will be fired when any event is emitted. Hunt object is a standard nodejs event emitter object , so it supports all event emitter methods. Also Hunt object possess the functions of EventEmitter2

Parameters:
Name Type Attributes Description
payload object
additionalOptionalPayload object <optional>
oneMoreAdditionalOptionalPayload object <optional>
evenOneMoreAdditionalOptionalPayload object <optional>
See:
Returns:

boolean

Example
function vortex(value1, value2) {
     console.log('All events trigger this. This is for you: ', value1, value2);
   }
   hunt.onAny(vortex);

   if (iHaveChangedMyMindToDoThis) {
     hunt.offAny(vortex);
   }

on(eventName, listener) → {Hunt}

Adds a listener to the end of the listeners array for the specified event. Calls can be chained. Hunt object is a standard nodejs event emitter object , so it supports all event emitter methods. Also Hunt object possess the functions of EventEmitter2 The default delimiter is ":"

Parameters:
Name Type Description
eventName string
listener function
See:
Returns:
Type
Hunt
Example
hunt
     .on('start', function (params) {
       console.log('Hunt is started as '+params.type+' on port '+params.port);
     })
     .on('httpError', console.error);

onAny(payload, additionalOptionalPayloadopt, oneMoreAdditionalOptionalPayloadopt, evenOneMoreAdditionalOptionalPayloadopt)

Adds a listener that will be fired when any event is emitted. Hunt object is a standard nodejs event emitter object , so it supports all event emitter methods. Also Hunt object possess the functions of EventEmitter2

Parameters:
Name Type Attributes Description
payload object
additionalOptionalPayload object <optional>
oneMoreAdditionalOptionalPayload object <optional>
evenOneMoreAdditionalOptionalPayload object <optional>
See:
Returns:

boolean

Example
function vortex(value1, value2) {
     console.log('All events trigger this. This is for you: ', value1, value2);
   }
   hunt.onAny(vortex);

   if (iHaveChangedMyMindToDoThis) {
     hunt.offAny(vortex);
   }

once(eventName, listener) → {Hunt}

Adds a one time listener for the event. This listener is invoked only the next time the event is fired, after which it is removed. Calls can be chained. Hunt object is a standard nodejs event emitter object , so it supports all event emitter methods. Also Hunt object possess the functions of EventEmitter2 The default delimiter is ":"

Parameters:
Name Type Description
eventName string
listener function
See:
Returns:
Type
Hunt

onSocketIoEvent(eventName, callback) → {Hunt}

Parameters:
Name Type Description
eventName string
callback function

function(payload, socket, function(error){...});

Since:
  • 0.2.0
Returns:

hunt object

Type
Hunt
Example
//client side code
<script>
var socket = io(); // TIP: io.connect() with no args does auto-discovery
socket.emit('message', 'I will find you!', function (data) {
  console.log(data); // data will be 'cool!'
});
socket.send('I will find you!', function (data) { //the same
  console.log(data); // data will be 'cool!'
});
</script>

//server side code
hunt.onSocketIoEvent('message', function(payload, socket, fn){
  console.log('Message recieved',payload);
  socket.emit('thanks','for the message');
  fn('cool!');
});

preload(modelName)

Middleware to load Mongoose model with id extracted from request.params[0] into request.preload Fires REST:collectionName:READ:itemId event if object can be shown to user.

Parameters:
Name Type Description
modelName string
See:
  • request#preload
Fires:
Returns:

function(request,response,next)

Example
hunt.extendRouter('/api/v1/trophy', function(core, router){
 router.get(/^\/([0-9a-fA-F]{24})\/isScored$/, core.preload('Trophy'), function(request, response){
   if(request.preload.canRead) {
     response.json({'scored':request.preload.model.scored});
   } else {
     response.sendStatus(403);
   }
 });
});

rack() → {string}

Generate really long random strings

Returns:

someReallyHardRandomStringThatMakesHackersRealySad

Type
string

removeListener(eventName, listener) → {Hunt}

Hunt object is a standard nodejs event emitter object , so it supports all event emitter methods. Also Hunt object possess the functions of EventEmitter2 Remove a listener from the listener array for the specified event. Caution: changes array indices in the listener array behind the listener. Calls can be chained.

Parameters:
Name Type Description
eventName string
listener function
Returns:

Hunt

Type
Hunt

sha512(str) → {string}

Make sha512 hash of string

Parameters:
Name Type Description
str string

text to decrypt

Returns:
  • decrypted string
Type
string

startBackGround()

Starts Hunt application as single threaded background application It have redis client and data models, event emitting system exposed. It makes Hunt to emit event of "start" with payload of {'type':'background'}

Fires:
Example
Hunt.startBackGround();

startBackGroundCluster(maxProcesses) → {Boolean}

Starts Hunt application as single threaded background application, that controls, by the means of cluster, other background applications. By default it spawns 1 process per CPU core.

Parameters:
Name Type Description
maxProcesses Number | null

maximal number of web server processes to spawn, default - 1 process per CPU core

Fires:
Returns:

true if this is master process, false if this is worker process.

Type
Boolean
Example
var numberOfProcessesToSpawn = 10;
   Hunt.startBackGroundCluster(numberOfProcessesToSpawn);

startCluster(parameters) → {Boolean}

Start Hunt as cluster. Parameters is object with 4 field -

  • web, background, telnet, 'port'. The values of web,background, telnet are number of child processes to spawn. The value of port is port number for web server processes to listen to. It is worth notice, that in this case telnet server listens on Hunt.config.port+1 port!
Parameters:
Name Type Description
parameters object

configuration parameters

To Do:
  • - make unit tests
Fires:
Returns:

true if this is master process, false if this is worker process.

Type
Boolean
Example
Hunt.startCluster({ 'web':1, 'background':1, 'telnet': 1 });
    Hunt.startCluster({ 'web':'max', 'port':80, 'address':'127.0.0.1' });
    Hunt.startCluster({ 'background':'max' });
    Hunt.startCluster({ 'telnet':max, 'port':25 });
    Hunt.startCluster({ 'web':'max', 'telnet':'max' }); //i strongly do not recommend doing this!

startTelnetCluster(port, maxProcesses) → {Boolean}

Starts hunt application as single threaded background application, that controls, by the means of nodejs embedded cluster, telnet server processes. By default it spawns 1 process per CPU core. It makes Hunt to emit event of "start" with payload of {'type':'background'} in master process, and events of "start" with payload of {'type':'telnet', 'port':25} in each of telnet server processes.

Parameters:
Name Type Description
port number | null

what port to use, if null - use port value from config

maxProcesses number | null

maximal number of web server processes to spawn, default - 1 process per CPU core

Fires:
Returns:

true if this is master process, false if this is worker process.

Type
Boolean
Example
Hunt.startTelnetCluster(25, 10000);

startTelnetServer(port, addressopt)

Start Hunt as single process telnet server

Parameters:
Name Type Attributes Default Description
port number | null

what port to use, if null - use port value from config

address string | null <optional>
"0.0.0.0"

address to listen on, if null - use address from config

Since:
  • 0.0.18
Tutorials:
Fires:
Example
Hunt.startTelnetServer(3003);

startWebCluster(port, maxProcesses) → {Boolean}

Starts hunt application as single threaded background application, that controls, by the means of nodejs embedded cluster, web server processes. By default it spawns 1 process per CPU core. It makes Hunt to emit event of "start" with payload of {'type':'background'} in master process, and events of "start" with payload of {'type':'webserver', 'port':80} in web server processes.

Parameters:
Name Type Description
port number | null

what port to use, if null - use port value from config

maxProcesses number | null

maximal number of web server processes to spawn, default - 1 process per CPU core

Tutorials:
Fires:
Returns:

true if this is master process, false if this is worker process.

Type
Boolean
Example
Hunt.startWebCluster(80, 10000);

startWebServer(port, address)

Starts Hunt application as single threaded web server It have redis client/models, expressJS application and event emitting system exposed. It makes Hunt to emit event of "start" with payload of {'type':'webserver', 'port':80}

Parameters:
Name Type Description
port number | null

what port to use, if null - use port value from config

address string | null

what address to bind to. Default is '0.0.0.0' - all IPv4 addresses. The address is populated from environment address of HUNTJS_ADDR

Tutorials:
Fires:
Example
Hunt.startWebServer(80);
    Hunt.startWebServer(80, '0.0.0.0');
    Hunt.startWebServer(80, 'fe80::7218:8bff:fe86:542b');

stop()

Stops the current application - close database connections, etc.

Events

broadcast

Broadcast message from core via socket.io to all webserver clients - both authorized users and non authorized site visitors

Type:
  • object
See:
  • Hunt#notify:sio
Example
core.emit('broadcast','Hello? Can you hear me? Jungle took him!');
//emits socket.io event of type `broadcast` with
//payload 'Hello? Can you hear me? Jungle took him!'

core.emit('broadcast', {type:'screamLoudly',message:'Hello? Can you hear me? Jungle took him!'});
//emits 2 socket.io events:

//the first one of type `broadcast` with
// {type:'screamLoudly',message:'Hello? Can you hear me? Jungle took him!'}
//for backward compatibility of huntjs 0.3.x branch

//and the second one of type `screamLoudly` with payload
//{type:'screamLoudly',message:'Hello? Can you hear me? Jungle took him!'}

start

Emitted when Hunt is started as telnet process

Type:
  • object
Properties:
Name Type Description
type string

with a value of string of 'telnet'

port string

with a value of string of port number

address string

with a value of address application is bound to

See:

start

Emitted when Hunt is started as webserver process

Type:
  • object
Properties:
Name Type Description
type string

with a value of string of 'webserver'

port number

with a value of port this application listens to

address string

with a value of address application is bound to

See:

start

Emitted when Hunt is started as background process

Type:
  • object
Properties:
Name Type Description
type string

with a value of string of 'background'

See:

http:*

Event emitted every time HTTP request is processed (successfully or not) for logging. http:* is namespace for http:success and http:error events

Type:
  • Object
Properties:
Name Type Description
startTime Date

start time of request

duration number

duration of request processing in milliseconds

statusCode number
method string

request method - GET, POST, PUT, DELETE

ip string

ip address of remote host

ips string

proxy chain if present - http://expressjs.com/api.html#req.ips

uri string
body string

This property is an object containing the parsed request body. This feature is provided by the bodyParser() middleware, though other body parsing middleware may follow this convention as well. This property defaults to {} when bodyParser() is used. http://expressjs.com/3x/api.html#req.body

query string

object containing the parsed query-string, defaulting to empty object - http://expressjs.com/3x/api.html#req.query

user User

user who did the request

See:
Example
Hunt.on('http:*', function(httpEvent){
    console.log('Http response processed!');
  });

  Hunt.on('http:success', function(httpEvent){
    console.log('Http response processed ok for ', httpEvent.ip);
  });

  Hunt.on('http:error', function(httpEvent){
    console.log('Http response failed for ', httpEvent.ip);
  });

http:error

Event is emmited when error occurs while performing http response

Type:
  • Object
Properties:
Name Type Description
error Error
errorStack object
startTime Date

start time of request

duration number

duration of request processing in milliseconds

statusCode number
method string

request method - GET, POST, PUT, DELETE

ip string

ip address of remote host

ips string

proxy chain if present - http://expressjs.com/api.html#req.ips

uri string
body string

This property is an object containing the parsed request body. This feature is provided by the bodyParser() middleware, though other body parsing middleware may follow this convention as well. This property defaults to {} when bodyParser() is used. http://expressjs.com/3x/api.html#req.body

query string

object containing the parsed query-string, defaulting to empty object - http://expressjs.com/3x/api.html#req.query

user User

user who did this request, and you can blaim him/her for breaking things

Example
Hunt.extendRoutes(function(core){
   core.app.get('/error', function(request,response){
     throw new Error('Shit happens!');
   });
  });

  Hunt.on('http:error', function(httpError){
    console.log(httpError.error.toString());
  });
  //=> Shit happens!

http:success

Event emitted every time HTTP request is processed successfully, useful for logging. It belongs to http namespace

Type:
  • Object
Properties:
Name Type Description
startTime Date

start time of request

duration number

duration of request processing in milliseconds

statusCode number
method string

request method - GET, POST, PUT, DELETE

ip string

ip address of remote host

ips string

proxy chain if present - http://expressjs.com/api.html#req.ips

uri string
body string

This property is an object containing the parsed request body. This feature is provided by the bodyParser() middleware, though other body parsing middleware may follow this convention as well. This property defaults to {} when bodyParser() is used. http://expressjs.com/3x/api.html#req.body

query string

object containing the parsed query-string, defaulting to empty object - http://expressjs.com/3x/api.html#req.query

user User

user who did the request

Example
Hunt.on('http:*', function(httpEvent){
    console.log('Http response processed!');
  });

  Hunt.on('http:success', function(httpEvent){
    console.log('Http response processed ok for ', httpEvent.ip);
  });

  Hunt.on('http:error', function(httpEvent){
    console.log('Http response failed for ', httpEvent.ip);
  });

message:sio

Event is emitted each time the socket.io client sends the message by this client side javascript code. See official socket.io wiki for details

Type:
  • object
Properties:
Name Type Description
user User | null

user, associated with this socket, or null if user is not authenticated

message string | object

message, issued by this socket.io client

Example
//in client side javascript
    var socket = io();
    socket.send('Hello!', function(error){...});
    socket.emit('message','Hello!', function(error){...}); //the same

    //in server side code
    hunt.on('message:sio', function (event) {
     console.log('We received socket.io event!', event);
    });


 

profiling:*

Emitted on every request send to any of data storage drivers - redis, mongoose, sequilize... Namespace is profiling:redis:* with namespaces consisted of redis command names and arguments' values

Type:
  • object
Properties:
Name Type Description
startedAt Date
finishedAt Date
duration Number

duration of request in milliseconds

driver String

database driver used, redis in this case

command String
command String
error Error | null
result string
Tutorials:
See:
Example
function listener(payload){
  console.log('We received event '+this.event+' with payload', payload);
}

//All this listeners will be fired on
//redis command `set someKeyName someKeyValue`

Hunt.on('profiling:*', listener);
Hunt.on('profiling:redis:*', listener);
Hunt.on('profiling:redis:set:*', listener);
Hunt.on('profiling:redis:set:someKeyName:*', listener);
Hunt.on('profiling:redis:set:someKeyName:someKeyValue', listener);
Hunt.redisClient.set('someKeyName','someKeyValue');

profiling:redis:*

Emitted on every redis command. Namespace is profiling:redis:* with namespaces consisted of redis command names and arguments' values

Type:
  • object
Properties:
Name Type Description
startedAt Date
finishedAt Date
duration Number

duration of request in milliseconds

driver String

database driver used, redis in this case

command String
command String
error Error | null
result string
Tutorials:
See:
Example
function listener(payload){
  console.log('We recieved event '+this.event+' with payload', payload);
}

//All this listeners will be fired on
//redis command `set someKeyName someKeyValue`

Hunt.on('profiling:*', listener);
Hunt.on('profiling:redis:*', listener);
Hunt.on('profiling:redis:set:*', listener);
Hunt.on('profiling:redis:set:someKeyName:*', listener);
Hunt.on('profiling:redis:set:someKeyName:someKeyValue', listener);
Hunt.redisClient.set('someKeyName','someKeyValue');

REST:collectionName:CALL_METHOD:methodName:itemId

Properties:
Name Type Description
ip string

ip address of remote host

ips string

proxy chain if present - http://expressjs.com/api.html#req.ips

modelName string

name of model being created

payload Object

data send from user

response Object

data recieved after calling method

document Object

document created

user User

user who did this request, and you can blaim him/her for breaking things

REST:collectionName:CALL_STATIC:methodName

Properties:
Name Type Description
ip string

ip address of remote host

ips string

proxy chain if present - http://expressjs.com/api.html#req.ips

modelName string

name of model being created

payload Object

data send from user

response Object

data recieved after calling method

user User

user who did this request, and you can blame him/her for breaking things

REST:collectionName:CREATE:itemCreatedId

Properties:
Name Type Description
ip string

ip address of remote host

ips string

proxy chain if present - http://expressjs.com/api.html#req.ips

modelName string

name of model being created

document Object

document created

seed Object

fields used to create new object

user User

user who did this request, and you can blaim him/her for breaking things

REST:collectionName:CREATE:itemCreatedId

Properties:
Name Type Description
ip string

ip address of remote host

ips string

proxy chain if present - http://expressjs.com/api.html#req.ips

modelName string

name of model being created

document Object

document created

seed Object

fields used to create new object

user User

user who did this request, and you can blaim him/her for breaking things

REST:collectionName:DELETE:itemId

Properties:
Name Type Description
ip string

ip address of remote host

ips string

proxy chain if present - http://expressjs.com/api.html#req.ips

modelName string

name of model being deleted

document Object

document being deleted

user User

user who did this request, and you can blaim him/her for breaking things

REST:collectionName:READ:itemId

Properties:
Name Type Description
ip string

ip address of remote host

ips string

proxy chain if present - http://expressjs.com/api.html#req.ips

modelName string

name of model being deleted

document Object

document being accessed

user User

user who did this request, and you can blaim him/her for breaking things

fieldsReadable Array.<string>

list of fields the current user have got access to

REST:collectionName:UPDATE:itemId

Properties:
Name Type Description
ip string

ip address of remote host

ips string

proxy chain if present - http://expressjs.com/api.html#req.ips

modelName string

name of model being deleted

document Object

document being deleted

user User

user who did this request, and you can blaim him/her for breaking things

patch Object

fields being updated, something like {"new":{"scored":true}, "old":{"scored":false}}

REST:collectionName:UPDATE:itemId

Properties:
Name Type Description
ip string

ip address of remote host

ips string

proxy chain if present - http://expressjs.com/api.html#req.ips

modelName string

name of model being deleted

document Object

document being deleted

user User

user who did this request, and you can blaim him/her for breaking things

patch Object

fields being updated, something like {"new":{"scored":true}, "old":{"scored":false}}

user:*

Namespace for events related to User model.

Type:
  • object
Properties:
Name Type Description
type string

type of event - auth,save...

info object

additional information

user User

user, related to this event

See:

user:notify:*

Emitted when any of users is notified by any channel

Type:
  • object
Properties:
Name Type Description
channel string

name of channel being used

user User

user being notified

message string | object
See:

user:notify:all

Emitted when any of users is notified by all channels

Type:
  • object
Properties:
Name Type Description
channel string

name of channel being used

user User

user being notified

message string | object
See:

user:notify:email

Emitted when any of users is notified by email, and when the user have email address, of course

Type:
  • object
Properties:
Name Type Description
user User

user being notified

message string | object
See:

user:notify:pm

Event is emitted each time user recieves a message via dialog api

Type:
  • object
Properties:
Name Type Description
to User

reciever of the message

from User

sender of the message

type type

of message

See:
Example
Hunt.on('user:notify:pm', function(payload){
  console.log(payload.from+ ' says to '+payload.user + ' ' + payload.message + ' via ' + payload.type );
});

user:notify:pm

Event is emitted each time user recieves a message via dialog api

Type:
  • object
Properties:
Name Type Description
to User

reciever of the message

from User

sender of the message

type type

of message

See:
Example
Hunt.on('user:notify:pm', function(payload){
  console.log(payload.from+ ' says to '+payload.user + ' ' + payload.message + ' via ' + payload.type );
});

user:notify:sio

Emitted to notify any of users by socket.io

Type:
  • object
Properties:
Name Type Description
user User

user being notified

message string | object

message object

type string

type of socket.io event to emit, default is notify:sio

See:

user:save

Event is emitted each time the user profile is updated and saved with payload of user being saved.

Type:
  • object
Properties:
Name Type Description
type string

type of event save...

info object

additional information

user User

user, related to this event

See:

user:signin:*

Event is emitted each time user signs in

Type:
  • object
Properties:
Name Type Description
type string

type of event auth

info object

additional information

user User

user, related to this event

Tutorials:
See:
Example
Hunt.on('user:signin:*', function(payload){
  console.log('We catch '+this.event.join(':') + 'event, which means '+ payload.user.displayName + ' signed in!');
});

user:signin:local

Event is emitted each time user signs in

Type:
  • object
Properties:
Name Type Description
type string

type of event auth

info object

additional information

user User

user, related to this event

Tutorials:
See:
Example
Hunt.on('user:signin:local', function(payload){
  console.log('We catch '+this.event.join(':') + 'event, which means '+ payload.user.displayName + ' authorized by local strategy!');
});

user:signin:providerName

Event is emitted each time user signs in by keychain

Type:
  • object
Properties:
Name Type Description
method string

name of provider user

profile object

profile as received from Oauth provider

user User

user, related to this event

ip string

IP address being used by user

ips string

IP addresses chain being used including proxies

userAgent string

user agent being used by user

Since:
  • 0.4.18
Tutorials:
See:
Example
Hunt.on('user:signin:github', function(payload){
  console.log('We catch '+this.event.join(':') + 'event, which means '+ payload.user.displayName + ' authorized by github!');
});

user:signup

Event is emited each time user sign's up

Type:
  • object
Properties:
Name Type Description
type string

type of event signup

info object

additional information

user User

user, related to this event

Tutorials:
See:
Example
Hunt.on('user:signup', function(payload){
  console.log('We catch '+this.event.join(':') + 'event, which means '+ payload.user.displayName + ' signed up by local strategy!');
});

Hunt

Constructor of HuntJS application

Constructor

new Hunt(config)

Parameters:
Name Type Description
config config

dictionary of configuration parameters

Fires:
Example
var hunt = require('hunt')({
 'port': 3000
})
.extendRoutes(function (core) {
   core.app.get('/', function (req, res) {
     res.send('Hello, world!');
   });
 })
 .startWebServer();

Classes

errorResponses

Members

app

ExpressJS application instance

async :Object

Embedded npm module of async of 1.2.1 version for better workflow

Type:
  • Object

config :config

Object that represents current config object of HuntJS application

Type:

express

ExpressJS framework constructor with static methods exposed, for example core.express.static is middleware used for serving css, client side javascripts, images.

http :Object

Embedded nodejs http module, that is used by socket.io and http server.

Type:
  • Object

httpServer

http server class, used by socket.io and expressJS objects

See:

io

Ready to use http://socket.io object with passport.js integration

model :model

Class to hold data models of Hunt application, they are injected into request object of controller.

Type:
See:

mongoConnection

Mongoose connection object

See:

mongoose

Mongoose object, used for object relation maping to mongo database Official Mongoose Documentation

Q :Object

Embedded npm module of Q of 1.4.1 version for better workflow

Type:
  • Object

redisClient

Ready to use redis client with connection parameters taken from config object. Additional info on redis client

Sequilize

SQL database object relational mapper constructor, that is used only when config option of sequilizeUrl is defined.

See:

sessionStorage

validator :Object

Embedded npm module of validator for better workflow

Type:
  • Object

version :string

Current HuntJS version

Type:
  • string

Methods

cachingMiddleware(ttlopt)

Generate caching middleware for this route

Parameters:
Name Type Attributes Default Description
ttl number | null <optional>
60

cache invalidation time, default is 60 seconds

Example
Hunt.extendRoutes(core){
 core.app.use('/cacheForTenSeconds', Hunt.cachingMiddleware(10000));
 core.app.use('/cacheForSixtySeconds', Hunt.cachingMiddleware(60000));
 core.app.get('*', function(request, response){
   response.send('Current time is '+new Date());
 });
}

createRedisClient()

Creates redis client

See:

decrypt(text, secretopt) → {string}

Decrypt the given text using config.SECRET by default or using the custom given secret

Parameters:
Name Type Attributes Description
text string

text to decrypt

secret string <optional>

secret to use for decryption, if absent, the value of config.secret is used

See:
Returns:
  • decrypted string
Type
string

doHttpError(response, statusCode, message)

Helper to make erroneous html response in controller.

Parameters:
Name Type Description
response Response
statusCode Number
message string

emit(eventName, payload, additionalOptionalPayloadopt, oneMoreAdditionalOptionalPayloadopt, evenOneMoreAdditionalOptionalPayloadopt)

Makes Hunt emit an event. Returns true if event had listeners, false otherwise. Hunt object is a standard nodejs event emitter object , so it supports all event emitter methods. Also Hunt object possess the functions of EventEmitter2 The default delimiter is ":"

Parameters:
Name Type Attributes Description
eventName string | Array.<string>
payload object
additionalOptionalPayload object <optional>
oneMoreAdditionalOptionalPayload object <optional>
evenOneMoreAdditionalOptionalPayload object <optional>
Returns:

boolean

Example
var hunt = require('./index.js')();
hunt.extendCore('a', 'b');
console.log('hunt.a=', hunt.a);

hunt.on('ping', function (msg, msg1) {
 console.log('+++ping+++', this.event, msg, msg1, '+++ping+++');
});

hunt.on('ping:2', function (msg, msg1) {
 console.log('+++ping:2+++', this.event, msg, msg1, '+++ping:2+++');
});

hunt.on('ping:*', function (msg, msg1) {
 console.log('+++ping:*+++', this.event, msg, msg1, '+++ping:*+++');
});


hunt.once('start', function (type) {
 console.log('Starting to send events...');
 hunt.emit(['ping', '2'], 'pong', 'lll');
});
hunt.startBackGround();

encrypt(text, secretopt) → {string}

Encrypt the given text by default or using the custom given secret

Parameters:
Name Type Attributes Description
text string

text to encrypt

secret string <optional>

secret to use for encryption, if absent, the value of config#secret is used

See:
Returns:
  • encrypted string
Type
string

exportModelToRest(parameters)

Export models as REST api, exposed by current http server

Parameters:
Name Type Description
parameters ExportModelToRestParameters

for exporting model to REST interface properly

extendApp(environment, settingsFunction) → {Hunt}

Set expressJS application parameters - template engine, variables, locals template engines, locals and other settings. In code it is called after setting logging middleware and port.

Parameters:
Name Type Description
environment string | Array | null

application environment to use, can be something like 'development', ['development','staging'] or null

settingsFunction function

function(core){....}

Tutorials:
See:
Returns:

hunt object

Type
Hunt
Example
//example of setting template engine
    hunt.extendApp = function (core) {
      core.app.set('views', __dirname + '/views');
      core.app.set('view engine', 'ejs');
      core.app.set('layout', 'layout');
      core.app.enable('view cache');
      core.app.engine('ejs', require('ejs'));
    };

extendController(mountPoint, settingsFunction) → {Hunt}

Add custom router for expressjs application

Parameters:
Name Type Description
mountPoint string
settingsFunction function
Since:
  • 0.2.2
Tutorials:
See:
Returns:

hunt object

Type
Hunt
Example
hunt.extendController('/', function(core, router){
 router.get('/', function(request,response){
   response.render('index',{'title':'Hello!'});
 });
});
//this controller overwrites the first one!
hunt.extendController('/', function(core, router){
 router.get('/', function(request,response){
   response.render('index2',{'title':'Hello!'});
 });
});

extendCore(field, value) → {Hunt}

Inject public property to hunt core. If value is function, the value injected is result of value(hunt), else value injected is AS IS.

Parameters:
Name Type Description
field string

property name to assign to hunt.[fieldName]

value string | object | Date | Array | function

value to assign

Returns:

hunt object for functions chaining

Type
Hunt
Example
var Hunt = require('hunt')(configObj);

   //extending application core

   //assign value to field
   Hunt.extendCore('someVar', 42);

   //assign factory function to field and this field value
   //is result of this function
   Hunt.extendCore('someFuncToGetSomeVar', function (core) {
     return core.someVar;
   });

   //assign function to a core
   Hunt.extendCore('getSumWithSomeVar', function (core) {
     return function (a, b) {
       return a + b + core.someFuncToGetSomeVar;
     };
   });

   //Hunt core works after extending
   console.log('Sum of 2, 2 and 42 is ' + Hunt.getSumWithSomeVar(2, 2));

extendModel(modelName, modelConstructor) → {Hunt}

Inject public property with model object to hunt.model.

Parameters:
Name Type Description
modelName string

property name to assign to hunt.model[modelName]

modelConstructor function

factory function to generate model using Hunt kernel

See:
Returns:

hunt object

Type
Hunt
Example
//for mongoose model
   if (Hunt.config.enableMongoose) { //verify that we enabled mongoose
     Hunt.extendModel('Trophy', function (core) {
       var TrophySchema = new core.mongoose.Schema({
         'name': {type: String, unique: true},
         'scored': Boolean
       });

       TrophySchema.index({
         name: 1
       });
//this step is very important - bind mongoose model to current mongo database connection
// and assign it to collection in mongo database
       return core.mongoConnection.model('Trophy', TrophySchema);
      });
// So, this model is accessible by
// Hunt.model.Trophy
    };

//sequilize model
Hunt.extendModel('Planet', function (core) {
    var Planet = core.sequelize.define('Planet', {
      name: core.Sequelize.STRING //note that core.Sequilize != core.sequilize
    });
    return Planet;
  });

extendStrategy(Strategy) → {Hunt}

Add new passportJS strategy to application by adding them to Hunt.passport object All strategies have to redirect to /auth/success on success or /auth/failure

Parameters:
Name Type Description
Strategy object

object

Tutorials:
See:
Returns:

hunt object

Type
Hunt
Example
var HashStrategy = require('passport-hash').Strategy;
   //used for verify account by email
   exports.strategy = function (core) {
     return new HashStrategy(function (hash, done) {
       core.model.User.findOneByHuntKeyAndVerifyEmail(hash, function (err, userFound) {
         done(err, userFound);
       });
     });
   };

   exports.routes = function (core) {
     core.app.get('/auth/confirm/:hash', core.passport.authenticate('hash', {
       successRedirect: '/auth/success',
       failureRedirect: '/auth/failure'
     }));
   };

extendTelnet(command, callback) → {Hunt}

Adds new behavior to telnet server. The callback has 2 arguments, first one is core object, and second one is RAI client object

Parameters:
Name Type Description
command string

command name

callback function

function(core, client, payload){}

Since:
  • 0.0.18
Tutorials:
Returns:

hunt object

Type
Hunt
Example
hunt.extendTelnet('version', function(core, client){
     client.send('HuntJS version is '+core.version);
    });
    hunt.extendTelnet('echo', function(core, client, payload){
     client.send(payload);
    });

forceHttps()

Middleware to ensure that connection is done via HTTPS protocol only. If request is done via HTTP protocol, user is redirected to HTTPS on the same url. This middleware do nothing if application environment is not production

See:
  • config#env
Returns:

function(request,response,next)

injectCssFromDirectory(arrayOfPatterns)

Automatically load css files from directory and load in hunt.app.locals.css

Parameters:
Name Type Description
arrayOfPatterns String

array of patterns for css files to load.

Example
Hunt.injectCssFromDirectory(["public/custom/*.css","public/vendor/*.css"])

injectJsFromDirectory(arrayOfPatterns)

Automatically load client side javascript files from directory and load in hunt.app.locals.javascripts

Parameters:
Name Type Description
arrayOfPatterns String

array of patterns for css files to load.

Example
Hunt.injectJsFromDirectory(["public/custom/*.js","public/vendor/*.js"])

loadControllersFromDirectory(dirname)

Automatically load custom controllers from directory.

Parameters:
Name Type Description
dirname String

path to directoriy with controller files.

Example
```javascript
//file `controllers/something.controller.js
"use strict";
exports.mountpoint = '/';
exports.handler = function (core, router) {
  router.get('/', function(req,res){
    res.send('Doing something...');
  });
}

//file index.js - main entry point
hunt.loadControllersFromDirectory('./controllers');
hunt.startWebServer();
```

loadModelsFromDirectory(dirname)

Automatically load custom models from directory.

Parameters:
Name Type Description
dirname String

path to directoriy with model files.

See:
Example
//file `models/Trophy.model.js
'use strict';

 exports.modelName = 'Trophy';
 exports.mountPoints = ['/api/v1/trophy', '/api/v1/trophies'];
 exports.exportModel = true;
 exports.ownerId = 'author';

 exports.init = function (core) {
  var TrophySchema = new core.mongoose.Schema({
  //other model initialization code
  })
 };
//file index.js - main entry point
hunt.loadModelsFromDirectory('./models');
hunt.startWebServer();

many(eventName, howManyTimesToFire, listener) → {Hunt}

Adds a listener to the end of the listeners array for the specified event that will execute n times for the event before being removed. The listener is invoked only the first n times the event is fired, after which it is removed. Calls can be chained. Hunt object is a standard nodejs event emitter object , so it supports all event emitter methods. Also Hunt object possess the functions of EventEmitter2 The default delimiter is ":"

Parameters:
Name Type Description
eventName string
howManyTimesToFire Number
listener function
See:
Returns:
Type
Hunt
Example
hunt
     .once('start', function (params) {
       console.log('Hunt is started as '+params.type+' on port '+params.port);
     })
     .many('httpError', 1, console.error); //1 error is enough :-)

md5(str) → {string}

Decrypt the given text using config.SECRET by default or using the custom given secret

Parameters:
Name Type Description
str string

text to decrypt

Returns:
  • decrypted string
Type
string

multipart()

Return connect-multiparty middleware to parse uploaded data and populate request.files with data. For example, when we submit form like this

  <form action="/upload" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="file" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
   </form>

the request.files is dictionary like this:

 {
   file: {
        fieldName: 'file',
       originalFilename: 'Kate Moss.jpg',
       path: '/tmp/4235-1yw9ixo.jpg',
       size: 61030,
       name: 'Kate Moss.jpg',
       type: 'image/jpeg',
       headers: {
        'content-disposition': 'form-data; name="file"; filename="Kate Moss.jpg"',
        'content-type': 'image/jpeg'
     },
     ws: {
      _writableState: [Object],
      writable: true,
      domain: [Object],
      _events: [Object],
      _maxListeners: 10,
      path: '/tmp/4235-1yw9ixo.jpg',
      fd: null,
      flags: 'w',
      mode: 438,
      start: undefined,
      pos: undefined,
      bytesWritten: 61030,
      closed: true
      }
   }
 }

It is worth noting, that files are cleared after response is send to user!

Returns:

function(request,response,next)

offAny(payload, additionalOptionalPayloadopt, oneMoreAdditionalOptionalPayloadopt, evenOneMoreAdditionalOptionalPayloadopt)

Removes the listener that will be fired when any event is emitted. Hunt object is a standard nodejs event emitter object , so it supports all event emitter methods. Also Hunt object possess the functions of EventEmitter2

Parameters:
Name Type Attributes Description
payload object
additionalOptionalPayload object <optional>
oneMoreAdditionalOptionalPayload object <optional>
evenOneMoreAdditionalOptionalPayload object <optional>
See:
Returns:

boolean

Example
function vortex(value1, value2) {
     console.log('All events trigger this. This is for you: ', value1, value2);
   }
   hunt.onAny(vortex);

   if (iHaveChangedMyMindToDoThis) {
     hunt.offAny(vortex);
   }

on(eventName, listener) → {Hunt}

Adds a listener to the end of the listeners array for the specified event. Calls can be chained. Hunt object is a standard nodejs event emitter object , so it supports all event emitter methods. Also Hunt object possess the functions of EventEmitter2 The default delimiter is ":"

Parameters:
Name Type Description
eventName string
listener function
See:
Returns:
Type
Hunt
Example
hunt
     .on('start', function (params) {
       console.log('Hunt is started as '+params.type+' on port '+params.port);
     })
     .on('httpError', console.error);

onAny(payload, additionalOptionalPayloadopt, oneMoreAdditionalOptionalPayloadopt, evenOneMoreAdditionalOptionalPayloadopt)

Adds a listener that will be fired when any event is emitted. Hunt object is a standard nodejs event emitter object , so it supports all event emitter methods. Also Hunt object possess the functions of EventEmitter2

Parameters:
Name Type Attributes Description
payload object
additionalOptionalPayload object <optional>
oneMoreAdditionalOptionalPayload object <optional>
evenOneMoreAdditionalOptionalPayload object <optional>
See:
Returns:

boolean

Example
function vortex(value1, value2) {
     console.log('All events trigger this. This is for you: ', value1, value2);
   }
   hunt.onAny(vortex);

   if (iHaveChangedMyMindToDoThis) {
     hunt.offAny(vortex);
   }

once(eventName, listener) → {Hunt}

Adds a one time listener for the event. This listener is invoked only the next time the event is fired, after which it is removed. Calls can be chained. Hunt object is a standard nodejs event emitter object , so it supports all event emitter methods. Also Hunt object possess the functions of EventEmitter2 The default delimiter is ":"

Parameters:
Name Type Description
eventName string
listener function
See:
Returns:
Type
Hunt

onSocketIoEvent(eventName, callback) → {Hunt}

Parameters:
Name Type Description
eventName string
callback function

function(payload, socket, function(error){...});

Since:
  • 0.2.0
Returns:

hunt object

Type
Hunt
Example
//client side code
<script>
var socket = io(); // TIP: io.connect() with no args does auto-discovery
socket.emit('message', 'I will find you!', function (data) {
  console.log(data); // data will be 'cool!'
});
socket.send('I will find you!', function (data) { //the same
  console.log(data); // data will be 'cool!'
});
</script>

//server side code
hunt.onSocketIoEvent('message', function(payload, socket, fn){
  console.log('Message recieved',payload);
  socket.emit('thanks','for the message');
  fn('cool!');
});

preload(modelName)

Middleware to load Mongoose model with id extracted from request.params[0] into request.preload Fires REST:collectionName:READ:itemId event if object can be shown to user.

Parameters:
Name Type Description
modelName string
See:
  • request#preload
Fires:
Returns:

function(request,response,next)

Example
hunt.extendRouter('/api/v1/trophy', function(core, router){
 router.get(/^\/([0-9a-fA-F]{24})\/isScored$/, core.preload('Trophy'), function(request, response){
   if(request.preload.canRead) {
     response.json({'scored':request.preload.model.scored});
   } else {
     response.sendStatus(403);
   }
 });
});

rack() → {string}

Generate really long random strings

Returns:

someReallyHardRandomStringThatMakesHackersRealySad

Type
string

removeListener(eventName, listener) → {Hunt}

Hunt object is a standard nodejs event emitter object , so it supports all event emitter methods. Also Hunt object possess the functions of EventEmitter2 Remove a listener from the listener array for the specified event. Caution: changes array indices in the listener array behind the listener. Calls can be chained.

Parameters:
Name Type Description
eventName string
listener function
Returns:

Hunt

Type
Hunt

sha512(str) → {string}

Make sha512 hash of string

Parameters:
Name Type Description
str string

text to decrypt

Returns:
  • decrypted string
Type
string

startBackGround()

Starts Hunt application as single threaded background application It have redis client and data models, event emitting system exposed. It makes Hunt to emit event of "start" with payload of {'type':'background'}

Fires:
Example
Hunt.startBackGround();

startBackGroundCluster(maxProcesses) → {Boolean}

Starts Hunt application as single threaded background application, that controls, by the means of cluster, other background applications. By default it spawns 1 process per CPU core.

Parameters:
Name Type Description
maxProcesses Number | null

maximal number of web server processes to spawn, default - 1 process per CPU core

Fires:
Returns:

true if this is master process, false if this is worker process.

Type
Boolean
Example
var numberOfProcessesToSpawn = 10;
   Hunt.startBackGroundCluster(numberOfProcessesToSpawn);

startCluster(parameters) → {Boolean}

Start Hunt as cluster. Parameters is object with 4 field -

  • web, background, telnet, 'port'. The values of web,background, telnet are number of child processes to spawn. The value of port is port number for web server processes to listen to. It is worth notice, that in this case telnet server listens on Hunt.config.port+1 port!
Parameters:
Name Type Description
parameters object

configuration parameters

To Do:
  • - make unit tests
Fires:
Returns:

true if this is master process, false if this is worker process.

Type
Boolean
Example
Hunt.startCluster({ 'web':1, 'background':1, 'telnet': 1 });
    Hunt.startCluster({ 'web':'max', 'port':80, 'address':'127.0.0.1' });
    Hunt.startCluster({ 'background':'max' });
    Hunt.startCluster({ 'telnet':max, 'port':25 });
    Hunt.startCluster({ 'web':'max', 'telnet':'max' }); //i strongly do not recommend doing this!

startTelnetCluster(port, maxProcesses) → {Boolean}

Starts hunt application as single threaded background application, that controls, by the means of nodejs embedded cluster, telnet server processes. By default it spawns 1 process per CPU core. It makes Hunt to emit event of "start" with payload of {'type':'background'} in master process, and events of "start" with payload of {'type':'telnet', 'port':25} in each of telnet server processes.

Parameters:
Name Type Description
port number | null

what port to use, if null - use port value from config

maxProcesses number | null

maximal number of web server processes to spawn, default - 1 process per CPU core

Fires:
Returns:

true if this is master process, false if this is worker process.

Type
Boolean
Example
Hunt.startTelnetCluster(25, 10000);

startTelnetServer(port, addressopt)

Start Hunt as single process telnet server

Parameters:
Name Type Attributes Default Description
port number | null

what port to use, if null - use port value from config

address string | null <optional>
"0.0.0.0"

address to listen on, if null - use address from config

Since:
  • 0.0.18
Tutorials:
Fires:
Example
Hunt.startTelnetServer(3003);

startWebCluster(port, maxProcesses) → {Boolean}

Starts hunt application as single threaded background application, that controls, by the means of nodejs embedded cluster, web server processes. By default it spawns 1 process per CPU core. It makes Hunt to emit event of "start" with payload of {'type':'background'} in master process, and events of "start" with payload of {'type':'webserver', 'port':80} in web server processes.

Parameters:
Name Type Description
port number | null

what port to use, if null - use port value from config

maxProcesses number | null

maximal number of web server processes to spawn, default - 1 process per CPU core

Tutorials:
Fires:
Returns:

true if this is master process, false if this is worker process.

Type
Boolean
Example
Hunt.startWebCluster(80, 10000);

startWebServer(port, address)

Starts Hunt application as single threaded web server It have redis client/models, expressJS application and event emitting system exposed. It makes Hunt to emit event of "start" with payload of {'type':'webserver', 'port':80}

Parameters:
Name Type Description
port number | null

what port to use, if null - use port value from config

address string | null

what address to bind to. Default is '0.0.0.0' - all IPv4 addresses. The address is populated from environment address of HUNTJS_ADDR

Tutorials:
Fires:
Example
Hunt.startWebServer(80);
    Hunt.startWebServer(80, '0.0.0.0');
    Hunt.startWebServer(80, 'fe80::7218:8bff:fe86:542b');

stop()

Stops the current application - close database connections, etc.

Events

broadcast

Broadcast message from core via socket.io to all webserver clients - both authorized users and non authorized site visitors

Type:
  • object
See:
  • Hunt#notify:sio
Example
core.emit('broadcast','Hello? Can you hear me? Jungle took him!');
//emits socket.io event of type `broadcast` with
//payload 'Hello? Can you hear me? Jungle took him!'

core.emit('broadcast', {type:'screamLoudly',message:'Hello? Can you hear me? Jungle took him!'});
//emits 2 socket.io events:

//the first one of type `broadcast` with
// {type:'screamLoudly',message:'Hello? Can you hear me? Jungle took him!'}
//for backward compatibility of huntjs 0.3.x branch

//and the second one of type `screamLoudly` with payload
//{type:'screamLoudly',message:'Hello? Can you hear me? Jungle took him!'}

start

Emitted when Hunt is started as telnet process

Type:
  • object
Properties:
Name Type Description
type string

with a value of string of 'telnet'

port string

with a value of string of port number

address string

with a value of address application is bound to

See:

start

Emitted when Hunt is started as webserver process

Type:
  • object
Properties:
Name Type Description
type string

with a value of string of 'webserver'

port number

with a value of port this application listens to

address string

with a value of address application is bound to

See:

start

Emitted when Hunt is started as background process

Type:
  • object
Properties:
Name Type Description
type string

with a value of string of 'background'

See:

http:*

Event emitted every time HTTP request is processed (successfully or not) for logging. http:* is namespace for http:success and http:error events

Type:
  • Object
Properties:
Name Type Description
startTime Date

start time of request

duration number

duration of request processing in milliseconds

statusCode number
method string

request method - GET, POST, PUT, DELETE

ip string

ip address of remote host

ips string

proxy chain if present - http://expressjs.com/api.html#req.ips

uri string
body string

This property is an object containing the parsed request body. This feature is provided by the bodyParser() middleware, though other body parsing middleware may follow this convention as well. This property defaults to {} when bodyParser() is used. http://expressjs.com/3x/api.html#req.body

query string

object containing the parsed query-string, defaulting to empty object - http://expressjs.com/3x/api.html#req.query

user User

user who did the request

See:
Example
Hunt.on('http:*', function(httpEvent){
    console.log('Http response processed!');
  });

  Hunt.on('http:success', function(httpEvent){
    console.log('Http response processed ok for ', httpEvent.ip);
  });

  Hunt.on('http:error', function(httpEvent){
    console.log('Http response failed for ', httpEvent.ip);
  });

http:error

Event is emmited when error occurs while performing http response

Type:
  • Object
Properties:
Name Type Description
error Error
errorStack object
startTime Date

start time of request

duration number

duration of request processing in milliseconds

statusCode number
method string

request method - GET, POST, PUT, DELETE

ip string

ip address of remote host

ips string

proxy chain if present - http://expressjs.com/api.html#req.ips

uri string
body string

This property is an object containing the parsed request body. This feature is provided by the bodyParser() middleware, though other body parsing middleware may follow this convention as well. This property defaults to {} when bodyParser() is used. http://expressjs.com/3x/api.html#req.body

query string

object containing the parsed query-string, defaulting to empty object - http://expressjs.com/3x/api.html#req.query

user User

user who did this request, and you can blaim him/her for breaking things

Example
Hunt.extendRoutes(function(core){
   core.app.get('/error', function(request,response){
     throw new Error('Shit happens!');
   });
  });

  Hunt.on('http:error', function(httpError){
    console.log(httpError.error.toString());
  });
  //=> Shit happens!

http:success

Event emitted every time HTTP request is processed successfully, useful for logging. It belongs to http namespace

Type:
  • Object
Properties:
Name Type Description
startTime Date

start time of request

duration number

duration of request processing in milliseconds

statusCode number
method string

request method - GET, POST, PUT, DELETE

ip string

ip address of remote host

ips string

proxy chain if present - http://expressjs.com/api.html#req.ips

uri string
body string

This property is an object containing the parsed request body. This feature is provided by the bodyParser() middleware, though other body parsing middleware may follow this convention as well. This property defaults to {} when bodyParser() is used. http://expressjs.com/3x/api.html#req.body

query string

object containing the parsed query-string, defaulting to empty object - http://expressjs.com/3x/api.html#req.query

user User

user who did the request

Example
Hunt.on('http:*', function(httpEvent){
    console.log('Http response processed!');
  });

  Hunt.on('http:success', function(httpEvent){
    console.log('Http response processed ok for ', httpEvent.ip);
  });

  Hunt.on('http:error', function(httpEvent){
    console.log('Http response failed for ', httpEvent.ip);
  });

message:sio

Event is emitted each time the socket.io client sends the message by this client side javascript code. See official socket.io wiki for details

Type:
  • object
Properties:
Name Type Description
user User | null

user, associated with this socket, or null if user is not authenticated

message string | object

message, issued by this socket.io client

Example
//in client side javascript
    var socket = io();
    socket.send('Hello!', function(error){...});
    socket.emit('message','Hello!', function(error){...}); //the same

    //in server side code
    hunt.on('message:sio', function (event) {
     console.log('We received socket.io event!', event);
    });


 

profiling:*

Emitted on every request send to any of data storage drivers - redis, mongoose, sequilize... Namespace is profiling:redis:* with namespaces consisted of redis command names and arguments' values

Type:
  • object
Properties:
Name Type Description
startedAt Date
finishedAt Date
duration Number

duration of request in milliseconds

driver String

database driver used, redis in this case

command String
command String
error Error | null
result string
Tutorials:
See:
Example
function listener(payload){
  console.log('We received event '+this.event+' with payload', payload);
}

//All this listeners will be fired on
//redis command `set someKeyName someKeyValue`

Hunt.on('profiling:*', listener);
Hunt.on('profiling:redis:*', listener);
Hunt.on('profiling:redis:set:*', listener);
Hunt.on('profiling:redis:set:someKeyName:*', listener);
Hunt.on('profiling:redis:set:someKeyName:someKeyValue', listener);
Hunt.redisClient.set('someKeyName','someKeyValue');

profiling:redis:*

Emitted on every redis command. Namespace is profiling:redis:* with namespaces consisted of redis command names and arguments' values

Type:
  • object
Properties:
Name Type Description
startedAt Date
finishedAt Date
duration Number

duration of request in milliseconds

driver String

database driver used, redis in this case

command String
command String
error Error | null
result string
Tutorials:
See:
Example
function listener(payload){
  console.log('We recieved event '+this.event+' with payload', payload);
}

//All this listeners will be fired on
//redis command `set someKeyName someKeyValue`

Hunt.on('profiling:*', listener);
Hunt.on('profiling:redis:*', listener);
Hunt.on('profiling:redis:set:*', listener);
Hunt.on('profiling:redis:set:someKeyName:*', listener);
Hunt.on('profiling:redis:set:someKeyName:someKeyValue', listener);
Hunt.redisClient.set('someKeyName','someKeyValue');

REST:collectionName:CALL_METHOD:methodName:itemId

Properties:
Name Type Description
ip string

ip address of remote host

ips string

proxy chain if present - http://expressjs.com/api.html#req.ips

modelName string

name of model being created

payload Object

data send from user

response Object

data recieved after calling method

document Object

document created

user User

user who did this request, and you can blaim him/her for breaking things

REST:collectionName:CALL_STATIC:methodName

Properties:
Name Type Description
ip string

ip address of remote host

ips string

proxy chain if present - http://expressjs.com/api.html#req.ips

modelName string

name of model being created

payload Object

data send from user

response Object

data recieved after calling method

user User

user who did this request, and you can blame him/her for breaking things

REST:collectionName:CREATE:itemCreatedId

Properties:
Name Type Description
ip string

ip address of remote host

ips string

proxy chain if present - http://expressjs.com/api.html#req.ips

modelName string

name of model being created

document Object

document created

seed Object

fields used to create new object

user User

user who did this request, and you can blaim him/her for breaking things

REST:collectionName:CREATE:itemCreatedId

Properties:
Name Type Description
ip string

ip address of remote host

ips string

proxy chain if present - http://expressjs.com/api.html#req.ips

modelName string

name of model being created

document Object

document created

seed Object

fields used to create new object

user User

user who did this request, and you can blaim him/her for breaking things

REST:collectionName:DELETE:itemId

Properties:
Name Type Description
ip string

ip address of remote host

ips string

proxy chain if present - http://expressjs.com/api.html#req.ips

modelName string

name of model being deleted

document Object

document being deleted

user User

user who did this request, and you can blaim him/her for breaking things

REST:collectionName:READ:itemId

Properties:
Name Type Description
ip string

ip address of remote host

ips string

proxy chain if present - http://expressjs.com/api.html#req.ips

modelName string

name of model being deleted

document Object

document being accessed

user User

user who did this request, and you can blaim him/her for breaking things

fieldsReadable Array.<string>

list of fields the current user have got access to

REST:collectionName:UPDATE:itemId

Properties:
Name Type Description
ip string

ip address of remote host

ips string

proxy chain if present - http://expressjs.com/api.html#req.ips

modelName string

name of model being deleted

document Object

document being deleted

user User

user who did this request, and you can blaim him/her for breaking things

patch Object

fields being updated, something like {"new":{"scored":true}, "old":{"scored":false}}

REST:collectionName:UPDATE:itemId

Properties:
Name Type Description
ip string

ip address of remote host

ips string

proxy chain if present - http://expressjs.com/api.html#req.ips

modelName string

name of model being deleted

document Object

document being deleted

user User

user who did this request, and you can blaim him/her for breaking things

patch Object

fields being updated, something like {"new":{"scored":true}, "old":{"scored":false}}

user:*

Namespace for events related to User model.

Type:
  • object
Properties:
Name Type Description
type string

type of event - auth,save...

info object

additional information

user User

user, related to this event

See:

user:notify:*

Emitted when any of users is notified by any channel

Type:
  • object
Properties:
Name Type Description
channel string

name of channel being used

user User

user being notified

message string | object
See:

user:notify:all

Emitted when any of users is notified by all channels

Type:
  • object
Properties:
Name Type Description
channel string

name of channel being used

user User

user being notified

message string | object
See:

user:notify:email

Emitted when any of users is notified by email, and when the user have email address, of course

Type:
  • object
Properties:
Name Type Description
user User

user being notified

message string | object
See:

user:notify:pm

Event is emitted each time user recieves a message via dialog api

Type:
  • object
Properties:
Name Type Description
to User

reciever of the message

from User

sender of the message

type type

of message

See:
Example
Hunt.on('user:notify:pm', function(payload){
  console.log(payload.from+ ' says to '+payload.user + ' ' + payload.message + ' via ' + payload.type );
});

user:notify:pm

Event is emitted each time user recieves a message via dialog api

Type:
  • object
Properties:
Name Type Description
to User

reciever of the message

from User

sender of the message

type type

of message

See:
Example
Hunt.on('user:notify:pm', function(payload){
  console.log(payload.from+ ' says to '+payload.user + ' ' + payload.message + ' via ' + payload.type );
});

user:notify:sio

Emitted to notify any of users by socket.io

Type:
  • object
Properties:
Name Type Description
user User

user being notified

message string | object

message object

type string

type of socket.io event to emit, default is notify:sio

See:

user:save

Event is emitted each time the user profile is updated and saved with payload of user being saved.

Type:
  • object
Properties:
Name Type Description
type string

type of event save...

info object

additional information

user User

user, related to this event

See:

user:signin:*

Event is emitted each time user signs in

Type:
  • object
Properties:
Name Type Description
type string

type of event auth

info object

additional information

user User

user, related to this event

Tutorials:
See:
Example
Hunt.on('user:signin:*', function(payload){
  console.log('We catch '+this.event.join(':') + 'event, which means '+ payload.user.displayName + ' signed in!');
});

user:signin:local

Event is emitted each time user signs in

Type:
  • object
Properties:
Name Type Description
type string

type of event auth

info object

additional information

user User

user, related to this event

Tutorials:
See:
Example
Hunt.on('user:signin:local', function(payload){
  console.log('We catch '+this.event.join(':') + 'event, which means '+ payload.user.displayName + ' authorized by local strategy!');
});

user:signin:providerName

Event is emitted each time user signs in by keychain

Type:
  • object
Properties:
Name Type Description
method string

name of provider user

profile object

profile as received from Oauth provider

user User

user, related to this event

ip string

IP address being used by user

ips string

IP addresses chain being used including proxies

userAgent string

user agent being used by user

Since:
  • 0.4.18
Tutorials:
See:
Example
Hunt.on('user:signin:github', function(payload){
  console.log('We catch '+this.event.join(':') + 'event, which means '+ payload.user.displayName + ' authorized by github!');
});

user:signup

Event is emited each time user sign's up

Type:
  • object
Properties:
Name Type Description
type string

type of event signup

info object

additional information

user User

user, related to this event

Tutorials:
See:
Example
Hunt.on('user:signup', function(payload){
  console.log('We catch '+this.event.join(':') + 'event, which means '+ payload.user.displayName + ' signed up by local strategy!');
});