Reputation: 10360
I have to write a shim for another abandoned npm library.
This library will be called by others using the new
keyword. This is what others do:
const Noble = require('noble/lib/noble');
var nobleInstance = new Noble(macBindings);
module.exports = nobleInstance;
Now I wrote a shim that changes what is being imported via require('noble/lib/noble');
. To make things nice for myself I want to change what
new Noble(macBindings);
is returning so whenever I call
require('third-pary-library-using-new-noble');
I will actually get my own return value.
so for this I need to change what new Noble(macBindings);
is returning. Reminder. I already managed to shim the Noble
Function.
What I am wondering is if it is possible to change what is being returned when someone calls the function with the new
keyword.
In the end, what I want to achieve is that when someone calls
var nobleInstance = new Noble(macBindings);
I want nobleInstance
to be macBindings
.
Upvotes: 1
Views: 52
Reputation: 1410
You can't replace the instance returned when you call new Noble(...)
as far as I know, but you can make your Noble
have the same methods and functions of macBindings
by iterating through the object, more or less as follows.
function Noble(arg) {
for(var key in arg) {
this[key] = arg[key];
}
}
You might have to work around the above code a little bit (changing the scope or limiting the properties that get copied over) and it might not fit your case 100%, but it should be a decent starting point.
Broadly speaking what you want to do is to build your own version of Noble
implementing the same methods and properties as the original version, possibly informing the user that Noble
is deprecated and should be removed by a certain date, in order to promote refactorings meant to move away from the abandoned library.
Upvotes: 1