jrf0110 / dirac

A Node Postgres DB layer built with MoSQL
http://dirac.j0.hn
6 stars 2 forks source link

Before and After Filters #2

Closed jrf0110 closed 11 years ago

jrf0110 commented 11 years ago

This will be used to integrate validators:

https://github.com/chriso/node-validator

// Before and After receive the MoSQL query object, MoSQL schema, and next function
dirac.dals.users.before( 'select', function( $query, schema, next ){
  // Filter columns on select statement to what is allowed
  $query.columns = $query.columns.filter( function( col ){
    return allowedColumns.indexOf( col ) > -1;
  });

  next();
});

// Called after results have been fetched. Has an additional
// results parameter that is the result of the query
// Be careful, results could be an array, an object, or null
dirac.dals.users.after( 'select', function( results, $query, schema, next ){
  // Cast bigints
  results.forEach( function( result, i ){
    results[ i ].rating = parseInt( result.rating );
  });

  next();
});

// You can send an error through next
dirac.dals.users.before( 'insert', function( $query, schema, next ){
  var errors = [];
  Object.keys( schema ).filter( function( key ){
    return 'validate' in schema[ key ];
  }).forEach( function( key ){
    Object.keys( schema[ key ].validate ).forEach( function( validator ){
      try {
        check( $query.values[ key ] )[ validator ].apply( check, schema[ key ].validate[ validator ] )
      } catch ( e ){
        errors.push( e );
      }
    });
  });

  if ( error.length > 0 ) return next( errors );

  next();
});

// Before all inserts
dirac.before( 'insert', function( $query, schema, next ){

});