Skip to content

ESM/import version #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
module.exports = require('./lib/client')
// module.exports = require('./lib/client')
// const client = require('./lib/client')
// export { client }

import { auth } from './lib/client'
export default auth;
28 changes: 16 additions & 12 deletions lib/client.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
const debug = require('debug')('bootic'),
colour = require('colour'),
Request = require('./request'),
Strategies = require('./strategies'),
Entities = require('./entities');
// import { colour } from 'colour';
import { sendRequest, streamData } from './request';
import { Strategies } from './strategies';
import { root, linkedProxy, embeddedProxy } from './entities';

const ROOT_URL = 'https://api.bootic.net/v1';
const debug = function(str) { }

const ROOT_URL = 'https://api.bootic.net/v1';

function Client(strategy, opts) {
var Strategy = Strategies[strategy]
if (!Strategy)
throw new Error('Invalid strategy, valid ones are: ' + Object.keys(Strategies));

this.strategy = new Strategy(opts);
console.log('initializing client', strategy, opts)

this.rootUrl = opts.rootUrl || ROOT_URL;
}

Expand All @@ -33,7 +36,7 @@ Client.prototype.authorize = function() {
// if (!data._class || ~data._class.indexOf('errors'))
// throw new Error(data.message)

client.root = Entities.root(client, data);
client.root = root(client, data);
return client.root;
})
})
Expand All @@ -47,7 +50,7 @@ Client.prototype.request = function(link, params) {
debug(link);
console.log((link.method || 'GET').toUpperCase().blue, link.href.split('{?')[0].grey)

return Request.send(link.method, link.href, params, headers).then(function(resp) {
return sendRequest(link.method, link.href, params, headers).then(function(resp) {
var code = resp.status,
time = Date.now() - start;

Expand All @@ -73,15 +76,16 @@ Client.prototype.request = function(link, params) {

Client.prototype.stream = function(url, headers, onData, onClose) {
console.log('GET'.blue, url.split('{?')[0].grey)
return Request.stream(url, headers, onData, onClose);
return streamData(url, headers, onData, onClose);
}

module.exports = Client
// module.exports = Client
export default Client;

module.exports.auth = function(strategy, opts) {
export function auth(strategy, opts) {
if (typeof strategy == 'object') {
opts = strategy
strategy = opts.strategy || (opts.token && opts.clientId ? 'authorized' : opts.token ? 'bearer' : 'credentials')
strategy = opts.strategy || (opts.token && opts.clientId ? 'authorized' : opts.accessToken ? 'bearer' : 'credentials')
}

return new Client(strategy, opts).authorize()
Expand Down
45 changes: 28 additions & 17 deletions lib/entities.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
const debug = require('debug')('bootic');
const explain = require('./explain');
const h = require('./helpers');

import explain from './explain'
import { isObject, isArray, isNumber, isFunction, containsVerb } from './helpers'

const LINK_PREFIX = 'btc:';

const debug = function(str) { }

// promise vs callback wrapper
function invoke(fn, cb) {
if (cb) {
Expand Down Expand Up @@ -40,6 +42,9 @@ function buildPagedArray(itemName, client, result) {
}

Object.defineProperties(arr, {
'toArray': {
get: function() { return arr }
},
'totalItems': {
get: function() { return result.total_items }
},
Expand Down Expand Up @@ -204,7 +209,7 @@ Collection.prototype.resetFilters = function() {
*/

Collection.prototype.where = function(params) {
if (!params || !h.isObject(params))
if (!params || !isObject(params))
throw new Error('Object expected, not ' + typeof(params));

this._params = params;
Expand Down Expand Up @@ -233,8 +238,8 @@ Collection.prototype.all = function(cb) {
}

Collection.prototype.first = function(num, cb) {
cb = h.isFunction(num) ? num : cb;
num = h.isNumber(num) ? num : null;
cb = isFunction(num) ? num : cb;
num = isNumber(num) ? num : null;

return invoke(function(done) {
this._fetchItems(function(items) {
Expand All @@ -244,8 +249,8 @@ Collection.prototype.first = function(num, cb) {
}

Collection.prototype.last = function(num, cb) {
cb = h.isFunction(num) ? num : cb;
num = h.isNumber(num) ? num : null;
cb = isFunction(num) ? num : cb;
num = isNumber(num) ? num : null;

return invoke(function(done) {
this._fetchItems(function(items) {
Expand Down Expand Up @@ -307,8 +312,8 @@ LinkedEntity.prototype = Object.create(Entity.prototype)
LinkedEntity.prototype.constructor = LinkedEntity

LinkedEntity.prototype.get = function(params, cb) {
cb = h.isFunction(params) ? params : cb;
params = h.isObject(params) ? params : {};
cb = isFunction(params) ? params : cb;
params = isObject(params) ? params : {};

return invoke(function(done) {
return this._client.request(this._link, params).then(function(result) {
Expand Down Expand Up @@ -410,13 +415,13 @@ LinkedCollection.prototype.desc = function(count) {

LinkedCollection.prototype.first = function(num, cb) {
this.asc();
if (h.isNumber(num)) this.limit(num);
if (isNumber(num)) this.limit(num);
return Collection.prototype.first.call(this, num, cb);
}

LinkedCollection.prototype.last = function(num, cb) {
this.desc();
if (h.isNumber(num)) this.limit(num);
if (isNumber(num)) this.limit(num);
return Collection.prototype.last.call(this, num, cb);
}

Expand Down Expand Up @@ -522,7 +527,7 @@ VirtualCollection.prototype._fetch = function(cb) {
// TODO: less duplication, if possible.

function embeddedProxy(client, name, data) {
if (h.isArray(data)) {
if (isArray(data)) {
var target = new Collection(name, client, data)
} else {
var target = new Entity(name, client, data)
Expand All @@ -543,7 +548,7 @@ function detectProxy(client, data, defaultName) {
}

function linkedProxy(client, name, link, singular) {
if (link.type || h.containsVerb(name) || (link.method && link.method.toLowerCase() != 'get'))
if (link.type || containsVerb(name) || (link.method && link.method.toLowerCase() != 'get'))
return new LinkedAction(name, client, link)

if (name[name.length-1] != 's') // singular, not a collection
Expand Down Expand Up @@ -610,13 +615,19 @@ let proxyHandler = {
////////////////////////////////////////////////////////////////
// the root exports

exports.root = function(client, data) {
function root(client, data) {
if (data && (data._links || {})['btc:all_shops'] && (data._embedded || {})['shops'])
delete data._embedded['shops'] // so root.shops returns 'all_shops' link

var target = new Entity('root', client, data)
return new Proxy(target, proxyHandler)
}

exports.embeddedProxy = embeddedProxy;
exports.linkedProxy = linkedProxy;
export {
root,
embeddedProxy,
linkedProxy
}

// exports.embeddedProxy = embeddedProxy;
// exports.linkedProxy = linkedProxy;
10 changes: 7 additions & 3 deletions lib/explain.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
const colour = require('colour')
const containsVerb = require('./helpers').containsVerb
// const colour = require('colour')
import colour from 'colour';
import { containsVerb } from './helpers';

const LINK_PREFIX = 'btc:'

function explain(el) {
Expand Down Expand Up @@ -46,4 +48,6 @@ function explain(el) {
}
}

module.exports = explain
export default explain;

// module.exports = explain
20 changes: 20 additions & 0 deletions lib/fetch-polyfill.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// fetch-polyfill.js
import fetch, {
Blob,
blobFrom,
blobFromSync,
File,
fileFrom,
fileFromSync,
FormData,
Headers,
Request,
Response,
} from 'node-fetch'

if (!globalThis.fetch) {
globalThis.fetch = fetch
globalThis.Headers = Headers
globalThis.Request = Request
globalThis.Response = Response
}
20 changes: 12 additions & 8 deletions lib/helpers.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,27 @@
var helpers = {};

helpers.isObject = function(obj) {
function isObject(obj) {
return obj && obj.constructor.name == 'Object'
}

helpers.isArray = function(obj) {
function isArray(obj) {
return obj && obj.constructor.name == 'Array'
}

helpers.isNumber = function(num) {
function isNumber(num) {
return typeof num == 'number'
}

helpers.isFunction = function(fn) {
function isFunction(fn) {
return typeof fn == 'function'
}

helpers.containsVerb = function(word) {
function containsVerb(word) {
return !!word.replace('btc:', '').match(/^(get|update|create|remove|destroy)_/)
}

module.exports = helpers;
export {
isObject,
isArray,
isNumber,
isFunction,
containsVerb,
}
23 changes: 15 additions & 8 deletions lib/request.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
var debug = require('debug')('bootic');
var uriTemplate = require('uri-templates');
// var debug = require('debug')('bootic');
// var uriTemplate = require('uri-templates');

if (typeof fetch == 'undefined') {
var fetch = require('node-fetch-polyfill');
require('http').globalAgent.keepAlive = true;
}
const debug = function(str) { }
import uriTemplate from 'uri-templates';

// import { fetch } from 'node-fetch-polyfill';
// import fetch from 'node-fetch';
// import './fetch-polyfill'

function sendRequest(method, url, params, headers) {
var template, params = params || {}, options = {
Expand Down Expand Up @@ -90,5 +92,10 @@ function streamData(url, headers, cb, done) {
});
}

exports.send = sendRequest;
exports.stream = streamData;
// exports.send = sendRequest;
// exports.stream = streamData;

export {
sendRequest,
streamData
}
8 changes: 4 additions & 4 deletions lib/strategies/authorized.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
var ClientOAuth2 = require('client-oauth2')
// var ClientOAuth2 = require('client-oauth2')
// import ClientOAuth2 from 'client-oauth2';
import ClientOAuth2 from './oauth2';

function AuthorizedStrategy(opts) {
export default function AuthorizedStrategy(opts) {
if (!opts.clientId || !opts.clientSecret || (!opts.token && !opts.accessToken))
throw new Error('token, clientId and clientSecret required!')

Expand All @@ -23,5 +25,3 @@ function AuthorizedStrategy(opts) {

return { getToken: getToken, canRefresh: true }
}

module.exports = AuthorizedStrategy
3 changes: 1 addition & 2 deletions lib/strategies/bearer.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
function BearerStrategy(opts) {
export default function BearerStrategy(opts) {
if (!opts.accessToken && !opts.token)
throw new Error('accessToken required!')

Expand All @@ -13,4 +13,3 @@ function BearerStrategy(opts) {
return { getToken: getToken, canRefresh: false }
}

module.exports = BearerStrategy
7 changes: 4 additions & 3 deletions lib/strategies/credentials.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
var ClientOAuth2 = require('client-oauth2')
// var ClientOAuth2 = require('client-oauth2')
// import ClientOAuth2 from 'client-oauth2';
import ClientOAuth2 from './oauth2';

function CredentialsStrategy(opts) {
export default function CredentialsStrategy(opts) {
if (!opts.clientId || !opts.clientSecret)
throw new Error('clientId and clientSecret required!')

Expand All @@ -21,4 +23,3 @@ function CredentialsStrategy(opts) {
return { getToken: getToken, canRefresh: true }
}

module.exports = CredentialsStrategy
13 changes: 10 additions & 3 deletions lib/strategies/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
exports.authorized = require('./authorized')
exports.bearer = require('./bearer')
exports.credentials = require('./credentials')
import authorized from './authorized';
import bearer from './bearer';
import credentials from './credentials';

export const Strategies = {
authorized,
bearer,
credentials
}

Loading