Advertisement
Guest User

Untitled

a guest
Jan 24th, 2016
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // src/model_base.js
  2. 'use strict'
  3.  
  4. import _ from '../lodash-mixins'
  5.  
  6. const utils = {}
  7.  
  8. /**
  9.  * Retrieve the file name of the model importing/requiring this file
  10.  *
  11.  * @return {string} Full path and filename of parent file - EG: /path/File-Name.js
  12.  */
  13. utils.getParentFilename = () => {
  14.     try {
  15.         var err = new Error()
  16.         var callerfile
  17.         var currentfile
  18.  
  19.         Error.prepareStackTrace =  (err, stack) => stack
  20.  
  21.         currentfile = err.stack.shift().getFileName()
  22.  
  23.         while (err.stack.length) {
  24.             callerfile = err.stack.shift().getFileName()
  25.  
  26.             if(currentfile !== callerfile)
  27.                 return callerfile
  28.         }
  29.     } catch (err) {}
  30.  
  31.     return undefined
  32. }
  33.  
  34. /**
  35.  * Return a model name based off of the filename/path returned from getParentFilename().
  36.  * Basically just a regex match for the filename, without the extension, and converted
  37.  * to snakeCase
  38.  *
  39.  * @return {string} Parent file name converted to string - EG: /path/File-Name.js -> file_name
  40.  */
  41. utils.getModelName = () => {
  42.     const parentFile = utils.getParentFilename()
  43.  
  44.     if( ! parentFile)
  45.         throw new Error('Failed to get the filename of the model calling the base model')
  46.  
  47.     return _.snakeCase( parentFile.match(/\/([a-zA-Z0-9]+)\.js/)[1] )
  48. }
  49.  
  50. module.exports = utils
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement