ngageoint / endpoint.js

Web application discovery, execution and streaming library
http://ngageoint.github.io/endpoint.js/
Apache License 2.0
26 stars 5 forks source link

Add streamify method to easily make methods support streaming #11

Open datasedai opened 8 years ago

datasedai commented 8 years ago

Endpoint.js should have a utility method to help users "streamify" their existing API functions. Basically, it will create a wrapper around the function that checks for a stream, and if so, it will read entries, call the function, and reply by writing to the output stream or the inputstream if output isn't present.

Something like this:

function streamify(func, ah) {

    return function() {
        var ctx = ah.adapter.getCurrentContext();
        if (ctx.hasInputStream() && ctx.hasOutputStream()) {
            inp = ctx.getInputStream();
            oup = ctx.getOutputStream();
            inp.on('readable', function() {
                var data;
                while ((data = inp.read()) !== null) {
                    var result = func.apply(func, data);
                    oup.write(result);
                }
            });
            inp.on('end', ctx.cancel.bind(ctx));
            oup.on('end', ctx.cancel.bind(ctx));
        }
        else if (ctx.hasInputStream()) {
            inp = ctx.getInputStream();
            inp.on('readable', function() {
                var data;
                while ((data = inp.read()) !== null) {
                    var result = func.apply(func, data);
                    inp.write(result);
                }
            });
            inp.on('end', ctx.cancel.bind(ctx));
        }
        else {
            return func.apply(func, arguments);
        }
    }

}