MPBasic

extends EventEmitter

Exports: Constructor

This is a general basic class. It inculdes some methods that are often usefull. It integrates logging, error handling getter/setter, ...

Example:

Config = require( "./path/to/config/module" );
class FooClass extends require( "mpbasic" )( Config )
initialize: =>
    @debug "init"

new FooClass() // -> DEBUG FooClass - Nov 07 2014 15:42:14 - init

npm modules

20  
21  _isFunction = require( "lodash/isFunction" )
22  _isString = require( "lodash/isString" )
23  _template = require( "lodash/template" )
24  
25  extend = require('extend')
26  colors = require('colors')
27  
28  module.exports = ( config )->
29    
30    if not config?
31  
32  

Default config

31  
32      config = require( "./config" )
33    
34  
35  

Basic Module

extends [EventEmitter]

Basic module to handle errors and initialize modules

36  
37    return class Basic extends require('events').EventEmitter
38  
39  

internals

make the deep extend availible for all modles

40  
41      extend: extend
42  
43  
44  

defaults Function basic object to hold config defaults. Will be overwritten by the constructor options

43  
44      defaults: =>
45        return {}
46  
47  
48  

constructor

new Baisc( options )

Basic constructor. Define the configuration by options and defaults, init logging and init the error handler

Params
options Object Basic config object
56  
57      constructor: ( options = {} )->
58        @on "_log", @_log
59  
60        @getter "classname", ->
61          return @constructor.name.toLowerCase()
62  
63        @config = extend( true, {}, @defaults(), config.get( @_config_name or @classname, true ), options )
64  
65  
66  

init errors

65  
66        @_initErrors()
67  
68        @initialize( options )
69  
70        @debug "loaded"
71        return
72  
73  
74  

useage:

mixin

mpbasic.mixin( mixins... )

Method to include other class methods to this class.

Params
mixins... Class One or more classes as arguments
API
public

Example:

class Foo
    bar: ->
    console.log( 42 )
    return @

class Lorem extends require( "mpbasic" )()
    constructor: ->
        @mixin( Foo )
    return
        run: -> return 23

new Lorem().bar().run() # -> log: 42 ; return 23
102  
103      mixin: (mixins...)=>
104        if mixins?.length
105          for mxn in mixins
106            for _fnname, fn of mxn.prototype when _fnname isnt "constructor"
107              @[ _fnname ] = fn
108        return
109  
110  
111  

initialize

basic.initialize()

Overwritible Method to initialize the module

Params
options Object Basic config object passed to constructor
API
public
120  
121      initialize: ( options )->
122        return
123  
124  
125  

define

basic.define( prop, fnGet [, fnSet] )

Helper to define getter and setter methods fot a property

Params
prop String Property name
fnGet Function Object Get method or a object with get and set
[fnSet] Function Set method
API
public
136  
137      define: ( prop, fnGet, fnSet, writable = true, enumerable = true )=>
138        _oGetSet =
139          enumerable: enumerable
140          writable: writable
141  
142        if _isFunction( fnGet )
143  
144  

set the defineProperty object

143  
144          _oGetSet =
145            get: fnGet
146          _oGetSet.set = fnSet if fnSet? and _isFunction( fnSet )
147        else
148          _oGetSet.value = fnGet
149        
150  
151  

define by object

150  
151        Object.defineProperty @, prop, _oGetSet
152        return
153  
154  
155  

getter

basic.getter( prop, fnGet )

Shortcut to define a getter

Params
prop String Property name
fnGet Function Get method
API
public
165  
166      getter: ( prop, _get, enumerable = true )=>
167        _obj =
168          enumerable: enumerable
169  
170  

writable: false

169  
170  
171        if _isFunction( _get )
172          _obj.get = _get
173        else
174          _obj.value = _get
175        Object.defineProperty @, prop, _obj
176        return
177  
178  
179  

setter

basic.setter( prop, fnSet )

Shortcut to define a setter

Params
prop String Property name
fnSet Function Get method
API
public
189  
190      setter: ( prop, fnGet, enumerable = true )=>
191        Object.defineProperty @, prop, set: fnGet, enumerable: enumerable, writable: true
192        return
193  
194  
195  

_waitUntil

basic._waitUntil( method[, key][, context] )

Wrapper method to create a methos thas is only called until the @{key}is true or an event {key} has bin emitted. Usually this is used to generate a method that will wait until the modules/class is ready.

Params
method Function The function to call.
[ String key="ready" ] the key to listen for.
[context={self}] Context The context to lsiten to the key. Per default it is the instance it self @ or this.
API
public
207  
208      _waitUntil: ( method, key = "ready", context = @ )=>
209        return =>
210          args = arguments
211          if context[ key ]
212            method.apply( @, args )
213          else
214            context.once key, =>
215              method.apply( @, args )
216              return
217          return
218  
219  
220  

handle a error

_handleError

basic._handleError( cb, err [, data] )

Baisc error handler. It creates a true error object and returns it to the callback, logs it or throws the error hard

Params
cb Function String Callback function or NAme to send it to the logger as error
err String Error Object Error type, Obejct or real error object
API
private
231  
232      _handleError: ( cb, err, data = {}, errExnd )=>
233  
234  

try to create a error Object with humanized message

233  
234        if _isString( err )
235          _err = new Error()
236          _err.name = err
237          _err.message = @_ERRORS?[ err ][ 1 ]?( data ) or "unkown"
238          _err.statusCode = @_ERRORS?[ err ][ 0 ] or 500
239          _err.customError = true
240        else
241          _err = err
242  
243        if errExnd?
244          _err.data = errExnd
245  
246        for _k, _v of data
247          _err[ _k ] = _v
248  
249        if _isFunction( cb )
250  
251  

@log "error", "", _err

250  
251          cb( _err )
252        else if _isString( cb )
253          @log "error", cb, _err
254        else if cb is true
255          return _err
256        else
257          throw _err
258        return _err
259  
260  
261  

log

base.log( severity, code [, content1, content2, ... ] )

write a log to the console if the current severity matches the message severity

Params
severity String Message severity
code String Simple code the describe/label the output
[contentN] Any Content to append to the log
API
public
272  
273      log: ( severity, code, content... )=>
274        args = [ "_log", severity, code ]
275        @emit.apply( @, args.concat( content ) )
276        return
277  
278  
279  

_log

base._log( severity, code [, content1, content2, ... ] )

write a log to the console if the current severity matches the message severity

Params
severity String Message severity
code String Simple code the describe/label the output
[contentN] Any Content to append to the log
API
private
290  
291      _log: ( severity, code, content... )=>
292  
293  

get the severity and throw a log event

292  
293        
294        if @_checkLogging( severity )
295          _tmpl = "%s %s - #{ new Date().toString()[4..23]} - %s "
296  
297          args = [ _tmpl, severity.toUpperCase(), @_logname(), code ]
298  
299          if content.length
300            args[ 0 ] += "\n"
301            for _c in content
302              args.push _c
303  
304          switch severity
305            when "fatal"
306              args[ 0 ] = args[ 0 ].red.bold.inverse
307              console.error.apply( console, args )
308              for arg in args when arg instanceof Error
309                console.log arg.stack
310                return
311              console.trace()
312            when "error"
313              args[ 0 ] = args[ 0 ].red.bold
314              console.error.apply( console, args )
315            when "warning"
316              args[ 0 ] = args[ 0 ].yellow.bold
317              console.warn.apply( console, args )
318            when "info"
319              args[ 0 ] = args[ 0 ].blue.bold
320              console.info.apply( console, args )
321            when "debug"
322              args[ 0 ] = args[ 0 ].green.bold
323              console.log.apply( console, args )
324            else
325      
326        return
327  
328  
329  

_logname

basic._logname()

Helper method to overwrite the name displayed withing the console output

Params
String Desc
Function Callback function
Returns
String Return Desc
API
private
341  
342      _logname: =>
343        return @constructor.name
344  
345  
346  

fatal

index.fatal( code, content... )

Shorthand to output a fatal log

Params
code String Simple code the describe/label the output
[contentN] Any Content to append to the log
API
public
356  
357      fatal: ( code, content... )=>
358        args = [ "_log", "fatal", code ]
359        @emit.apply( @, args.concat( content ) )
360        return
361  
362  
363  

error

index.error( code, content... )

Shorthand to output a error log

Params
code String Simple code the describe/label the output
[contentN] Any Content to append to the log
API
public
373  
374      error: ( code, content... )=>
375        args = [ "_log", "error", code ]
376        @emit.apply( @, args.concat( content ) )
377        return
378  
379  
380  

warning

index.warning( code, content... )

Shorthand to output a warning log

Params
code String Simple code the describe/label the output
[contentN] Any Content to append to the log
API
public
390  
391      warning: ( code, content... )=>
392        args = ["_log",  "warning", code ]
393        @emit.apply( @, args.concat( content ) )
394        return
395  
396  
397  

info

index.info( code, content... )

Shorthand to output a info log

Params
code String Simple code the describe/label the output
[contentN] Any Content to append to the log
API
public
407  
408      info: ( code, content... )=>
409        args = [ "_log", "info", code ]
410        @emit.apply( @, args.concat( content ) )
411        return
412  
413  
414  

debug

index.debug( code, content... )

Shorthand to output a debug log

Params
code String Simple code the describe/label the output
[contentN] Any Content to append to the log
API
public
424  
425      debug: ( code, content... )=>
426        args = [ "_log", "debug", code ]
427        @emit.apply( @, args.concat( content ) )
428        return
429  
430  
431  

_checkLogging

basic._checkLogging( severity )

Helper to check if a log will be written to the console

Params
severity String Message severity
Returns
Boolean Flag if the severity is allowed to write to the console
API
private
442  
443      _checkLogging: ( severity )=>
444        if not @_logging_iseverity?
445          @_logging_iseverity = @config.logging.severitys.indexOf( @config.logging.severity )
446  
447        iServ = @config.logging.severitys.indexOf( severity )
448        if @config.logging.severity? and iServ <= @_logging_iseverity
449          true
450        else
451          false
452  
453  
454  

_initErrors

basic._initErrors( )

convert error messages to underscore templates

API
private
461  
462      _initErrors: =>
463        @_ERRORS = @ERRORS()
464        for key, msg of @_ERRORS
465          if not _isFunction( msg[ 1 ] )
466            @_ERRORS[ key ][ 1 ] = _template( msg[ 1 ] )
467      
468        return
469  
470  
471  

ERRORS

passwordless.ERRORS()

Error detail mappings

Returns
Object Return A Object of error details. Format: "ERRORCODE":[ ststudCode, "Error detail" ]
API
private
480  
481      ERRORS: =>
482        "ENOTIMPLEMENTED": [ 501, "This function is planed but currently not implemented" ]
483