mirror of
https://github.com/samsonjs/gitter.git
synced 2026-04-27 15:07:41 +00:00
works in Chrome 7 and Safari 5
This commit is contained in:
parent
0045038619
commit
b0254932d0
1 changed files with 385 additions and 304 deletions
305
lib/index.js
305
lib/index.js
|
|
@ -7,13 +7,15 @@
|
||||||
|
|
||||||
// TODO:
|
// TODO:
|
||||||
// - authentication and write APIs
|
// - authentication and write APIs
|
||||||
// - run in browsers (dojo?)
|
|
||||||
|
|
||||||
var request = require('request')
|
(function() {
|
||||||
, util = require('util')
|
var global = this
|
||||||
|
, isBrowser = 'document' in global
|
||||||
|
, request = isBrowser ? xhr : require('request')
|
||||||
, Blob, Branch, Commit, Raw, Repo, Tree, User
|
, Blob, Branch, Commit, Raw, Repo, Tree, User
|
||||||
|
, api
|
||||||
|
|
||||||
module.exports = {
|
api = {
|
||||||
blob: function(repo, sha, path, cb) {
|
blob: function(repo, sha, path, cb) {
|
||||||
return new Blob(repo, sha, path, cb)
|
return new Blob(repo, sha, path, cb)
|
||||||
},
|
},
|
||||||
|
|
@ -74,19 +76,22 @@ module.exports = {
|
||||||
watched: function(user, cb) {
|
watched: function(user, cb) {
|
||||||
return new User(user).getWatched(cb)
|
return new User(user).getWatched(cb)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (isBrowser) global.GITR = api
|
||||||
|
else module.exports = api
|
||||||
|
|
||||||
// Define resources //
|
|
||||||
|
|
||||||
Blob = createResource('blob/show/:repo/:tree/:path', {
|
// Define resources //
|
||||||
|
|
||||||
|
Blob = createResource('blob/show/:repo/:tree/:path', {
|
||||||
has: [ ['commits', 'commits/list/:repo/:tree/:path'] ]
|
has: [ ['commits', 'commits/list/:repo/:tree/:path'] ]
|
||||||
})
|
})
|
||||||
Branch = createResource('commits/show/:repo/:branch', {
|
Branch = createResource('commits/show/:repo/:branch', {
|
||||||
has: [ ['commits', 'commits/list/:repo/:branch'] ]
|
has: [ ['commits', 'commits/list/:repo/:branch'] ]
|
||||||
})
|
})
|
||||||
Commit = createResource('commits/show/:repo/:sha')
|
Commit = createResource('commits/show/:repo/:sha')
|
||||||
Raw = createResource('blob/show/:repo/:sha')
|
Raw = createResource('blob/show/:repo/:sha')
|
||||||
Repo = createResource('repos/show/:repo', {
|
Repo = createResource('repos/show/:repo', {
|
||||||
has: [ 'branches'
|
has: [ 'branches'
|
||||||
, 'collaborators'
|
, 'collaborators'
|
||||||
, 'contributors'
|
, 'contributors'
|
||||||
|
|
@ -95,52 +100,52 @@ Repo = createResource('repos/show/:repo', {
|
||||||
, 'tags'
|
, 'tags'
|
||||||
, 'watchers'
|
, 'watchers'
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
Tree = createResource('tree/show/:repo/:sha', {
|
Tree = createResource('tree/show/:repo/:sha', {
|
||||||
has: [ ['blobs', 'blob/all/:repo/:sha']
|
has: [ ['blobs', 'blob/all/:repo/:sha']
|
||||||
, ['fullBlobs', 'blob/full/:repo/:sha']
|
, ['fullBlobs', 'blob/full/:repo/:sha']
|
||||||
, ['fullTree', 'tree/full/:repo/:sha']
|
, ['fullTree', 'tree/full/:repo/:sha']
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
Tree.prototype._processData = function(data) {
|
Tree.prototype._processData = function(data) {
|
||||||
Resource.prototype._processData.call(this, data)
|
Resource.prototype._processData.call(this, data)
|
||||||
this.blobs = this.data()
|
this.blobs = this.data()
|
||||||
}
|
}
|
||||||
|
|
||||||
User = createResource('user/show/:user', {
|
User = createResource('user/show/:user', {
|
||||||
has: [ 'followers'
|
has: [ 'followers'
|
||||||
, 'following'
|
, 'following'
|
||||||
, ['repos', 'repos/show/:user']
|
, ['repos', 'repos/show/:user']
|
||||||
, ['watched', 'repos/watched/:user']
|
, ['watched', 'repos/watched/:user']
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
|
|
||||||
// Construct a new github resource.
|
// Construct a new github resource.
|
||||||
//
|
//
|
||||||
// options:
|
// options:
|
||||||
// - params: params for constructor (optional, inferred from route if missing)
|
// - params: params for constructor (optional, inferred from route if missing)
|
||||||
// - has: list of related resources, accessors are created for each item
|
// - has: list of related resources, accessors are created for each item
|
||||||
//
|
//
|
||||||
// The members of the `has` list are arrays of the form [name, route, unpack].
|
// The members of the `has` list are arrays of the form [name, route, unpack].
|
||||||
// The first member, name, is used to create an accessor (e.g. getName), and
|
// The first member, name, is used to create an accessor (e.g. getName), and
|
||||||
// is required.
|
// is required.
|
||||||
//
|
//
|
||||||
// Route and unpack are optional. Route specifies the endpoint for this
|
// Route and unpack are optional. Route specifies the endpoint for this
|
||||||
// resource and defaults to the name appended to the main resource's endpoint.
|
// resource and defaults to the name appended to the main resource's endpoint.
|
||||||
//
|
//
|
||||||
// Unpack is a function that extracts the desired value from the object fetched
|
// Unpack is a function that extracts the desired value from the object fetched
|
||||||
// for this resource. It defaults to a function that picks out the only property
|
// for this resource. It defaults to a function that picks out the only property
|
||||||
// from an object, or returns the entire walue if not an object or it contains
|
// from an object, or returns the entire walue if not an object or it contains
|
||||||
// more than one property.
|
// more than one property.
|
||||||
//
|
//
|
||||||
// When passing only the name you may pass it directly without wrapping it in
|
// When passing only the name you may pass it directly without wrapping it in
|
||||||
// an array.
|
// an array.
|
||||||
function createResource(route, options) {
|
function createResource(route, options) {
|
||||||
if (!route) throw new Error('route is required')
|
if (!route) throw new Error('route is required')
|
||||||
options = options || {}
|
options = options || {}
|
||||||
|
|
||||||
var resource = function() { Resource.apply(this, slice(arguments)) }
|
var resource = function() { Resource.apply(this, [].slice.call(arguments)) }
|
||||||
util.inherits(resource, Resource)
|
inherits(resource, Resource)
|
||||||
|
|
||||||
resource.prototype._route = route
|
resource.prototype._route = route
|
||||||
resource.prototype._params = options.params || paramsFromRoute(route)
|
resource.prototype._params = options.params || paramsFromRoute(route)
|
||||||
|
|
@ -167,18 +172,18 @@ function createResource(route, options) {
|
||||||
})
|
})
|
||||||
|
|
||||||
return resource
|
return resource
|
||||||
}
|
}
|
||||||
|
|
||||||
// Assigns the given resource args to the new instance. Sets the path to the
|
// Assigns the given resource args to the new instance. Sets the path to the
|
||||||
// endpoint for main resource data.
|
// endpoint for main resource data.
|
||||||
//
|
//
|
||||||
// If the optional last arg is a function main data is fetched immediately,
|
// If the optional last arg is a function main data is fetched immediately,
|
||||||
// and that function is used as the callback.
|
// and that function is used as the callback.
|
||||||
//
|
//
|
||||||
// If the optional last arg is an object then it is set as the main resource
|
// If the optional last arg is an object then it is set as the main resource
|
||||||
// data.
|
// data.
|
||||||
function Resource(/* ...args, opt: data or callback */) {
|
function Resource(/* ...args, opt: data or callback */) {
|
||||||
var args = slice(arguments)
|
var args = [].slice.call(arguments)
|
||||||
, last = args[args.length - 1]
|
, last = args[args.length - 1]
|
||||||
|
|
||||||
// assign params from args
|
// assign params from args
|
||||||
|
|
@ -191,39 +196,39 @@ function Resource(/* ...args, opt: data or callback */) {
|
||||||
|
|
||||||
if (typeof last === 'function') this.fetch(last)
|
if (typeof last === 'function') this.fetch(last)
|
||||||
else if (typeof last === 'object') this.data(last)
|
else if (typeof last === 'object') this.data(last)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set or get main data for this resource, or fetch
|
// Set or get main data for this resource, or fetch
|
||||||
// a specific property from the data.
|
// a specific property from the data.
|
||||||
//
|
//
|
||||||
// When the data param is empty cached data is returned.
|
// When the data param is empty cached data is returned.
|
||||||
//
|
//
|
||||||
// When the data param is a string the property by that name
|
// When the data param is a string the property by that name
|
||||||
// is looked up in the cached data.
|
// is looked up in the cached data.
|
||||||
//
|
//
|
||||||
// Otherwise cached data is set to the data param.
|
// Otherwise cached data is set to the data param.
|
||||||
Resource.prototype.data = function(data) {
|
Resource.prototype.data = function(data) {
|
||||||
if (!data) return this._data
|
if (!data) return this._data
|
||||||
if (typeof data === 'string' && typeof this._data === 'object') return this._data[data]
|
if (typeof data === 'string' && typeof this._data === 'object') return this._data[data]
|
||||||
|
|
||||||
getter(this, '_data', function() { return data }, {configurable: true})
|
getter(this, '_data', function() { return data }, {configurable: true})
|
||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fetch the main data for this resource.
|
// Fetch the main data for this resource.
|
||||||
//
|
//
|
||||||
// cb: callback(err, data)
|
// cb: callback(err, data)
|
||||||
// force: if true load data from github, bypassing the local cache
|
// force: if true load data from github, bypassing the local cache
|
||||||
Resource.prototype.fetch = function(cb, force) {
|
Resource.prototype.fetch = function(cb, force) {
|
||||||
return this._fetch({ prop: '_data'
|
return this._fetch({ prop: '_data'
|
||||||
, route: this.urlPath
|
, route: this.urlPath
|
||||||
, processData: this._processData.bind(this)
|
, processData: this._processData.bind(this)
|
||||||
, result: function(resource) { return resource }
|
, result: function(resource) { return resource }
|
||||||
}, cb.bind(this), force)
|
}, cb.bind(this), force)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 'repos/show/:user/:repo/branches' -> 'repos/show/samsonjs/gitter
|
// 'repos/show/:user/:repo/branches' -> 'repos/show/samsonjs/gitter
|
||||||
Resource.prototype.resolve = function(route) { // based on crock's supplant
|
Resource.prototype.resolve = function(route) { // based on crock's supplant
|
||||||
if (route.indexOf(':') < 0) return route
|
if (route.indexOf(':') < 0) return route
|
||||||
return route.replace(/:(\w+)\b/g, function (s, prop) {
|
return route.replace(/:(\w+)\b/g, function (s, prop) {
|
||||||
var val = this[prop]
|
var val = this[prop]
|
||||||
|
|
@ -231,18 +236,18 @@ Resource.prototype.resolve = function(route) { // based on crock's supplant
|
||||||
throw new Error('no suitable property named "' + prop + '" (found ' + val + ')')
|
throw new Error('no suitable property named "' + prop + '" (found ' + val + ')')
|
||||||
return val
|
return val
|
||||||
}.bind(this))
|
}.bind(this))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fetch arbitrary data from github.
|
// Fetch arbitrary data from github.
|
||||||
//
|
//
|
||||||
// options:
|
// options:
|
||||||
// - prop: name of data cache property
|
// - prop: name of data cache property
|
||||||
// - route: route to github endpoint (can contain resource params)
|
// - route: route to github endpoint (can contain resource params)
|
||||||
// - processData: function that processes fetched data
|
// - processData: function that processes fetched data
|
||||||
// - result: function to obtain the result passed to the callback
|
// - result: function to obtain the result passed to the callback
|
||||||
// cb: callback(err, data)
|
// cb: callback(err, data)
|
||||||
// force: if true load data from github, bypassing the local cache
|
// force: if true load data from github, bypassing the local cache
|
||||||
Resource.prototype._fetch = function(options, cb, force) {
|
Resource.prototype._fetch = function(options, cb, force) {
|
||||||
if (!force && this[options.prop]) {
|
if (!force && this[options.prop]) {
|
||||||
cb(null, options.result(this))
|
cb(null, options.result(this))
|
||||||
return this
|
return this
|
||||||
|
|
@ -260,16 +265,18 @@ Resource.prototype._fetch = function(options, cb, force) {
|
||||||
options.processData(data)
|
options.processData(data)
|
||||||
cb(null, options.result(this))
|
cb(null, options.result(this))
|
||||||
}.bind(this))
|
}.bind(this))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fetch data from github. JSON responses are parsed.
|
// Fetch data from github. JSON responses are parsed.
|
||||||
//
|
//
|
||||||
// path: github endpoint
|
// path: github endpoint
|
||||||
// cb: callback(err, data)
|
// cb: callback(err, data)
|
||||||
Resource.prototype._get = function(path, cb) {
|
Resource.prototype._get = function(path, cb) {
|
||||||
request({uri: 'http://github.com/api/v2/json/' + path}, function(err, response, body) {
|
request({uri: 'http://github.com/api/v2/json/' + path}, function(err, response, body) {
|
||||||
if (err)
|
if (err)
|
||||||
cb(err)
|
cb(err)
|
||||||
|
else if (isBrowser)
|
||||||
|
cb(null, body) // body is an object
|
||||||
else if (response.statusCode !== 200)
|
else if (response.statusCode !== 200)
|
||||||
cb(new Error('failed to fetch ' + path + ': ' + response.statusCode))
|
cb(new Error('failed to fetch ' + path + ': ' + response.statusCode))
|
||||||
else if (response.headers['content-type'].match(/json/))
|
else if (response.headers['content-type'].match(/json/))
|
||||||
|
|
@ -278,54 +285,128 @@ Resource.prototype._get = function(path, cb) {
|
||||||
cb(null, body)
|
cb(null, body)
|
||||||
})
|
})
|
||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
|
|
||||||
// Descendents of Resource can overwrite _processData and _unpack to process
|
// Descendents of Resource can overwrite _processData and _unpack to process
|
||||||
// the main resource data differently.
|
// the main resource data differently.
|
||||||
|
|
||||||
Resource.prototype._processData = function(data) {
|
Resource.prototype._processData = function(data) {
|
||||||
return this.data(camelize(this._unpack(data)))
|
return this.data(camelize(this._unpack(data)))
|
||||||
}
|
}
|
||||||
Resource.prototype._unpack = onlyProp
|
Resource.prototype._unpack = onlyProp
|
||||||
|
|
||||||
|
|
||||||
// Utilities //
|
// Utilities //
|
||||||
|
|
||||||
function camel(s) { // created_at => createdAt
|
function camel(s) { // created_at => createdAt
|
||||||
return s.replace(/_(.)/g, function(_, l) { return l.toUpperCase() })
|
return s.replace(/_(.)/g, function(_, l) { return l.toUpperCase() })
|
||||||
}
|
}
|
||||||
function camelize(obj) { // camelize all keys of an object, or all objects in an array
|
function camelize(obj) { // camelize all keys of an object, or all objects in an array
|
||||||
if (!obj || typeof obj === 'string') return obj
|
if (!obj || typeof obj === 'string') return obj
|
||||||
if (Array.isArray(obj)) return obj.map(camelize)
|
if (Array.isArray(obj)) return obj.map(camelize)
|
||||||
return Object.keys(obj).reduce(function(newObj, k) {
|
return Object.keys(obj).reduce(function(newObj, k) {
|
||||||
newObj[camel(k)] = obj[k]
|
newObj[camel(k)] = obj[k]
|
||||||
return newObj
|
return newObj
|
||||||
}, {})
|
}, {})
|
||||||
}
|
}
|
||||||
|
|
||||||
function getter(obj, prop, fn, opts) { // minor convenience
|
function getter(obj, prop, fn, opts) { // minor convenience
|
||||||
opts = opts || {}
|
opts = opts || {}
|
||||||
opts.get = fn
|
opts.get = fn
|
||||||
Object.defineProperty(obj, prop, opts)
|
Object.defineProperty(obj, prop, opts)
|
||||||
}
|
}
|
||||||
|
|
||||||
// get an only property, if any
|
function inherits(ctor, superCtor) {
|
||||||
function onlyProp(obj) {
|
ctor.super_ = superCtor
|
||||||
|
ctor.prototype = Object.create(superCtor.prototype, {
|
||||||
|
constructor: {
|
||||||
|
value: ctor,
|
||||||
|
enumerable: false
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function xhr(options, cb) {
|
||||||
|
GITR._jsonpCallback = function(obj) {
|
||||||
|
cb(null, null, obj)
|
||||||
|
}
|
||||||
|
;(function (global, oDOC, handler) {
|
||||||
|
options.uri += '?callback=GITR._jsonpCallback'
|
||||||
|
var head = oDOC.head || oDOC.getElementsByTagName("head")
|
||||||
|
|
||||||
|
// loading code borrowed directly from LABjs itself
|
||||||
|
setTimeout(function () {
|
||||||
|
if ("item" in head) { // check if ref is still a live node list
|
||||||
|
if (!head[0]) { // append_to node not yet ready
|
||||||
|
setTimeout(arguments.callee, 25)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
head = head[0]; // reassign from live node list ref to pure node ref -- avoids nasty IE bug where changes to DOM invalidate live node lists
|
||||||
|
}
|
||||||
|
var scriptElem = oDOC.createElement("script"),
|
||||||
|
scriptdone = false
|
||||||
|
scriptElem.onload = scriptElem.onreadystatechange = function () {
|
||||||
|
if ((scriptElem.readyState && scriptElem.readyState !== "complete" && scriptElem.readyState !== "loaded") || scriptdone) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
scriptElem.onload = scriptElem.onreadystatechange = null
|
||||||
|
scriptdone = true
|
||||||
|
};
|
||||||
|
scriptElem.src = options.uri
|
||||||
|
head.insertBefore(scriptElem, head.firstChild)
|
||||||
|
}, 0)
|
||||||
|
|
||||||
|
// required: shim for FF <= 3.5 not having document.readyState
|
||||||
|
if (oDOC.readyState == null && oDOC.addEventListener) {
|
||||||
|
oDOC.readyState = "loading"
|
||||||
|
oDOC.addEventListener("DOMContentLoaded", handler = function () {
|
||||||
|
oDOC.removeEventListener("DOMContentLoaded", handler, false)
|
||||||
|
oDOC.readyState = "complete"
|
||||||
|
}, false)
|
||||||
|
}
|
||||||
|
})(window, document)
|
||||||
|
}
|
||||||
|
|
||||||
|
// get an only property, if any
|
||||||
|
function onlyProp(obj) {
|
||||||
if (obj && typeof obj === 'object') {
|
if (obj && typeof obj === 'object') {
|
||||||
var keys = Object.keys(obj)
|
var keys = Object.keys(obj)
|
||||||
if (keys.length === 1) return obj[keys[0]]
|
if (keys.length === 1) return obj[keys[0]]
|
||||||
}
|
}
|
||||||
return obj
|
return obj
|
||||||
}
|
}
|
||||||
|
|
||||||
// 'repos/show/:user/:repo/branches' -> ['user', 'repo']
|
// 'repos/show/:user/:repo/branches' -> ['user', 'repo']
|
||||||
function paramsFromRoute(route) {
|
function paramsFromRoute(route) {
|
||||||
if (route.indexOf(':') === -1) return []
|
if (route.indexOf(':') === -1) return []
|
||||||
return route.split('/')
|
return route.split('/')
|
||||||
.filter(function(s) { return s.charAt(0) === ':' })
|
.filter(function(s) { return s.charAt(0) === ':' })
|
||||||
.map(function(s) { return s.slice(1) })
|
.map(function(s) { return s.slice(1) })
|
||||||
}
|
}
|
||||||
|
|
||||||
function slice(x) { return [].slice.call(x) }
|
function titleCaseFirst(s) { return s.charAt(0).toUpperCase() + s.slice(1) }
|
||||||
|
|
||||||
function titleCaseFirst(s) { return s.charAt(0).toUpperCase() + s.slice(1) }
|
if (isBrowser) {
|
||||||
|
function update(array, args) {
|
||||||
|
var arrayLength = array.length, length = args.length;
|
||||||
|
while (length--) array[arrayLength + length] = args[length];
|
||||||
|
return array;
|
||||||
|
}
|
||||||
|
|
||||||
|
function merge(array, args) {
|
||||||
|
array = [].slice.call(array, 0);
|
||||||
|
return update(array, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Function.prototype.bind) {
|
||||||
|
Function.prototype.bind = function(context) {
|
||||||
|
if (arguments.length < 2 && typeof arguments[0] === 'undefined') return this
|
||||||
|
var __method = this, args = [].slice.call(arguments, 1)
|
||||||
|
return function() {
|
||||||
|
var a = merge(args, arguments)
|
||||||
|
return __method.apply(context, a)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}())
|
||||||
Loading…
Reference in a new issue