lukehamilton
9/13/2010 - 5:18 AM

twitter.js

var sys = require("sys"), http = require('http'), encode = require('./encoding');

function createAuthorization(username, password) {
    return "Basic " + encode.base64(username + ":" + password);
}

Object.prototype.filter = function(fn) {
    var result = {};
    for (var name in this) {
        if (this.hasOwnProperty(name)) {
            if (fn.call(this[name], name, this[name])) {
                result[name] = this[name];
            }
        }
    }
    return result;
};

Object.prototype.into = function(theArray, fn) {
    for (var name in this) {
        if (this.hasOwnProperty(name)) {
            theArray.push(fn.call(this[name], name, this[name]));
        }
    }
    return theArray;
};

function encodeOptions(options) {
    var parameters = [];
    if (typeof(options) === "object" && options !== null) {
        parameters = options
                        .filter(function(name) {
                            return !(name === "username" || name === "password" || name === "callback");})
                        .into([], function(name, value) {
                            return encodeURIComponent(name) + "=" + encodeURIComponent(value); });
    }
    return parameters.length ? ("?" + parameters.join("&")) : "";
}

exports.query = function(method, options) {
    var client = http.createClient(80, "api.twitter.com");
    var username = options.username, password = options.password;
    var path = "/l/statuses/" + method + ".json" + encodeOptions(options);

    var request = client.request("GET", path, {
        Authorization : createAuthorization(username, password), "host" : "api.twitter.com"
    });

    request.addListener('response', function (res) {
        var tweets = "";

        res.addListener("data", function (chunk) {
            tweets += chunk;
        });

        res.addListener("end", function() {
            options.callback.call(null, JSON.parse(tweets));
        });
    });

    request.close();
};