Skip to content
This repository has been archived by the owner on May 13, 2021. It is now read-only.

Plugin validate #1

Closed
zce opened this issue Aug 18, 2017 · 1 comment
Closed

Plugin validate #1

zce opened this issue Aug 18, 2017 · 1 comment

Comments

@zce
Copy link
Owner

zce commented Aug 18, 2017

wrapper.js

/**
 * Wrapper plugin
 * @param  {Function} plugin Plugin function
 * @return {Function}        Plugin function
 */
const defaultPlugin = (files, app, next) => next()

module.exports = plugin => {
  if (typeof plugin !== 'function') return defaultPlugin

  const fnStr = plugin.toString()
  const matches = /\(\s*([\s\S]*?)\s*\)/.exec(fnStr)

  if (!matches) return defaultPlugin

  const params = matches[1].split(/\s*,\s*/)

  if (params.length !== 3) return defaultPlugin

  // https://github.com/goatslacker/get-parameter-names/blob/master/index.js
  const code = fnStr.replace(/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg, '')

  const regexp = new RegExp(`${params[2]}\\(\\s*\\)`)
  return regexp.test(code) ? plugin : defaultPlugin
}
@zce
Copy link
Owner Author

zce commented Aug 18, 2017

wrapper.test.js

const assert = require('assert')
const plugin = require('../../lib/plugin')

describe('lib/plugin', () => {
  it('Should return default plugin when input plugin is invaild', () => {
    assert.equal(
      undefined,
      plugin('')(1, 2, () => {})
    )
  })

  it('Should return default plugin when input plugin is invaild', () => {
    assert.equal(
      undefined,
      plugin(foo => {
        return 'fake'
      })(1, 2, () => {})
    )
  })

  it('Should return default plugin when input plugin is invaild', () => {
    assert.equal(
      undefined,
      plugin((foo, bar) => {
        return 'fake'
      })(1, 2, () => {})
    )
  })

  it('Should return default plugin when input plugin is invaild', () => {
    assert.equal(
      undefined,
      plugin((foo, bar, baz) => {
        return 'fake'
      })(1, 2, () => {})
    )
  })

  it('Should return default plugin when input plugin is invaild', () => {
    assert.equal(
      undefined,
      plugin((foo, bar, baz) => {
        console.log()
        return 'fake'
      })(1, 2, () => {})
    )
  })

  it('Should return input plugin when input plugin is vaild', () => {
    assert.equal(
      'fake',
      plugin((foo, bar, baz) => {
        baz()
        return 'fake'
      })(1, 2, () => {})
    )
  })
})

@zce zce closed this as completed Apr 25, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant