Skip to content

Commit

Permalink
Initial Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
lspecian committed May 13, 2014
0 parents commit 813ffdd
Show file tree
Hide file tree
Showing 38 changed files with 2,329 additions and 0 deletions.
23 changes: 23 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
lib-cov
*.seed
*.log
*.csv
*.dat
*.out
*.pid
*.gz
*.swp

pids
logs
results
tmp

npm-debug.log
node_modules
.idea
*.iml
.DS_Store
Thumbs.db

buildAssets
8 changes: 8 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
0.0.3 May 13, 2014
- Refactored to new Architecture

0.0.2 May 5, 2014
- Changes on the package.json

0.0.1 May 5, 2014
- Initial release
41 changes: 41 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Iugu para node.js [![Build Status](https://travis-ci.org/lspecian/iugu-node.png?branch=pos-refactor)](https://travis-ci.org/lspecian/iugu-node)

## Instalação

`npm install iugu`

## Exemplo de Uso
```js
var iugu = require('iugu')('c73d49f9-6490-46ee-ba36-dcf69f6334fd'); // Ache sua chave API no Painel
// iugu.{ RESOURCE_NAME }.{ METHOD_NAME }
```
Todo método aceita um callback opcional como ultimo argumento:

```js
iugu.customer.create({
'email': '[email protected]',
'name': 'Nome do Cliente',
'notes': 'Anotações Gerais'
}, function(err, customer) {
err; // null se não ocorreu nenhum erro
customer; // O objeto de retorno da criação
}
);
```

## Documentação
Acesse [iugu.com/documentacao](http://iugu.com/documentacao) para referência

## Configuração

* `iugu.setApiKey('c73d49f9-6490-46ee-ba36-dcf69f6334fd');`
* `iugu.setTimeout(20000); // in ms` (node's default: `120000ms`)

## Testes
Execute :

`npm test`

## Autor

Originalmente por [Luis Specian](https://github.com/lspecian) ([email protected]).
1 change: 1 addition & 0 deletions VERSION
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
0.0.3
66 changes: 66 additions & 0 deletions lib/Error.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
'use strict';

var utils = require('./utils');

module.exports = _Error;

/**
* Generic Error class to wrap any errors returned by iugu-node
*/
function _Error(raw) {
this.populate.apply(this, arguments);
}

// Extend Native Error
_Error.prototype = Object.create(Error.prototype);

_Error.prototype.type = 'GenericError';
_Error.prototype.populate = function(type, message) {
this.type = type;
this.message = message;
};

_Error.extend = utils.protoExtend;

/**
* Create subclass of internal Error class
* (Specifically for errors returned from Iugu's REST API)
*/
var IuguError = _Error.IuguError = _Error.extend({
type: 'IuguError',
populate: function(raw) {

// Move from prototype def (so it appears in stringified obj)
this.type = this.type;

this.rawType = raw.type;
this.code = raw.code;
this.param = raw.param;
this.message = raw.message;
this.detail = raw.detail;
this.raw = raw;

}
});

/**
* Helper factory which takes raw iugu errors and outputs wrapping instances
*/
IuguError.generate = function(rawIuguError) {
switch (rawIuguError.type) {
case 'card_error':
return new _Error.IuguCardError(rawIuguError);
case 'invalid_request_error':
return new _Error.IuguInvalidRequestError(rawIuguError);
case 'api_error':
return new _Error.IuguAPIError(rawIuguError);
}
return new _Error('Generic', 'Unknown Error');
};

// Specific Stripe Error types:
_Error.IuguCardError = IuguError.extend({ type: 'IuguCardError' });
_Error.IuguInvalidRequestError = IuguError.extend({ type: 'IuguInvalidRequest' });
_Error.IuguAPIError = IuguError.extend({ type: 'IuguAPIError' });
_Error.IuguAuthenticationError = IuguError.extend({ type: 'IuguAuthenticationError' });
_Error.IuguConnectionError = IuguError.extend({ type: 'IuguConnectionError' });
35 changes: 35 additions & 0 deletions lib/IuguMethod.basic.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
'use strict';

var iuguMethod = require('./IuguMethod');
var utils = require('./utils');

module.exports = {

create: iuguMethod({
method: 'POST'
}),

list: iuguMethod({
method: 'GET'
}),

retrieve: iuguMethod({
method: 'GET',
path: '/{id}',
urlParams: ['id']
}),

update: iuguMethod({
method: 'POST',
path: '{id}',
urlParams: ['id']
}),

// Avoid 'delete' keyword in JS
del: iuguMethod({
method: 'DELETE',
path: '{id}',
urlParams: ['id']
})

};
66 changes: 66 additions & 0 deletions lib/IuguMethod.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
'use strict';

var path = require('path');
var utils = require('./utils');

/**
* Create an API method from the declared spec.
*
* @param [spec.method='GET'] Request Method (POST, GET, DELETE, PUT)
* @param [spec.path=''] Path to be appended to the API BASE_PATH, joined with
* the instance's path (e.g. "charges" or "customers")
* @param [spec.required=[]] Array of required arguments in the order that they
* must be passed by the consumer of the API. Subsequent optional arguments are
* optionally passed through a hash (Object) as the penultimate argument
* (preceeding the also-optional callback argument
*/
module.exports = function iuguMethod(spec) {

var commandPath = utils.makeURLInterpolator( spec.path || '' );
var requestMethod = (spec.method || 'GET').toUpperCase();
var urlParams = spec.urlParams || [];

return function() {

var self = this;
var args = [].slice.call(arguments);

var callback = typeof args[args.length - 1] == 'function' && args.pop();
var auth = args.length > urlParams.length && utils.isAuthKey(args[args.length - 1]) ? args.pop() : null;
var data = utils.isObject(args[args.length - 1]) ? args.pop() : {};
var urlData = this.createUrlData();

var deferred = this.createDeferred(callback);

for (var i = 0, l = urlParams.length; i < l; ++i) {
var arg = args[0];
if (urlParams[i] && !arg) {
throw new Error('Iugu: I require argument "' + urlParams[i] + '", but I got: ' + arg);
}
urlData[urlParams[i]] = args.shift();
}

if (args.length) {
throw new Error(
'Iugu: Unknown arguments (' + args + '). Did you mean to pass an options object? '
);
}

var requestPath = this.createFullPath(commandPath, urlData);

self._request(requestMethod, requestPath, data, auth, function(err, response) {
if (err) {
deferred.reject(err);
} else {
deferred.resolve(
spec.transformResponseData ?
spec.transformResponseData(response) :
response
);
}
});

return deferred.promise;

};
};
Loading

0 comments on commit 813ffdd

Please sign in to comment.