├── .editorconfig ├── .gitattributes ├── .gitignore ├── index.js ├── license ├── optimization-test.js ├── package.json ├── readme.md └── test.js /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = tab 5 | end_of_line = lf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | 10 | [{package.json,*.yml}] 11 | indent_style = space 12 | indent_size = 2 13 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .idea 3 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var processFn = function (fn, P, context, opts) { 4 | return function () { 5 | var args = new Array(arguments.length); 6 | 7 | for (var i = 0; i < arguments.length; i++) { 8 | args[i] = arguments[i]; 9 | } 10 | 11 | return new P(function (resolve, reject) { 12 | args.push(function (err, result) { 13 | if (err) { 14 | reject(err); 15 | } else { 16 | 17 | if (opts.multiArgs) { 18 | 19 | var results = new Array(arguments.length - 1); 20 | 21 | for (var i = 1; i < arguments.length; i++) { 22 | results[i - 1] = arguments[i]; 23 | } 24 | 25 | resolve(results); 26 | 27 | } else { 28 | resolve(result); 29 | } 30 | } 31 | }); 32 | 33 | fn.apply(context, args); 34 | }); 35 | } 36 | }; 37 | 38 | module.exports = function (obj, P, opts) { 39 | var proto = Object.getPrototypeOf(obj) 40 | 41 | if (!proto) { 42 | throw new Error('object has no prototype') 43 | } 44 | 45 | if (typeof P !== 'function') { 46 | opts = P; 47 | P = Promise; 48 | } 49 | 50 | opts = opts || {}; 51 | 52 | var exclude = opts.exclude || [/.+Sync$/]; 53 | 54 | var filter = function (key) { 55 | var match = function (pattern) { 56 | return typeof pattern === 'string' ? key === pattern : pattern.test(key); 57 | }; 58 | 59 | return opts.include ? opts.include.some(match) : !exclude.some(match); 60 | }; 61 | 62 | var newProto = Object.keys(proto).reduce(function (newProto, key) { 63 | var x = obj[key]; 64 | 65 | if (typeof x === 'function' && filter(key)) { 66 | newProto[key] = processFn(x, P, obj, opts) 67 | } else if (typeof x === 'function') { 68 | newProto[key] = x.bind(obj) 69 | } else { 70 | newProto[key] = x 71 | } 72 | 73 | return newProto; 74 | }, {}); 75 | 76 | var props = Object.keys(obj).reduce(function (props, key) { 77 | props[key] = Object.getOwnPropertyDescriptor(obj, key) 78 | return props 79 | }, {}) 80 | 81 | return Object.create(newProto, props) 82 | }; 83 | -------------------------------------------------------------------------------- /license: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016 Sam Gluck 2 | 3 | MIT License 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining 6 | a copy of this software and associated documentation files (the 7 | "Software"), to deal in the Software without restriction, including 8 | without limitation the rights to use, copy, modify, merge, publish, 9 | distribute, sublicense, and/or sell copies of the Software, and to 10 | permit persons to whom the Software is furnished to do so, subject to 11 | the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be 14 | included in all copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 19 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 20 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 22 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 23 | -------------------------------------------------------------------------------- /optimization-test.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-fallthrough */ 2 | 'use strict'; 3 | var assert = require('assert'); 4 | var Promise = require('pinkie-promise'); 5 | var v8 = require('v8-natives'); 6 | var fn = require('./'); 7 | 8 | function assertOptimized(fn, name) { 9 | var status = v8.getOptimizationStatus(fn); 10 | 11 | switch (status) { 12 | case 1: 13 | // fn is optimized 14 | return; 15 | case 2: 16 | assert(false, name + ' is not optimized (' + status + ')'); 17 | case 3: 18 | // fn is always optimized 19 | return; 20 | case 4: 21 | assert(false, name + ' is never optimized (' + status + ')'); 22 | case 6: 23 | assert(false, name + ' is maybe deoptimized (' + status + ')'); 24 | default: 25 | assert(false, 'unknown OptimizationStatus: ' + status + ' (' + name + ')'); 26 | } 27 | } 28 | 29 | var sut = fn(Object.create({ 30 | unicorn: function (cb) { 31 | cb(null, 'unicorn'); 32 | } 33 | }), Promise); 34 | 35 | sut.unicorn().then(function () { 36 | v8.optimizeFunctionOnNextCall(sut.unicorn); 37 | 38 | return sut.unicorn().then(function () { 39 | assertOptimized(sut.unicorn, 'unicorn'); 40 | }); 41 | }).catch(function (err) { 42 | console.log(err.stack); 43 | process.exit(1); 44 | }); 45 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "pify-proto", 3 | "version": "0.2.0", 4 | "description": "Promisify methods on the prototype of an object", 5 | "license": "MIT", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/sdgluck/pify-proto.git" 9 | }, 10 | "author": "Sam Gluck ", 11 | "engines": { 12 | "node": ">=0.10.0" 13 | }, 14 | "scripts": { 15 | "test": "ava && npm run optimization-test", 16 | "optimization-test": "node --allow-natives-syntax optimization-test.js" 17 | }, 18 | "files": [ 19 | "index.js" 20 | ], 21 | "keywords": [ 22 | "promise", 23 | "promises", 24 | "promisify", 25 | "denodify", 26 | "denodeify", 27 | "callback", 28 | "cb", 29 | "node", 30 | "then", 31 | "thenify", 32 | "convert", 33 | "transform", 34 | "wrap", 35 | "wrapper", 36 | "bind", 37 | "to", 38 | "async", 39 | "es2015", 40 | "prototype" 41 | ], 42 | "devDependencies": { 43 | "ava": "*", 44 | "pinkie-promise": "^2.0.0", 45 | "v8-natives": "0.0.2" 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # pify-proto 2 | 3 | > Promisify methods on the prototype of an object 4 | 5 | npm version 6 | 7 | - Exclusively for promisfying enumerable methods on a prototype 8 | - Does not modify the original object prototype; returns a copy with a new prototype* 9 | - Only `include`/`exclude`/`multiArgs` options (I don't need the others; always open to PRs) 10 | 11 | _* In order that the lib can operate normally if it uses any method internally 12 | (because it will be passing callbacks as per original method signature)._ 13 | 14 | --- 15 | 16 | Credit goes to [Sindre Sorhus](http://sindresorhus.com) 17 | and other contributors of [`pify`](https://github.com/sindresorhus/pify), 18 | for which this is a fork. Thanks y'all! 19 | 20 | ## Install 21 | 22 | ``` 23 | $ npm install --save pify-proto 24 | ``` 25 | 26 | ## Usage 27 | 28 | ```js 29 | const pify = require('pify-proto'); 30 | 31 | class SomeConstructor { 32 | constructor () { 33 | this.foo = 'bar' 34 | } 35 | 36 | baz (cb) { 37 | cb(null, this.foo) 38 | } 39 | } 40 | 41 | // promisify prototype of an object 42 | 43 | const inst = pify(new SomeConstructor()) 44 | 45 | inst.baz().then(console.log.bind(console)) 46 | //=> 'foo' 47 | ``` 48 | 49 | ## API 50 | 51 | ### pify(input, [promiseModule], [options]) 52 | 53 | Returns a new object with prototype methods on `obj` promisified. 54 | 55 | #### input 56 | 57 | Type: `object` 58 | 59 | The object to promisify. 60 | 61 | #### promiseModule 62 | 63 | Type: `function` 64 | 65 | Custom promise module to use instead of the native one. 66 | 67 | Check out [`pinkie-promise`](https://github.com/floatdrop/pinkie-promise) if you need a tiny promise polyfill. 68 | 69 | #### options 70 | 71 | ##### include 72 | 73 | Type: `array` of (`string`|`regex`) 74 | 75 | Methods in a module to promisify. Remaining methods will be left untouched. 76 | 77 | ##### exclude 78 | 79 | Type: `array` of (`string`|`regex`)
80 | Default: `[/.+Sync$/]` 81 | 82 | Methods in a module **not** to promisify. Methods with names ending with `'Sync'` are excluded by default. 83 | 84 | ##### multiArgs 85 | 86 | Type: `boolean`
87 | Default: `false` 88 | 89 | By default, the promisified methods will only return the second argument from the callback, which works fine for most APIs. This option can be useful for modules like `oauth` with prototype methods that return multiple arguments. Turning this on will make it return an array of all arguments from the callback, excluding the error argument, instead of just the second argument. 90 | 91 | ```js 92 | const OAuth = require('oauth').OAuth; 93 | const pify = require('pify-proto'); 94 | 95 | const oauth = pify(new OAuth( 96 | 'http://blah', 97 | 'http://blah', 98 | 'blah blah' 99 | ), {multiArgs: true}); 100 | 101 | oauth.getOAuthRequestToken() 102 | .then(result => { 103 | const [ oauth_token, oauth_secret ] = result; 104 | }); 105 | ``` 106 | 107 | ## Authors & License 108 | 109 | `pify` was created by [Sindre Sorhus](http://sindresorhus.com). 110 | 111 | `pify-proto` was created by [Sam Gluck](https://twitter.com/sdgluck). 112 | 113 | `pify-proto` contributors: 114 | 115 | * [Scott Donnelly (@sdd)](https://github.com/sdd) 116 | 117 | `pify-proto` is released under the MIT license. 118 | -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | import test from 'ava'; 2 | import pinkiePromise from 'pinkie-promise'; 3 | import pify from './'; 4 | 5 | global.Promise = pinkiePromise; 6 | 7 | function Fixture() {} 8 | 9 | Fixture.prototype.spongebob = 'squarepants' 10 | Fixture.prototype.englebert = 'humperdink' 11 | Fixture.prototype.methodSync = () => 'unicorn' 12 | Fixture.prototype.method1 = cb => setImmediate(() => cb(null, 'unicorn')); 13 | Fixture.prototype.method2 = (x, cb) => setImmediate(() => cb(null, x)); 14 | Fixture.prototype.method3 = cb => setImmediate(() => cb(null)); 15 | Fixture.prototype.method4 = function (cb) { setImmediate(() => this.method1(cb)) } 16 | Fixture.prototype.method5 = function (cb) { cb(null, this.spongebob) } 17 | Fixture.prototype.method6 = function (cb) { cb(null, this.spongebob, this.englebert) } 18 | 19 | const pifyd = pify(new Fixture()); 20 | const pifyd_MultiArgs = pify(new Fixture(), { multiArgs: true }); 21 | 22 | test('fails with no prototype', async t => { 23 | t.throws(() => pify(Object.create(null))) 24 | }); 25 | 26 | test('main', async t => { 27 | t.is(typeof pifyd.method1().then, 'function'); 28 | t.is(await pifyd.method1(), 'unicorn'); 29 | }); 30 | 31 | test('pass argument', async t => { 32 | t.is(await pifyd.method2('rainbow'), 'rainbow'); 33 | }); 34 | 35 | test('custom Promise module', async t => { 36 | t.is(await pify(new Fixture(), pinkiePromise).method1(), 'unicorn'); 37 | }); 38 | 39 | test('multiArgs option', async t => { 40 | t.deepEqual(await pifyd_MultiArgs.method6(), ['squarepants', 'humperdink']); 41 | }); 42 | 43 | test('doesn\'t transform *Sync methods by default', t => { 44 | t.is(pifyd.methodSync(), 'unicorn'); 45 | }); 46 | 47 | test('ensures execution context is original obj when included', async t => { 48 | t.is(await pifyd.method4(), 'unicorn') 49 | }); 50 | 51 | test('ensures execution context is original obj when excluded', async t => { 52 | const pifyd = pify(new Fixture(), { 53 | exclude: ['method5'] 54 | }); 55 | 56 | pifyd.method5((err, spongebob) => t.is(spongebob, 'squarepants')) 57 | }); 58 | 59 | test('preserves own properties', t => { 60 | const inst = new Fixture() 61 | inst.prop = 1 62 | t.is(pify(inst).prop, 1) 63 | }) 64 | 65 | test('transforms only members in options.include', t => { 66 | const pifyd = pify(new Fixture(), { 67 | include: ['method1', 'method2'] 68 | }); 69 | 70 | t.is(typeof pifyd.method1().then, 'function'); 71 | t.is(typeof pifyd.method2(123).then, 'function'); 72 | t.not(typeof pifyd.method3(() => {}), 'function'); 73 | }); 74 | 75 | test('doesn\'t transform members in options.exclude', t => { 76 | const pifyd = pify(new Fixture(), { 77 | exclude: ['method3'] 78 | }); 79 | 80 | t.is(typeof pifyd.method1().then, 'function'); 81 | t.is(typeof pifyd.method2(123).then, 'function'); 82 | t.not(typeof pifyd.method3(() => {}).then, 'function'); 83 | }); 84 | 85 | test('options.include over options.exclude', t => { 86 | const pifyd = pify(new Fixture(), { 87 | include: ['method1', 'method2'], 88 | exclude: ['method2', 'method3'] 89 | }); 90 | 91 | t.is(typeof pifyd.method1().then, 'function'); 92 | t.is(typeof pifyd.method2(123).then, 'function'); 93 | t.not(typeof pifyd.method3(() => {}).then, 'function'); 94 | }); 95 | 96 | test('preserves non-function members', t => { 97 | const module = Object.create({ 98 | method: function () {}, 99 | nonMethod: 3 100 | }); 101 | 102 | t.deepEqual( 103 | Object.keys(Object.getPrototypeOf(module)), 104 | Object.keys(Object.getPrototypeOf(pify(module))) 105 | ); 106 | }); 107 | --------------------------------------------------------------------------------