Skip to content

Instantly share code, notes, and snippets.

@gpincheiraa
Last active August 23, 2016 03:27
Show Gist options
  • Save gpincheiraa/fb1cff50eff4d5e2c70ebda0ef80853d to your computer and use it in GitHub Desktop.
Save gpincheiraa/fb1cff50eff4d5e2c70ebda0ef80853d to your computer and use it in GitHub Desktop.
Loopback Models ES6
import request from 'request-promise';
var token = process.env.SBIF_TOKEN_URL,
api_url = process.env.SBIF_API_URL;
class SbifApi{
constructor(SbifModel){
//map remote methods to class methods. Set an extra this using the .bind function
SbifModel.uf = this.getData.bind(SbifModel, 'uf');
SbifModel.utm = this.getData.bind(SbifModel, 'utm');
SbifModel.ipc = this.getData.bind(SbifModel, 'ipc');
SbifModel.dolar = this.getData.bind(SbifModel, 'dolar');
SbifModel.euro = this.getData.bind(SbifModel, 'euro');
//Set remotes
this.setRemotes(SbifModel, {name: 'uf', path: '/uf', root: 'uf'});
this.setRemotes(SbifModel, {name: 'utm', path: '/utm', root: 'utm'});
this.setRemotes(SbifModel, {name: 'ipc', path: '/ipc', root: 'ipc'});
this.setRemotes(SbifModel, {name: 'dolar', path: '/dolar', root: 'dolar'});
this.setRemotes(SbifModel, {name: 'euro', path: '/euro', root: 'euro'});
return SbifModel;
}
setRemotes(model, remoteMethod){
let remoteOpts = {
accepts: {
arg: 'params',
type: 'string'
},
returns: {
arg: remoteMethod.root || remoteMethod.name,
type: 'string'
},
http: {
path: remoteMethod.path || '/' + remoteMethod.name,
verb: 'get'
}
};
//Set the model remote methodnpm
model.remoteMethod(remoteMethod.name, remoteOpts);
}
getData(type, params, callback){
request(`${api_url}/${type}?apikey=${token}&formato=json`).then((res) => {
let data = JSON.parse(res);
switch(type){
case 'uf':
data = data.UFs[0];
break;
case 'utm':
data = data.UTMs[0];
break;
case 'ipc':
data = data.IPCs[0];
break;
case 'dolar':
data = data.Dolares[0];
break;
case 'euro':
data = data.Euros[0];
break;
}
callback(null, data);
});
}
}
module.exports = (Model) => { new SbifApi(Model) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment