Socket
Socket
Sign inDemoInstall

@ndustrial/contxt-sdk

Package Overview
Dependencies
Maintainers
9
Versions
123
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@ndustrial/contxt-sdk - npm Package Compare versions

Comparing version 0.0.11 to 0.0.12

.prettierignore

13

CHANGELOG.md

@@ -0,1 +1,14 @@

## [v0.0.12](http://github.com/ndustrialio/contxt-sdk-js/tree/v0.0.12) (2018-06-13)
**Changed**
* Added methods around the display and manipulation of Cost Centers. They are namespaced under facilities (i.e. `facilities.costCenters.methodName()`) and include:
* CostCenters#addFacility to add a facility to a cost center
* CostCenters#create for creating a new cost center
* CostCenters#getAll for getting a list of all cost centers
* CostCenters#getAllByOrganizationId for getting all cost centers for a specific organization
* CostCenters#remove to remove an existing cost center
* CostCenters#removeFacility to remove a facility from a cost center
* CostCenters#update to update an existing cost center
## [v0.0.11](http://github.com/ndustrialio/contxt-sdk-js/tree/v0.0.11) (2018-05-16)

@@ -2,0 +15,0 @@

@@ -19,2 +19,6 @@ ## Classes

</dd>
<dt><a href="./CostCenters.md">CostCenters</a></dt>
<dd><p>Module that provides access to cost centers, and helps manage
the relationship between those cost centers and facilities</p>
</dd>
<dt><a href="./Facilities.md">Facilities</a></dt>

@@ -45,2 +49,6 @@ <dd><p>Module that provides access to, and the manipulation

<dd></dd>
<dt><a href="./Typedefs.md#CostCenter">CostCenter</a> : <code>Object</code></dt>
<dd></dd>
<dt><a href="./Typedefs.md#CostCenterFacility">CostCenterFacility</a> : <code>Object</code></dt>
<dd></dd>
<dt><a href="./Typedefs.md#CustomAudience">CustomAudience</a> : <code>Object</code></dt>

@@ -47,0 +55,0 @@ <dd><p>A custom audience that will override the configuration of an individual module. Consists of

@@ -25,2 +25,29 @@ <a name="Audience"></a>

<a name="CostCenter"></a>
## CostCenter : <code>Object</code>
**Kind**: global typedef
| Param | Type | Description |
| --- | --- | --- |
| createdAt | <code>string</code> | ISO 8601 Extended Format date/time string |
| [description] | <code>string</code> | |
| id | <code>string</code> | UUID |
| name | <code>string</code> | |
| organizationId | <code>string</code> | UUID |
| updatedAt | <code>string</code> | ISO 8601 Extended Format date/time string |
<a name="CostCenterFacility"></a>
## CostCenterFacility : <code>Object</code>
**Kind**: global typedef
| Param | Type | Description |
| --- | --- | --- |
| costCenterId | <code>string</code> | UUID |
| createdAt | <code>string</code> | ISO 8601 Extended Format date/time string |
| facilityId | <code>number</code> | |
| id | <code>string</code> | UUID |
| updatedAt | <code>string</code> | ISO 8601 Extended Format date/time string |
<a name="CustomAudience"></a>

@@ -27,0 +54,0 @@

@@ -295,2 +295,43 @@ import axios from 'axios';

function formatCostCenterFacilityFromServer() {
var input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return {
costCenterId: input.cost_center_id,
createdAt: input.created_at,
facilityId: input.facility_id,
id: input.id,
updatedAt: input.updated_at
};
}
function formatCostCenterFromServer() {
var input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var costCenter = {
createdAt: input.created_at,
description: input.description,
id: input.id,
name: input.name,
organizationId: input.organization_id,
updatedAt: input.updated_at
};
if (input.facilities) {
costCenter.facilities = input.facilities.map(formatFacilityFromServer);
}
return costCenter;
}
function formatCostCenterToServer() {
var input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return {
description: input.description,
name: input.name,
organization_id: input.organizationId
};
}
function formatFacilityFromServer() {

@@ -558,2 +599,127 @@ var input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

var CostCenters = function () {
function CostCenters(sdk, request, baseUrl) {
classCallCheck(this, CostCenters);
this._baseUrl = baseUrl;
this._request = request;
this._sdk = sdk;
}
createClass(CostCenters, [{
key: 'addFacility',
value: function addFacility(costCenterId, facilityId) {
var errorMsg = void 0;
if (!costCenterId) {
errorMsg = 'A costCenterId is required to create a relationship between a cost center and a facility.';
} else if (!facilityId) {
errorMsg = 'A facilityId is required to create a relationship between a cost center and a facility.';
}
if (errorMsg) {
return Promise.reject(new Error(errorMsg));
}
return this._request.post(this._baseUrl + '/costcenters/' + costCenterId + '/facility/' + facilityId).then(function (costCenterFacility) {
return formatCostCenterFacilityFromServer(costCenterFacility);
});
}
}, {
key: 'create',
value: function create() {
var costCenter = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var requiredFields = ['name', 'organizationId'];
for (var i = 0; i < requiredFields.length; i++) {
var field = requiredFields[i];
if (!costCenter[field]) {
return Promise.reject(new Error('A ' + field + ' is required to create a new cost center.'));
}
}
var data = formatCostCenterToServer(costCenter);
return this._request.post(this._baseUrl + '/costcenters', data).then(function (costCenter) {
return formatCostCenterFromServer(costCenter);
});
}
}, {
key: 'delete',
value: function _delete(costCenterId) {
if (!costCenterId) {
return Promise.reject(new Error('A cost center id is required for deleting a cost center.'));
}
return this._request.delete(this._baseUrl + '/costcenters/' + costCenterId);
}
}, {
key: 'getAll',
value: function getAll() {
return this._request.get(this._baseUrl + '/costcenters').then(function (costCenters) {
return costCenters.map(formatCostCenterFromServer);
});
}
}, {
key: 'getAllByOrganizationId',
value: function getAllByOrganizationId(organizationId) {
if (!organizationId) {
return Promise.reject(new Error("An organization id is required for getting a list of an organization's cost centers."));
}
return this._request.get(this._baseUrl + '/organizations/' + organizationId + '/costcenters').then(function (costCenters) {
return costCenters.map(formatCostCenterFromServer);
});
}
}, {
key: 'removeFacility',
value: function removeFacility(costCenterId, facilityId) {
var errorMsg = void 0;
if (!costCenterId) {
errorMsg = 'A costCenterId is required to remove a relationship between a cost center and a facility.';
} else if (!facilityId) {
errorMsg = 'A facilityId is required to remove a relationship between a cost center and a facility.';
}
if (errorMsg) {
return Promise.reject(new Error(errorMsg));
}
return this._request.delete(this._baseUrl + '/costcenters/' + costCenterId + '/facility/' + facilityId);
}
}, {
key: 'update',
value: function update(costCenterId, _update) {
if (!costCenterId) {
return Promise.reject(new Error('A cost center id is required to update a cost center.'));
}
if (!_update) {
return Promise.reject(new Error('An update is required to update a cost center.'));
}
if (!lodash_isplainobject(_update)) {
return Promise.reject(new Error('The cost center update must be a well-formed object with the data you wish to update.'));
}
var formattedUpdate = formatCostCenterToServer(_update);
return this._request.put(this._baseUrl + '/costcenters/' + costCenterId, formattedUpdate).then(function (costCenter) {
return formatCostCenterFromServer(costCenter);
});
}
}]);
return CostCenters;
}();
var Facilities = function () {

@@ -571,2 +737,3 @@

this.groupings = new FacilityGroupings(sdk, request, baseUrl);
this.costCenters = new CostCenters(sdk, request, baseUrl);
}

@@ -573,0 +740,0 @@

@@ -299,2 +299,43 @@ 'use strict';

function formatCostCenterFacilityFromServer() {
var input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return {
costCenterId: input.cost_center_id,
createdAt: input.created_at,
facilityId: input.facility_id,
id: input.id,
updatedAt: input.updated_at
};
}
function formatCostCenterFromServer() {
var input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var costCenter = {
createdAt: input.created_at,
description: input.description,
id: input.id,
name: input.name,
organizationId: input.organization_id,
updatedAt: input.updated_at
};
if (input.facilities) {
costCenter.facilities = input.facilities.map(formatFacilityFromServer);
}
return costCenter;
}
function formatCostCenterToServer() {
var input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return {
description: input.description,
name: input.name,
organization_id: input.organizationId
};
}
function formatFacilityFromServer() {

@@ -562,2 +603,127 @@ var input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

var CostCenters = function () {
function CostCenters(sdk, request, baseUrl) {
classCallCheck(this, CostCenters);
this._baseUrl = baseUrl;
this._request = request;
this._sdk = sdk;
}
createClass(CostCenters, [{
key: 'addFacility',
value: function addFacility(costCenterId, facilityId) {
var errorMsg = void 0;
if (!costCenterId) {
errorMsg = 'A costCenterId is required to create a relationship between a cost center and a facility.';
} else if (!facilityId) {
errorMsg = 'A facilityId is required to create a relationship between a cost center and a facility.';
}
if (errorMsg) {
return Promise.reject(new Error(errorMsg));
}
return this._request.post(this._baseUrl + '/costcenters/' + costCenterId + '/facility/' + facilityId).then(function (costCenterFacility) {
return formatCostCenterFacilityFromServer(costCenterFacility);
});
}
}, {
key: 'create',
value: function create() {
var costCenter = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var requiredFields = ['name', 'organizationId'];
for (var i = 0; i < requiredFields.length; i++) {
var field = requiredFields[i];
if (!costCenter[field]) {
return Promise.reject(new Error('A ' + field + ' is required to create a new cost center.'));
}
}
var data = formatCostCenterToServer(costCenter);
return this._request.post(this._baseUrl + '/costcenters', data).then(function (costCenter) {
return formatCostCenterFromServer(costCenter);
});
}
}, {
key: 'delete',
value: function _delete(costCenterId) {
if (!costCenterId) {
return Promise.reject(new Error('A cost center id is required for deleting a cost center.'));
}
return this._request.delete(this._baseUrl + '/costcenters/' + costCenterId);
}
}, {
key: 'getAll',
value: function getAll() {
return this._request.get(this._baseUrl + '/costcenters').then(function (costCenters) {
return costCenters.map(formatCostCenterFromServer);
});
}
}, {
key: 'getAllByOrganizationId',
value: function getAllByOrganizationId(organizationId) {
if (!organizationId) {
return Promise.reject(new Error("An organization id is required for getting a list of an organization's cost centers."));
}
return this._request.get(this._baseUrl + '/organizations/' + organizationId + '/costcenters').then(function (costCenters) {
return costCenters.map(formatCostCenterFromServer);
});
}
}, {
key: 'removeFacility',
value: function removeFacility(costCenterId, facilityId) {
var errorMsg = void 0;
if (!costCenterId) {
errorMsg = 'A costCenterId is required to remove a relationship between a cost center and a facility.';
} else if (!facilityId) {
errorMsg = 'A facilityId is required to remove a relationship between a cost center and a facility.';
}
if (errorMsg) {
return Promise.reject(new Error(errorMsg));
}
return this._request.delete(this._baseUrl + '/costcenters/' + costCenterId + '/facility/' + facilityId);
}
}, {
key: 'update',
value: function update(costCenterId, _update) {
if (!costCenterId) {
return Promise.reject(new Error('A cost center id is required to update a cost center.'));
}
if (!_update) {
return Promise.reject(new Error('An update is required to update a cost center.'));
}
if (!lodash_isplainobject(_update)) {
return Promise.reject(new Error('The cost center update must be a well-formed object with the data you wish to update.'));
}
var formattedUpdate = formatCostCenterToServer(_update);
return this._request.put(this._baseUrl + '/costcenters/' + costCenterId, formattedUpdate).then(function (costCenter) {
return formatCostCenterFromServer(costCenter);
});
}
}]);
return CostCenters;
}();
var Facilities = function () {

@@ -575,2 +741,3 @@

this.groupings = new FacilityGroupings(sdk, request, baseUrl);
this.costCenters = new CostCenters(sdk, request, baseUrl);
}

@@ -577,0 +744,0 @@

7

package.json
{
"name": "@ndustrial/contxt-sdk",
"version": "0.0.11",
"version": "0.0.12",
"description": "",

@@ -13,2 +13,3 @@ "main": "lib/index.js",

"lint": "eslint --format 'node_modules/eslint-friendly-formatter' '+(src|support)/**/*.js'",
"precommit": "pretty-quick --staged",
"prepare": "npm run build",

@@ -41,2 +42,3 @@ "report": "nyc report",

"eslint-config-ndustrial": "^1.0.5",
"eslint-config-prettier": "^2.9.0",
"eslint-friendly-formatter": "^3.0.0",

@@ -46,2 +48,3 @@ "eslint-plugin-node": "^5.2.1",

"fast-glob": "^2.1.0",
"husky": "^0.14.3",
"jsdoc-to-markdown": "^4.0.1",

@@ -53,2 +56,4 @@ "lodash.omit": "^4.5.0",

"nyc": "^11.4.1",
"prettier": "^1.12.1",
"pretty-quick": "^1.4.1",
"rollup": "^0.54.1",

@@ -55,0 +60,0 @@ "rollup-plugin-babel": "^3.0.3",

38

README.md

@@ -1,2 +0,2 @@

# contxt-sdk [![wercker status](https://app.wercker.com/status/869ef086297da79ddd0cbf3564f7cba6/s/master "wercker status")](https://app.wercker.com/project/byKey/869ef086297da79ddd0cbf3564f7cba6)
# contxt-sdk [![wercker status](https://app.wercker.com/status/869ef086297da79ddd0cbf3564f7cba6/s/master 'wercker status')](https://app.wercker.com/project/byKey/869ef086297da79ddd0cbf3564f7cba6)

@@ -97,25 +97,25 @@ ## Installation

- `npm test` - Lints, sets up tracking for Istanbul coverage reports, and runs the test suite
- `npm run test:js` - Runs the test suite
- `npm run test:js:dev` - Runs the test suite in watch mode, where the tests are re-run whenever a file changes
- `npm run test:js:inspect` - Runs the test suite in inspect/inspect-brk mode. Insert a `debugger` somewhere in your code and connect to the debugger with this command. (Node 8: visit `chrome://inspect` to connect. Node 6: Copy and paste the blob provided in the terminal into Chrome to connect. Older versions also have ways to connect.)
- `npm run lint` - Lints the source code
- `npm run coverage` - Sets up tracking for Istanbul coverage reports and runs the test suite
- `npm run report` - Parses the Istanbul coverage reports and writes them to file (in `./coverage`) and displays them in terminal
* `npm test` - Lints, sets up tracking for Istanbul coverage reports, and runs the test suite
* `npm run test:js` - Runs the test suite
* `npm run test:js:dev` - Runs the test suite in watch mode, where the tests are re-run whenever a file changes
* `npm run test:js:inspect` - Runs the test suite in inspect/inspect-brk mode. Insert a `debugger` somewhere in your code and connect to the debugger with this command. (Node 8: visit `chrome://inspect` to connect. Node 6: Copy and paste the blob provided in the terminal into Chrome to connect. Older versions also have ways to connect.)
* `npm run lint` - Lints the source code
* `npm run coverage` - Sets up tracking for Istanbul coverage reports and runs the test suite
* `npm run report` - Parses the Istanbul coverage reports and writes them to file (in `./coverage`) and displays them in terminal
Some tools used for testing and ensuring code quality include:
- [Chai.js](http://chaijs.com/) (specifically the `expect` syntax)
- [chai-as-promised](https://github.com/domenic/chai-as-promised)
- [ESLint](https://eslint.org/)
- [eslint-config-ndustrial](https://github.com/ndustrialio/eslint-config-ndustrial)
- [faker.js](https://github.com/marak/Faker.js/)
- [Mocha](https://mochajs.org/)
- [Sinon.JS](http://sinonjs.org/)
- [sinon-chai](http://chaijs.com/plugins/sinon-chai/)
* [Chai.js](http://chaijs.com/) (specifically the `expect` syntax)
* [chai-as-promised](https://github.com/domenic/chai-as-promised)
* [ESLint](https://eslint.org/)
* [eslint-config-ndustrial](https://github.com/ndustrialio/eslint-config-ndustrial)
* [faker.js](https://github.com/marak/Faker.js/)
* [Mocha](https://mochajs.org/)
* [Sinon.JS](http://sinonjs.org/)
* [sinon-chai](http://chaijs.com/plugins/sinon-chai/)
Additionally, some globals have been added to the testing environment to streamline the process slightly:
- `expect` - Corresponds with `require('chai').expect`. [Info](http://chaijs.com/api/bdd/)
- `faker` - Corresponds with `require('faker')`. [Info](https://github.com/marak/Faker.js/)
- `sandbox` - Corresponds with `require('sinon').sandbox`. Should be used anytime when wanting to create a `sinon.spy` or `sinon.stub` as it can be easily used to reset/restore multiple spys and stubs. [Info](http://sinonjs.org/releases/v4.1.6/sandbox/)
* `expect` - Corresponds with `require('chai').expect`. [Info](http://chaijs.com/api/bdd/)
* `faker` - Corresponds with `require('faker')`. [Info](https://github.com/marak/Faker.js/)
* `sandbox` - Corresponds with `require('sinon').sandbox`. Should be used anytime when wanting to create a `sinon.spy` or `sinon.stub` as it can be easily used to reset/restore multiple spys and stubs. [Info](http://sinonjs.org/releases/v4.1.6/sandbox/)

@@ -27,3 +27,3 @@ import babel from 'rollup-plugin-babel';

commonjs({
include: 'node_modules/**',
include: 'node_modules/**'
}),

@@ -30,0 +30,0 @@ babel({

@@ -59,5 +59,5 @@ import defaultAudiences from './audiences';

* method used for navigating through Auth0 callbacks in Web applications
* @property {number} [auth.tokenExpiresAtBufferMs = 300000] The time (in milliseconds) before a
* token truly expires that we consider it expired (i.e. the token's expiresAt - this = calculated
* expiresAt). Defaults to 5 minutes.
* @property {number} [auth.tokenExpiresAtBufferMs = 300000] The time (in milliseconds) before a
* token truly expires that we consider it expired (i.e. the token's expiresAt - this = calculated
* expiresAt). Defaults to 5 minutes.
*/

@@ -111,3 +111,5 @@

} else {
throw new Error('Custom module configurations must either contain a `host` and `clientId` or specify a specific target environment via the `env` property');
throw new Error(
'Custom module configurations must either contain a `host` and `clientId` or specify a specific target environment via the `env` property'
);
}

@@ -163,3 +165,5 @@ }

if (!(externalModules[key].clientId && externalModules[key].host)) {
throw new Error('External modules must contain `clientId` and `host` properties');
throw new Error(
'External modules must contain `clientId` and `host` properties'
);
}

@@ -196,3 +200,6 @@

if (customModuleConfig) {
memo[key] = this._getAudienceFromCustomConfig(customModuleConfig, moduleAudiences);
memo[key] = this._getAudienceFromCustomConfig(
customModuleConfig,
moduleAudiences
);
} else {

@@ -199,0 +206,0 @@ memo[key] = moduleAudiences[env];

@@ -42,5 +42,10 @@ import times from 'lodash.times';

getAudiences = this.sandbox.stub(Config.prototype, '_getAudiences').returns(expectedAudiences);
getAudiences = this.sandbox
.stub(Config.prototype, '_getAudiences')
.returns(expectedAudiences);
config = new Config({ ...baseConfigs, auth: baseAuthConfigs }, expectedExternalModules);
config = new Config(
{ ...baseConfigs, auth: baseAuthConfigs },
expectedExternalModules
);
});

@@ -74,22 +79,28 @@

describe('_getAudienceFromCustomConfig', function() {
context('when providing a custom host and clientId for a module', function() {
let audiences;
let expectedAudience;
context(
'when providing a custom host and clientId for a module',
function() {
let audiences;
let expectedAudience;
beforeEach(function() {
const env = faker.hacker.adjective();
expectedAudience = fixture.build('audience');
const config = { ...expectedAudience, env };
const initialAudiences = {
[env]: fixture.build('audience'),
[faker.hacker.verb()]: fixture.build('audience')
};
beforeEach(function() {
const env = faker.hacker.adjective();
expectedAudience = fixture.build('audience');
const config = { ...expectedAudience, env };
const initialAudiences = {
[env]: fixture.build('audience'),
[faker.hacker.verb()]: fixture.build('audience')
};
audiences = Config.prototype._getAudienceFromCustomConfig(config, initialAudiences);
});
audiences = Config.prototype._getAudienceFromCustomConfig(
config,
initialAudiences
);
});
it('provides audience information that matches the custom information provided', function() {
expect(audiences).to.deep.equal(expectedAudience);
});
});
it('provides audience information that matches the custom information provided', function() {
expect(audiences).to.deep.equal(expectedAudience);
});
}
);

@@ -109,3 +120,6 @@ context('when providing an environment for a module', function() {

audiences = Config.prototype._getAudienceFromCustomConfig(config, initialAudiences);
audiences = Config.prototype._getAudienceFromCustomConfig(
config,
initialAudiences
);
});

@@ -118,51 +132,69 @@

context('when there is missing or malformed custom configuration information', function() {
let initialAudiences;
context(
'when there is missing or malformed custom configuration information',
function() {
let initialAudiences;
beforeEach(function() {
const env = faker.hacker.adjective();
initialAudiences = {
facilities: {
[env]: fixture.build('audience')
}
};
});
it('throws an error when missing the clientId', function() {
const fn = () => {
const config = {
beforeEach(function() {
const env = faker.hacker.adjective();
initialAudiences = {
facilities: {
host: faker.internet.url()
[env]: fixture.build('audience')
}
};
Config.prototype._getAudienceFromCustomConfig(config, initialAudiences);
};
});
expect(fn).to.throw('Custom module configurations must either contain a `host` and `clientId` or specify a specific target environment via the `env` property');
});
it('throws an error when missing the clientId', function() {
const fn = () => {
const config = {
facilities: {
host: faker.internet.url()
}
};
Config.prototype._getAudienceFromCustomConfig(
config,
initialAudiences
);
};
it('throws an error when missing the host', function() {
const fn = () => {
const config = {
facilities: {
clientId: faker.internet.password()
}
expect(fn).to.throw(
'Custom module configurations must either contain a `host` and `clientId` or specify a specific target environment via the `env` property'
);
});
it('throws an error when missing the host', function() {
const fn = () => {
const config = {
facilities: {
clientId: faker.internet.password()
}
};
Config.prototype._getAudienceFromCustomConfig(
config,
initialAudiences
);
};
Config.prototype._getAudienceFromCustomConfig(config, initialAudiences);
};
expect(fn).to.throw('Custom module configurations must either contain a `host` and `clientId` or specify a specific target environment via the `env` property');
});
expect(fn).to.throw(
'Custom module configurations must either contain a `host` and `clientId` or specify a specific target environment via the `env` property'
);
});
it('throws an error when the configuration is malformed', function() {
const fn = () => {
const config = {
facilities: [faker.internet.password(), faker.internet.url()]
it('throws an error when the configuration is malformed', function() {
const fn = () => {
const config = {
facilities: [faker.internet.password(), faker.internet.url()]
};
Config.prototype._getAudienceFromCustomConfig(
config,
initialAudiences
);
};
Config.prototype._getAudienceFromCustomConfig(config, initialAudiences);
};
expect(fn).to.throw('Custom module configurations must either contain a `host` and `clientId` or specify a specific target environment via the `env` property');
});
});
expect(fn).to.throw(
'Custom module configurations must either contain a `host` and `clientId` or specify a specific target environment via the `env` property'
);
});
}
);
});

@@ -185,5 +217,7 @@

getExternalAudiences = this.sandbox.stub(Config.prototype, '_getExternalAudiences')
getExternalAudiences = this.sandbox
.stub(Config.prototype, '_getExternalAudiences')
.returns(expectedExternalAudiences);
getInternalAudiences = this.sandbox.stub(Config.prototype, '_getInternalAudiences')
getInternalAudiences = this.sandbox
.stub(Config.prototype, '_getInternalAudiences')
.returns(expectedInternalAudiences);

@@ -261,90 +295,105 @@ });

describe('_getExternalAudiences', function() {
context('when external modules are provided with a clientId and host', function() {
let audiences;
let expectedAudiences;
context(
'when external modules are provided with a clientId and host',
function() {
let audiences;
let expectedAudiences;
beforeEach(function() {
const externalModules = {};
expectedAudiences = {};
beforeEach(function() {
const externalModules = {};
expectedAudiences = {};
times(faker.random.number({ min: 1, max: 10 }))
.map(() => faker.hacker.adjective())
.forEach((moduleName) => {
const audience = fixture.build('audience');
expectedAudiences[moduleName] = audience;
externalModules[moduleName] = {
...audience,
module: function() {}
};
times(faker.random.number({ min: 1, max: 10 }))
.map(() => faker.hacker.adjective())
.forEach((moduleName) => {
const audience = fixture.build('audience');
expectedAudiences[moduleName] = audience;
externalModules[moduleName] = {
...audience,
module: function() {}
};
});
audiences = Config.prototype._getExternalAudiences({
externalModules
});
});
audiences = Config.prototype._getExternalAudiences({ externalModules });
});
it('provides an object with the hosts and clientIds of the external modules', function() {
expect(audiences).to.deep.equal(expectedAudiences);
});
}
);
it('provides an object with the hosts and clientIds of the external modules', function() {
expect(audiences).to.deep.equal(expectedAudiences);
});
});
context('when external modules are provided by are missing a clientId or host', function() {
it('throws an error when the clientId is not provided', function() {
const fn = () => {
Config.prototype._getExternalAudiences({
externalModules: {
[faker.hacker.adjective()]: {
host: faker.internet.url()
context(
'when external modules are provided by are missing a clientId or host',
function() {
it('throws an error when the clientId is not provided', function() {
const fn = () => {
Config.prototype._getExternalAudiences({
externalModules: {
[faker.hacker.adjective()]: {
host: faker.internet.url()
}
}
}
});
};
});
};
expect(fn).to.throw('External modules must contain `clientId` and `host` properties');
});
expect(fn).to.throw(
'External modules must contain `clientId` and `host` properties'
);
});
it('throws an error when the host is not provided', function() {
const fn = () => {
Config.prototype._getExternalAudiences({
externalModules: {
[faker.hacker.adjective()]: {
clientId: faker.internet.url()
it('throws an error when the host is not provided', function() {
const fn = () => {
Config.prototype._getExternalAudiences({
externalModules: {
[faker.hacker.adjective()]: {
clientId: faker.internet.url()
}
}
}
});
};
});
};
expect(fn).to.throw('External modules must contain `clientId` and `host` properties');
});
});
expect(fn).to.throw(
'External modules must contain `clientId` and `host` properties'
);
});
}
);
});
describe('_getInternalAudiences', function() {
context('when using the same audience environment across all modules', function() {
let audiences;
let expectedAudiences;
context(
'when using the same audience environment across all modules',
function() {
let audiences;
let expectedAudiences;
beforeEach(function() {
const env = faker.hacker.adjective();
expectedAudiences = fixture.build('defaultAudiences');
const initialAudiences = {
contxtAuth: {
[env]: expectedAudiences.contxtAuth,
[faker.hacker.verb()]: fixture.build('audience')
},
facilities: {
[env]: expectedAudiences.facilities,
[faker.hacker.verb()]: fixture.build('audience')
}
};
beforeEach(function() {
const env = faker.hacker.adjective();
expectedAudiences = fixture.build('defaultAudiences');
const initialAudiences = {
contxtAuth: {
[env]: expectedAudiences.contxtAuth,
[faker.hacker.verb()]: fixture.build('audience')
},
facilities: {
[env]: expectedAudiences.facilities,
[faker.hacker.verb()]: fixture.build('audience')
}
};
audiences = Config.prototype._getInternalAudiences({
env,
audiences: initialAudiences,
customModuleConfigs: {}
audiences = Config.prototype._getInternalAudiences({
env,
audiences: initialAudiences,
customModuleConfigs: {}
});
});
});
it('provides audience information for the specified environment', function() {
expect(audiences).to.deep.equal(expectedAudiences);
});
});
it('provides audience information for the specified environment', function() {
expect(audiences).to.deep.equal(expectedAudiences);
});
}
);

@@ -376,3 +425,4 @@ context('when a module uses a custom configuration', function() {

getAudienceFromCustomConfig = this.sandbox.stub(Config.prototype, '_getAudienceFromCustomConfig')
getAudienceFromCustomConfig = this.sandbox
.stub(Config.prototype, '_getAudienceFromCustomConfig')
.returns(expectedAudiences.facilities);

@@ -379,0 +429,0 @@

@@ -88,3 +88,3 @@ import isPlainObject from 'lodash.isplainobject';

)
.then(groupingFacility =>
.then((groupingFacility) =>
formatGroupingFacilityFromServer(groupingFacility)

@@ -140,3 +140,3 @@ );

.post(`${this._baseUrl}/groupings`, data)
.then(grouping => formatGroupingFromServer(grouping));
.then((grouping) => formatGroupingFromServer(grouping));
}

@@ -192,3 +192,3 @@

.get(`${this._baseUrl}/groupings`)
.then(groupings => groupings.map(formatGroupingFromServer));
.then((groupings) => groupings.map(formatGroupingFromServer));
}

@@ -225,3 +225,3 @@

.get(`${this._baseUrl}/organizations/${organizationId}/groupings`)
.then(groupings => groupings.map(formatGroupingFromServer));
.then((groupings) => groupings.map(formatGroupingFromServer));
}

@@ -320,3 +320,3 @@

.put(`${this._baseUrl}/groupings/${facilityGroupingId}`, formattedUpdate)
.then(grouping => formatGroupingFromServer(grouping));
.then((grouping) => formatGroupingFromServer(grouping));
}

@@ -323,0 +323,0 @@ }

@@ -316,3 +316,3 @@ import omit from 'lodash.omit';

);
groupingsFromServer.forEach(grouping => {
groupingsFromServer.forEach((grouping) => {
expect(formatGroupingFromServer).to.be.calledWith(grouping);

@@ -380,3 +380,3 @@ });

);
groupingsFromServer.forEach(grouping => {
groupingsFromServer.forEach((grouping) => {
expect(formatGroupingFromServer).to.be.calledWith(grouping);

@@ -383,0 +383,0 @@ });

import isPlainObject from 'lodash.isplainobject';
import FacilityGroupings from './groupings';
import CostCenters from './costCenters';
import {

@@ -55,2 +56,3 @@ formatFacilityFromServer,

this.groupings = new FacilityGroupings(sdk, request, baseUrl);
this.costCenters = new CostCenters(sdk, request, baseUrl);
}

@@ -107,3 +109,3 @@

.post(`${this._baseUrl}/facilities`, data)
.then(facility => formatFacilityFromServer(facility));
.then((facility) => formatFacilityFromServer(facility));
}

@@ -216,3 +218,3 @@

.get(`${this._baseUrl}/facilities/${facilityId}`)
.then(facility => formatFacilityFromServer(facility));
.then((facility) => formatFacilityFromServer(facility));
}

@@ -238,4 +240,4 @@

.get(`${this._baseUrl}/facilities`)
.then(facilities =>
facilities.map(facility => formatFacilityFromServer(facility))
.then((facilities) =>
facilities.map((facility) => formatFacilityFromServer(facility))
);

@@ -278,4 +280,4 @@ }

})
.then(facilities =>
facilities.map(facility => formatFacilityFromServer(facility))
.then((facilities) =>
facilities.map((facility) => formatFacilityFromServer(facility))
);

@@ -282,0 +284,0 @@ }

@@ -5,3 +5,3 @@ import omit from 'lodash.omit';

describe('Facilities', function () {
describe('Facilities', function() {
let baseRequest;

@@ -11,3 +11,3 @@ let baseSdk;

beforeEach(function () {
beforeEach(function() {
this.sandbox = sandbox.create();

@@ -31,22 +31,24 @@

afterEach(function () {
afterEach(function() {
this.sandbox.restore();
});
describe('constructor', function () {
describe('constructor', function() {
let facilities;
beforeEach(function () {
beforeEach(function() {
facilities = new Facilities(baseSdk, baseRequest);
});
it('sets a base url for the class instance', function () {
expect(facilities._baseUrl).to.equal(`${baseSdk.config.audiences.facilities.host}/v1`);
it('sets a base url for the class instance', function() {
expect(facilities._baseUrl).to.equal(
`${baseSdk.config.audiences.facilities.host}/v1`
);
});
it('appends the supplied request module to the class instance', function () {
it('appends the supplied request module to the class instance', function() {
expect(facilities._request).to.equal(baseRequest);
});
it('appends the supplied sdk to the class instance', function () {
it('appends the supplied sdk to the class instance', function() {
expect(facilities._sdk).to.equal(baseSdk);

@@ -56,4 +58,4 @@ });

describe('create', function () {
context('when all required information is supplied', function () {
describe('create', function() {
context('when all required information is supplied', function() {
let expectedFacility;

@@ -68,3 +70,3 @@ let formatFacilityFromServer;

beforeEach(function () {
beforeEach(function() {
expectedFacility = fixture.build('facility', null, {

@@ -81,5 +83,7 @@ fromServer: true

formatFacilityFromServer = this.sandbox.stub(facilitiesUtils, 'formatFacilityFromServer')
formatFacilityFromServer = this.sandbox
.stub(facilitiesUtils, 'formatFacilityFromServer')
.returns(expectedFacility);
formatFacilityToServer = this.sandbox.stub(facilitiesUtils, 'formatFacilityToServer')
formatFacilityToServer = this.sandbox
.stub(facilitiesUtils, 'formatFacilityToServer')
.returns(formattedFacility);

@@ -97,11 +101,14 @@ request = {

it('formats the submitted facility object to send to the server', function () {
it('formats the submitted facility object to send to the server', function() {
expect(formatFacilityToServer).to.be.calledWith(initialFacility);
});
it('creates a new facility', function () {
expect(request.post).to.be.deep.calledWith(`${expectedHost}/facilities`, formattedFacility);
it('creates a new facility', function() {
expect(request.post).to.be.deep.calledWith(
`${expectedHost}/facilities`,
formattedFacility
);
});
it('formats the returned facility object', function () {
it('formats the returned facility object', function() {
return promise.then(() => {

@@ -112,11 +119,12 @@ expect(formatFacilityFromServer).to.be.calledWith(rawFacility);

it('returns a fulfilled promise with the new facility information', function () {
return expect(promise).to.be.fulfilled
.and.to.eventually.equal(expectedFacility);
it('returns a fulfilled promise with the new facility information', function() {
return expect(promise).to.be.fulfilled.and.to.eventually.equal(
expectedFacility
);
});
});
context('when there is missing required information', function () {
['organizationId', 'name', 'timezone'].forEach(function (field) {
it(`it throws an error when ${field} is missing`, function () {
context('when there is missing required information', function() {
['organizationId', 'name', 'timezone'].forEach(function(field) {
it(`it throws an error when ${field} is missing`, function() {
const facility = fixture.build('facility');

@@ -130,4 +138,5 @@ const initialFacility = {

return expect(promise).to.be
.rejectedWith(`A ${field} is required to create a new facility.`);
return expect(promise).to.be.rejectedWith(
`A ${field} is required to create a new facility.`
);
});

@@ -138,4 +147,4 @@ });

describe('createOrUpdateInfo', function () {
context('when all required information is available', function () {
describe('createOrUpdateInfo', function() {
context('when all required information is available', function() {
let facilityId;

@@ -145,3 +154,3 @@ let facilityInfoUpdate;

beforeEach(function () {
beforeEach(function() {
facilityId = fixture.build('facility').id;

@@ -156,6 +165,7 @@ facilityInfoUpdate = fixture.build('facilityInfo');

it('updates the facility', function () {
it('updates the facility', function() {
expect(baseRequest.post).to.be.calledWith(
`${expectedHost}/facilities/${facilityId}/info`,
facilityInfoUpdate, {
facilityInfoUpdate,
{
params: {

@@ -168,3 +178,3 @@ should_update: true

it('returns a fulfilled promise', function () {
it('returns a fulfilled promise', function() {
return expect(promise).to.be.fulfilled;

@@ -174,41 +184,52 @@ });

context('when there is missing or malformed required information', function () {
let facilities;
context(
'when there is missing or malformed required information',
function() {
let facilities;
beforeEach(function () {
facilities = new Facilities(baseSdk, baseRequest);
});
beforeEach(function() {
facilities = new Facilities(baseSdk, baseRequest);
});
it('throws an error when there is no provided facility ID', function () {
const facilityInfoUpdate = fixture.build('facilityInfo');
const promise = facilities.createOrUpdateInfo(null, facilityInfoUpdate);
it('throws an error when there is no provided facility ID', function() {
const facilityInfoUpdate = fixture.build('facilityInfo');
const promise = facilities.createOrUpdateInfo(
null,
facilityInfoUpdate
);
return expect(promise).to.be
.rejectedWith("A facility ID is required to update a facility's info.");
});
return expect(promise).to.be.rejectedWith(
"A facility ID is required to update a facility's info."
);
});
it('throws an error when there is no update provided', function () {
const facility = fixture.build('facility');
const promise = facilities.createOrUpdateInfo(facility.id);
it('throws an error when there is no update provided', function() {
const facility = fixture.build('facility');
const promise = facilities.createOrUpdateInfo(facility.id);
return expect(promise).to.be.rejectedWith("An update is required to update a facility's info.");
});
return expect(promise).to.be.rejectedWith(
"An update is required to update a facility's info."
);
});
it('throws an error when the update is not an object', function () {
const facility = fixture.build('facility');
const promise = facilities.createOrUpdateInfo(facility.id, [facility.info]);
it('throws an error when the update is not an object', function() {
const facility = fixture.build('facility');
const promise = facilities.createOrUpdateInfo(facility.id, [
facility.info
]);
return expect(promise).to.be.rejectedWith(
'The facility info update must be a well-formed object with the data you wish to update.'
);
});
});
return expect(promise).to.be.rejectedWith(
'The facility info update must be a well-formed object with the data you wish to update.'
);
});
}
);
});
describe('delete', function () {
context('the facility ID is provided', function () {
describe('delete', function() {
context('the facility ID is provided', function() {
let facility;
let promise;
beforeEach(function () {
beforeEach(function() {
facility = fixture.build('facility');

@@ -222,8 +243,9 @@

it('requests to delete the facility', function () {
expect(baseRequest.delete).to.be
.calledWith(`${expectedHost}/facilities/${facility.id}`);
it('requests to delete the facility', function() {
expect(baseRequest.delete).to.be.calledWith(
`${expectedHost}/facilities/${facility.id}`
);
});
it('returns a resolved promise', function () {
it('returns a resolved promise', function() {
return expect(promise).to.be.fulfilled;

@@ -233,9 +255,10 @@ });

context('the facility ID is not provided', function () {
it('throws an error', function () {
context('the facility ID is not provided', function() {
it('throws an error', function() {
const facilities = new Facilities(baseSdk, baseRequest);
const promise = facilities.delete();
return expect(promise).to.be
.rejectedWith('A facility ID is required for deleting a facility');
return expect(promise).to.be.rejectedWith(
'A facility ID is required for deleting a facility'
);
});

@@ -245,4 +268,4 @@ });

describe('get', function () {
context('the facility ID is provided', function () {
describe('get', function() {
context('the facility ID is provided', function() {
let expectedFacilityId;

@@ -255,3 +278,3 @@ let formatFacilityFromServer;

beforeEach(function () {
beforeEach(function() {
expectedFacilityId = faker.random.number();

@@ -265,3 +288,4 @@ rawFacility = fixture.build('facility', null, {

formatFacilityFromServer = this.sandbox.stub(facilitiesUtils, 'formatFacilityFromServer')
formatFacilityFromServer = this.sandbox
.stub(facilitiesUtils, 'formatFacilityFromServer')
.returns(formattedFacility);

@@ -279,7 +303,9 @@ request = {

it('gets a list of facilities from the server', function () {
expect(request.get).to.be.calledWith(`${expectedHost}/facilities/${expectedFacilityId}`);
it('gets a list of facilities from the server', function() {
expect(request.get).to.be.calledWith(
`${expectedHost}/facilities/${expectedFacilityId}`
);
});
it('formats the facility object', function () {
it('formats the facility object', function() {
return promise.then(() => {

@@ -290,15 +316,17 @@ expect(formatFacilityFromServer).to.be.calledWith(rawFacility);

it('returns the requested facility', function () {
return expect(promise).to.be.fulfilled
.and.to.eventually.equal(formattedFacility);
it('returns the requested facility', function() {
return expect(promise).to.be.fulfilled.and.to.eventually.equal(
formattedFacility
);
});
});
context('the facility ID is not provided', function () {
it('throws an error', function () {
context('the facility ID is not provided', function() {
it('throws an error', function() {
const facilities = new Facilities(baseSdk, baseRequest);
const promise = facilities.get();
return expect(promise).to.be
.rejectedWith('A facility ID is required for getting information about a facility');
return expect(promise).to.be.rejectedWith(
'A facility ID is required for getting information about a facility'
);
});

@@ -308,3 +336,3 @@ });

describe('getAll', function () {
describe('getAll', function() {
let formatFacilityFromServer;

@@ -316,3 +344,3 @@ let formattedFacilities;

beforeEach(function () {
beforeEach(function() {
const numberOfFacilities = faker.random.number({

@@ -327,3 +355,4 @@ min: 1,

formatFacilityFromServer = this.sandbox.stub(facilitiesUtils, 'formatFacilityFromServer')
formatFacilityFromServer = this.sandbox
.stub(facilitiesUtils, 'formatFacilityFromServer')
.callsFake((facility) => {

@@ -344,9 +373,11 @@ const index = rawFacilities.indexOf(facility);

it('gets a list of facilities from the server', function () {
it('gets a list of facilities from the server', function() {
expect(request.get).to.be.calledWith(`${expectedHost}/facilities`);
});
it('formats the facility object', function () {
it('formats the facility object', function() {
return promise.then(() => {
expect(formatFacilityFromServer).to.have.callCount(rawFacilities.length);
expect(formatFacilityFromServer).to.have.callCount(
rawFacilities.length
);

@@ -359,10 +390,11 @@ rawFacilities.forEach((facility) => {

it('returns a list of facilities', function () {
return expect(promise).to.be.fulfilled
.and.to.eventually.deep.equal(formattedFacilities);
it('returns a list of facilities', function() {
return expect(promise).to.be.fulfilled.and.to.eventually.deep.equal(
formattedFacilities
);
});
});
describe('getAllByOrganizationId', function () {
context('the organization ID is provided', function () {
describe('getAllByOrganizationId', function() {
context('the organization ID is provided', function() {
let expectedOrganizationId;

@@ -378,3 +410,3 @@ let formatFacilityFromServer;

beforeEach(function () {
beforeEach(function() {
expectedOrganizationId = faker.random.number();

@@ -386,11 +418,18 @@ const numberOfFacilities = faker.random.number({

formattedFacilities = fixture.buildList('facility', numberOfFacilities);
rawFacilities = fixture.buildList('facility', numberOfFacilities, null, {
fromServer: true
});
rawFacilities = fixture.buildList(
'facility',
numberOfFacilities,
null,
{
fromServer: true
}
);
initialOptions = faker.helpers.createTransaction();
rawFacilityOptions = faker.helpers.createTransaction();
formatFacilityOptionsToServer = this.sandbox.stub(facilitiesUtils, 'formatFacilityOptionsToServer')
formatFacilityOptionsToServer = this.sandbox
.stub(facilitiesUtils, 'formatFacilityOptionsToServer')
.returns(rawFacilityOptions);
formatFacilityFromServer = this.sandbox.stub(facilitiesUtils, 'formatFacilityFromServer')
formatFacilityFromServer = this.sandbox
.stub(facilitiesUtils, 'formatFacilityFromServer')
.callsFake((facility) => {

@@ -408,12 +447,16 @@ const index = rawFacilities.indexOf(facility);

promise = facilities.getAllByOrganizationId(expectedOrganizationId, initialOptions);
promise = facilities.getAllByOrganizationId(
expectedOrganizationId,
initialOptions
);
});
it('gets options that are in a format suitable for the API', function () {
it('gets options that are in a format suitable for the API', function() {
expect(formatFacilityOptionsToServer).to.be.calledWith(initialOptions);
});
it('gets a list of facilities for an organization from the server', function () {
it('gets a list of facilities for an organization from the server', function() {
expect(request.get).to.be.calledWith(
`${expectedHost}/organizations/${expectedOrganizationId}/facilities`, {
`${expectedHost}/organizations/${expectedOrganizationId}/facilities`,
{
params: rawFacilityOptions

@@ -424,5 +467,7 @@ }

it('formats the facility object', function () {
it('formats the facility object', function() {
return promise.then(() => {
expect(formatFacilityFromServer).to.have.callCount(rawFacilities.length);
expect(formatFacilityFromServer).to.have.callCount(
rawFacilities.length
);

@@ -435,10 +480,11 @@ rawFacilities.forEach((facility) => {

it('returns a list of facilities', function () {
return expect(promise).to.be.fulfilled
.and.to.eventually.deep.equal(formattedFacilities);
it('returns a list of facilities', function() {
return expect(promise).to.be.fulfilled.and.to.eventually.deep.equal(
formattedFacilities
);
});
});
context('the organization id is not provided', function () {
it('throws an error', function () {
context('the organization id is not provided', function() {
it('throws an error', function() {
const facilities = new Facilities(baseSdk, baseRequest);

@@ -454,4 +500,4 @@ const promise = facilities.getAllByOrganizationId();

describe('update', function () {
context('when all required information is available', function () {
describe('update', function() {
context('when all required information is available', function() {
let facilityUpdate;

@@ -462,3 +508,3 @@ let formatFacilityToServer;

beforeEach(function () {
beforeEach(function() {
facilityUpdate = fixture.build('facility');

@@ -469,3 +515,4 @@ formattedFacility = fixture.build('facility', null, {

formatFacilityToServer = this.sandbox.stub(facilitiesUtils, 'formatFacilityToServer')
formatFacilityToServer = this.sandbox
.stub(facilitiesUtils, 'formatFacilityToServer')
.returns(formattedFacility);

@@ -479,7 +526,7 @@

it('formats the data into the right format', function () {
it('formats the data into the right format', function() {
expect(formatFacilityToServer).to.be.calledWith(facilityUpdate);
});
it('updates the facility', function () {
it('updates the facility', function() {
expect(baseRequest.put).to.be.calledWith(

@@ -491,3 +538,3 @@ `${expectedHost}/facilities/${facilityUpdate.id}`,

it('returns a fulfilled promise', function () {
it('returns a fulfilled promise', function() {
return expect(promise).to.be.fulfilled;

@@ -497,34 +544,42 @@ });

context('when there is missing or malformed required information', function () {
let facilities;
context(
'when there is missing or malformed required information',
function() {
let facilities;
beforeEach(function () {
facilities = new Facilities(baseSdk, baseRequest);
});
beforeEach(function() {
facilities = new Facilities(baseSdk, baseRequest);
});
it('throws an error when there is no provided facility id', function () {
const facilityUpdate = fixture.build('facility');
const promise = facilities.update(null, facilityUpdate);
it('throws an error when there is no provided facility id', function() {
const facilityUpdate = fixture.build('facility');
const promise = facilities.update(null, facilityUpdate);
return expect(promise).to.be
.rejectedWith('A facility ID is required to update a facility.');
});
return expect(promise).to.be.rejectedWith(
'A facility ID is required to update a facility.'
);
});
it('throws an error when there is no update provided', function () {
const facilityUpdate = fixture.build('facility');
const promise = facilities.update(facilityUpdate.id);
it('throws an error when there is no update provided', function() {
const facilityUpdate = fixture.build('facility');
const promise = facilities.update(facilityUpdate.id);
return expect(promise).to.be.rejectedWith('An update is required to update a facility.');
});
return expect(promise).to.be.rejectedWith(
'An update is required to update a facility.'
);
});
it('throws an error when the update is not an object', function () {
const facilityUpdate = fixture.build('facility');
const promise = facilities.update(facilityUpdate.id, [facilityUpdate]);
it('throws an error when the update is not an object', function() {
const facilityUpdate = fixture.build('facility');
const promise = facilities.update(facilityUpdate.id, [
facilityUpdate
]);
return expect(promise).to.be.rejectedWith(
'The facility update must be a well-formed object with the data you wish to update.'
);
});
});
return expect(promise).to.be.rejectedWith(
'The facility update must be a well-formed object with the data you wish to update.'
);
});
}
);
});
});

@@ -33,3 +33,5 @@ import times from 'lodash.times';

beforeEach(function() {
expectedExternalModules = times(faker.random.number({ min: 1, max: 5 })).reduce((memo) => {
expectedExternalModules = times(
faker.random.number({ min: 1, max: 5 })
).reduce((memo) => {
const moduleName = faker.hacker.verb();

@@ -45,3 +47,4 @@ memo[moduleName] = {

createAuthSession = this.sandbox.stub(ContxtSdk.prototype, '_createAuthSession')
createAuthSession = this.sandbox
.stub(ContxtSdk.prototype, '_createAuthSession')
.returns(expectedAuthSession);

@@ -89,6 +92,10 @@ createRequest = this.sandbox.stub(ContxtSdk.prototype, '_createRequest');

const authSessionStub = this.sandbox.stub(sessionTypes, authSessionConfig.moduleName)
const authSessionStub = this.sandbox
.stub(sessionTypes, authSessionConfig.moduleName)
.returns(expectedSession);
const authSession = ContxtSdk.prototype._createAuthSession.call(instance, authSessionConfig.sessionType);
const authSession = ContxtSdk.prototype._createAuthSession.call(
instance,
authSessionConfig.sessionType
);

@@ -112,3 +119,4 @@ expect(authSessionStub).to.be.calledWithNew;

it('throws an error if no session type is provided', function() {
const fn = () => ContxtSdk.prototype._createAuthSession.call({ config: baseConfig });
const fn = () =>
ContxtSdk.prototype._createAuthSession.call({ config: baseConfig });

@@ -128,3 +136,6 @@ expect(fn).to.throw('Invalid sessionType provided');

request = ContxtSdk.prototype._createRequest.call(expectedInstance, expectedAudienceName);
request = ContxtSdk.prototype._createRequest.call(
expectedInstance,
expectedAudienceName
);
});

@@ -144,9 +155,13 @@

beforeEach(function() {
externalModules = times(faker.random.number({ min: 1, max: 5 })).reduce((memo) => {
const moduleName = faker.hacker.verb();
memo[moduleName] = { module: this.sandbox.stub() };
return memo;
}, {});
externalModules = times(faker.random.number({ min: 1, max: 5 })).reduce(
(memo) => {
const moduleName = faker.hacker.verb();
memo[moduleName] = { module: this.sandbox.stub() };
return memo;
},
{}
);
instance = {
_createRequest: this.sandbox.stub()
_createRequest: this.sandbox
.stub()
.callsFake((moduleName) => `request module for: ${moduleName}`)

@@ -167,4 +182,6 @@ };

expect(externalModules[module].module).to.be.calledWithNew;
expect(externalModules[module].module)
.to.be.calledWith(instance, `request module for: ${module}`);
expect(externalModules[module].module).to.be.calledWith(
instance,
`request module for: ${module}`
);
}

@@ -175,3 +192,5 @@ });

for (const module in externalModules) {
expect(instance[module]).to.be.an.instanceof(externalModules[module].module);
expect(instance[module]).to.be.an.instanceof(
externalModules[module].module
);
}

@@ -178,0 +197,0 @@ });

@@ -25,4 +25,3 @@ import axios from 'axios';

delete(...args) {
return this._axios.delete(...args)
.then(({ data }) => data);
return this._axios.delete(...args).then(({ data }) => data);
}

@@ -38,4 +37,3 @@

get(...args) {
return this._axios.get(...args)
.then(({ data }) => data);
return this._axios.get(...args).then(({ data }) => data);
}

@@ -51,4 +49,3 @@

head(...args) {
return this._axios.head(...args)
.then(({ data }) => data);
return this._axios.head(...args).then(({ data }) => data);
}

@@ -64,4 +61,3 @@

options(...args) {
return this._axios.options(...args)
.then(({ data }) => data);
return this._axios.options(...args).then(({ data }) => data);
}

@@ -77,4 +73,3 @@

patch(...args) {
return this._axios.patch(...args)
.then(({ data }) => data);
return this._axios.patch(...args).then(({ data }) => data);
}

@@ -90,4 +85,3 @@

post(...args) {
return this._axios.post(...args)
.then(({ data }) => data);
return this._axios.post(...args).then(({ data }) => data);
}

@@ -103,4 +97,3 @@

put(...args) {
return this._axios.put(...args)
.then(({ data }) => data);
return this._axios.put(...args).then(({ data }) => data);
}

@@ -116,4 +109,3 @@

request(...args) {
return this._axios.request(...args)
.then(({ data }) => data);
return this._axios.request(...args).then(({ data }) => data);
}

@@ -134,3 +126,4 @@

_insertHeaders = (config) => {
return this._sdk.auth.getCurrentApiToken(this._audienceName)
return this._sdk.auth
.getCurrentApiToken(this._audienceName)
.then((apiToken) => {

@@ -141,5 +134,5 @@ config.headers.common.Authorization = `Bearer ${apiToken}`;

});
}
};
}
export default Request;

@@ -54,3 +54,5 @@ import axios from 'axios';

expect(baseAxiosInstance.interceptors.request.use).to.be.calledOnce;
const [requestInterceptor] = baseAxiosInstance.interceptors.request.use.firstCall.args;
const [
requestInterceptor
] = baseAxiosInstance.interceptors.request.use.firstCall.args;
expect(requestInterceptor).to.be.a('function');

@@ -78,7 +80,11 @@ expect(requestInterceptor).to.equal(request._insertHeaders);

beforeEach(function() {
expectedArgs = times(faker.random.number({ min: 1, max: 10 })).map(faker.hacker.phrase);
expectedArgs = times(faker.random.number({ min: 1, max: 10 })).map(
faker.hacker.phrase
);
expectedResponse = faker.hacker.phrase();
axiosInstance = {
...baseAxiosInstance,
[method]: this.sandbox.stub().callsFake(() => Promise.resolve({ data: expectedResponse }))
[method]: this.sandbox
.stub()
.callsFake(() => Promise.resolve({ data: expectedResponse }))
};

@@ -97,4 +103,5 @@

it('returns the promise with the requested data', function() {
return expect(response).to.be.fulfilled
.and.to.eventually.equal(expectedResponse);
return expect(response).to.be.fulfilled.and.to.eventually.equal(
expectedResponse
);
});

@@ -131,3 +138,5 @@ });

it("gets a current token from the sdk's auth module", function() {
expect(sdk.auth.getCurrentApiToken).to.be.calledWith(expectedAudienceName);
expect(sdk.auth.getCurrentApiToken).to.be.calledWith(
expectedAudienceName
);
});

@@ -142,3 +151,5 @@

expect(config).to.equal(initialConfig);
expect(config.headers.common.Authorization).to.equal(`Bearer ${expectedToken}`);
expect(config.headers.common.Authorization).to.equal(
`Bearer ${expectedToken}`
);
});

@@ -145,0 +156,0 @@ });

@@ -70,3 +70,4 @@ import auth0 from 'auth0-js';

this._onRedirect = this._sdk.config.auth.onRedirect || this._defaultOnRedirect;
this._onRedirect =
this._sdk.config.auth.onRedirect || this._defaultOnRedirect;
this._sessionInfo = this._loadSession();

@@ -115,20 +116,19 @@

getProfile() {
return this.getCurrentAccessToken()
.then((accessToken) => {
return new Promise((resolve, reject) => {
this._auth0.client.userInfo(accessToken, (err, profile) => {
if (err) {
reject(err);
}
return this.getCurrentAccessToken().then((accessToken) => {
return new Promise((resolve, reject) => {
this._auth0.client.userInfo(accessToken, (err, profile) => {
if (err) {
reject(err);
}
const formattedProfile = {
...profile,
updatedAt: profile.updated_at
};
delete formattedProfile.updated_at;
const formattedProfile = {
...profile,
updatedAt: profile.updated_at
};
delete formattedProfile.updated_at;
resolve(formattedProfile);
});
resolve(formattedProfile);
});
});
});
}

@@ -150,3 +150,3 @@

accessToken: hash.accessToken,
expiresAt: (hash.expiresIn * 1000) + Date.now()
expiresAt: hash.expiresIn * 1000 + Date.now()
},

@@ -188,4 +188,8 @@ this._getApiToken(hash.accessToken)

isAuthenticated() {
const hasTokens = !!(this._sessionInfo && this._sessionInfo.accessToken &&
this._sessionInfo.apiToken && this._sessionInfo.expiresAt);
const hasTokens = !!(
this._sessionInfo &&
this._sessionInfo.accessToken &&
this._sessionInfo.apiToken &&
this._sessionInfo.expiresAt
);

@@ -239,4 +243,10 @@ return hasTokens && this._sessionInfo.expiresAt > Date.now();

audiences: Object.keys(this._sdk.config.audiences)
.map((audienceName) => this._sdk.config.audiences[audienceName].clientId)
.filter((clientId) => clientId !== this._sdk.config.audiences.contxtAuth.clientId),
.map(
(audienceName) =>
this._sdk.config.audiences[audienceName].clientId
)
.filter(
(clientId) =>
clientId !== this._sdk.config.audiences.contxtAuth.clientId
),
nonce: 'nonce'

@@ -318,3 +328,5 @@ },

if (err || !hashResponse) {
return reject(err || new Error('No valid tokens returned from auth0'));
return reject(
err || new Error('No valid tokens returned from auth0')
);
}

@@ -321,0 +333,0 @@

@@ -57,3 +57,5 @@ import auth0 from 'auth0-js';

loadSession = this.sandbox.stub(Auth0WebAuth.prototype, '_loadSession').returns(expectedSession);
loadSession = this.sandbox
.stub(Auth0WebAuth.prototype, '_loadSession')
.returns(expectedSession);

@@ -68,3 +70,5 @@ auth0WebAuth = new Auth0WebAuth(sdk);

it('sets the default onRedirect method to the class instance', function() {
expect(auth0WebAuth._onRedirect).to.equal(Auth0WebAuth.prototype._defaultOnRedirect);
expect(auth0WebAuth._onRedirect).to.equal(
Auth0WebAuth.prototype._defaultOnRedirect
);
});

@@ -86,3 +90,5 @@

domain: 'ndustrial.auth0.com',
redirectUri: `${global.window.location}/${sdk.config.auth.authorizationPath}`,
redirectUri: `${global.window.location}/${
sdk.config.auth.authorizationPath
}`,
responseType: 'token',

@@ -120,3 +126,5 @@ scope: 'profile openid'

const [{ redirectUri }] = webAuth.firstCall.args;
expect(redirectUri).to.match(new RegExp(`${expectedAuthorizationPath}$`));
expect(redirectUri).to.match(
new RegExp(`${expectedAuthorizationPath}$`)
);
});

@@ -148,3 +156,4 @@ });

getCurrentTokenByType = this.sandbox.stub(Auth0WebAuth.prototype, '_getCurrentTokenByType')
getCurrentTokenByType = this.sandbox
.stub(Auth0WebAuth.prototype, '_getCurrentTokenByType')
.resolves(expectedToken);

@@ -162,4 +171,5 @@ this.sandbox.stub(Auth0WebAuth.prototype, '_loadSession');

it('returns a promise with the token', function() {
return expect(promise).to.be.fulfilled
.and.to.eventually.equal(expectedToken);
return expect(promise).to.be.fulfilled.and.to.eventually.equal(
expectedToken
);
});

@@ -181,5 +191,8 @@ });

profile = fixture.build('userProfile', null, { fromServer: true });
expectedProfile = omit({ ...profile, updatedAt: profile.updated_at }, ['updated_at']);
expectedProfile = omit({ ...profile, updatedAt: profile.updated_at }, [
'updated_at'
]);
getCurrentAccessToken = this.sandbox.stub(Auth0WebAuth.prototype, 'getCurrentAccessToken')
getCurrentAccessToken = this.sandbox
.stub(Auth0WebAuth.prototype, 'getCurrentAccessToken')
.resolves(expectedAccessToken);

@@ -203,3 +216,5 @@ this.sandbox.stub(Auth0WebAuth.prototype, '_loadSession');

return promise.then(() => {
expect(webAuthSession.client.userInfo).to.be.calledWith(expectedAccessToken);
expect(webAuthSession.client.userInfo).to.be.calledWith(
expectedAccessToken
);
});

@@ -209,4 +224,5 @@ });

it("returns a fulfilled promise with the users's profile", function() {
return expect(promise).to.be.fulfilled
.and.to.eventually.deep.equal(expectedProfile);
return expect(promise).to.be.fulfilled.and.to.eventually.deep.equal(
expectedProfile
);
});

@@ -222,3 +238,4 @@ });

this.sandbox.stub(Auth0WebAuth.prototype, 'getCurrentAccessToken')
this.sandbox
.stub(Auth0WebAuth.prototype, 'getCurrentAccessToken')
.resolves(faker.internet.password());

@@ -265,15 +282,21 @@ this.sandbox.stub(Auth0WebAuth.prototype, '_loadSession');

clock = sinon.useFakeTimers(currentDate);
getApiToken = this.sandbox.stub(Auth0WebAuth.prototype, '_getApiToken').callsFake(() => {
return Promise.resolve(expectedSessionInfo.apiToken);
});
getRedirectPathname = this.sandbox.stub(Auth0WebAuth.prototype, '_getRedirectPathname')
getApiToken = this.sandbox
.stub(Auth0WebAuth.prototype, '_getApiToken')
.callsFake(() => {
return Promise.resolve(expectedSessionInfo.apiToken);
});
getRedirectPathname = this.sandbox
.stub(Auth0WebAuth.prototype, '_getRedirectPathname')
.returns(expectedRedirectPathname);
this.sandbox.stub(Auth0WebAuth.prototype, '_loadSession');
onRedirect = this.sandbox.stub();
parseWebAuthHash = this.sandbox.stub(Auth0WebAuth.prototype, '_parseWebAuthHash').callsFake(() => {
return Promise.resolve({
accessToken: expectedSessionInfo.accessToken,
expiresIn: (expectedSessionInfo.expiresAt - currentDate.getTime()) / 1000
parseWebAuthHash = this.sandbox
.stub(Auth0WebAuth.prototype, '_parseWebAuthHash')
.callsFake(() => {
return Promise.resolve({
accessToken: expectedSessionInfo.accessToken,
expiresIn:
(expectedSessionInfo.expiresAt - currentDate.getTime()) / 1000
});
});
});
saveSession = this.sandbox.stub(Auth0WebAuth.prototype, '_saveSession');

@@ -329,4 +352,5 @@ global.window = {

it('returns a promise that is fulfilled with the web auth info and contxt api token', function() {
return expect(promise).to.be.fulfilled
.and.to.eventually.deep.equal(expectedSessionInfo);
return expect(promise).to.be.fulfilled.and.to.eventually.deep.equal(
expectedSessionInfo
);
});

@@ -343,10 +367,14 @@ });

this.sandbox.stub(Auth0WebAuth.prototype, '_getApiToken').callsFake(() => {
return Promise.reject(expectedError);
});
this.sandbox
.stub(Auth0WebAuth.prototype, '_getApiToken')
.callsFake(() => {
return Promise.reject(expectedError);
});
this.sandbox.stub(Auth0WebAuth.prototype, '_loadSession');
onRedirect = this.sandbox.stub();
this.sandbox.stub(Auth0WebAuth.prototype, '_parseWebAuthHash').callsFake(() => {
return Promise.resolve({});
});
this.sandbox
.stub(Auth0WebAuth.prototype, '_parseWebAuthHash')
.callsFake(() => {
return Promise.resolve({});
});
global.window = {

@@ -368,7 +396,5 @@ _location: `${faker.internet.url()}/${faker.hacker.adjective()}`,

it("assigns the new redirect url to the browsers's location", function() {
return promise
.then(expect.fail)
.catch(() => {
expect(onRedirect).to.be.calledWith('/');
});
return promise.then(expect.fail).catch(() => {
expect(onRedirect).to.be.calledWith('/');
});
});

@@ -573,4 +599,5 @@

it('returns a promise that fulfills with the api access token', function() {
return expect(promise).to.be.fulfilled
.and.to.eventually.equal(expectedApiToken);
return expect(promise).to.be.fulfilled.and.to.eventually.equal(
expectedApiToken
);
});

@@ -602,4 +629,5 @@ });

return expect(promise).to.be.fulfilled
.and.to.eventually.equal(expectedToken);
return expect(promise).to.be.fulfilled.and.to.eventually.equal(
expectedToken
);
});

@@ -627,3 +655,5 @@ });

this.sandbox.stub(Auth0WebAuth.prototype, '_loadSession');
global.localStorage.getItem = this.sandbox.stub().returns(expectedPathname);
global.localStorage.getItem = this.sandbox
.stub()
.returns(expectedPathname);

@@ -635,7 +665,11 @@ const auth0WebAuth = new Auth0WebAuth(sdk);

it('gets the stored pathname from local storage', function() {
expect(global.localStorage.getItem).to.be.calledWith('redirect_pathname');
expect(global.localStorage.getItem).to.be.calledWith(
'redirect_pathname'
);
});
it('removes the previously stored pathname from local storage', function() {
expect(global.localStorage.removeItem).to.be.calledWith('redirect_pathname');
expect(global.localStorage.removeItem).to.be.calledWith(
'redirect_pathname'
);
});

@@ -733,3 +767,5 @@

expectedHash = faker.helpers.createTransaction();
webAuthSession.parseHash = this.sandbox.stub().callsFake((cb) => cb(null, expectedHash));
webAuthSession.parseHash = this.sandbox
.stub()
.callsFake((cb) => cb(null, expectedHash));

@@ -755,3 +791,5 @@ const auth0WebAuth = new Auth0WebAuth(sdk);

expectedError = new Error(faker.hacker.phrase());
webAuthSession.parseHash = this.sandbox.stub().callsFake((cb) => cb(expectedError));
webAuthSession.parseHash = this.sandbox
.stub()
.callsFake((cb) => cb(expectedError));

@@ -762,3 +800,5 @@ auth0WebAuth = new Auth0WebAuth(sdk);

it('returns with a rejected promise', function() {
return expect(auth0WebAuth._parseWebAuthHash()).to.be.rejectedWith(expectedError);
return expect(auth0WebAuth._parseWebAuthHash()).to.be.rejectedWith(
expectedError
);
});

@@ -771,3 +811,5 @@ });

beforeEach(function() {
webAuthSession.parseHash = this.sandbox.stub().callsFake((cb) => cb(null, null));
webAuthSession.parseHash = this.sandbox
.stub()
.callsFake((cb) => cb(null, null));

@@ -778,4 +820,5 @@ auth0WebAuth = new Auth0WebAuth(sdk);

it('returns with a rejected promise', function() {
return expect(auth0WebAuth._parseWebAuthHash())
.to.be.rejectedWith('No valid tokens returned from auth0');
return expect(auth0WebAuth._parseWebAuthHash()).to.be.rejectedWith(
'No valid tokens returned from auth0'
);
});

@@ -816,16 +859,22 @@ });

it('saves the access token to local storage', function() {
expect(localStorage.setItem)
.to.be.calledWith('access_token', expectedSessionInfo.accessToken);
expect(localStorage.setItem).to.be.calledWith(
'access_token',
expectedSessionInfo.accessToken
);
});
it('saves the api access token to local storage', function() {
expect(localStorage.setItem)
.to.be.calledWith('api_token', expectedSessionInfo.apiToken);
expect(localStorage.setItem).to.be.calledWith(
'api_token',
expectedSessionInfo.apiToken
);
});
it('saves the expires at information to local storage', function() {
expect(localStorage.setItem)
.to.be.calledWith('expires_at', expectedSessionInfo.expiresAt);
expect(localStorage.setItem).to.be.calledWith(
'expires_at',
expectedSessionInfo.expiresAt
);
});
});
});

@@ -1,7 +0,3 @@

import Auth0WebAuth, {
TYPE as AUTH0_WEB_AUTH
} from './auth0WebAuth';
import MachineAuth, {
TYPE as MACHINE_AUTH
} from './machineAuth';
import Auth0WebAuth, { TYPE as AUTH0_WEB_AUTH } from './auth0WebAuth';
import MachineAuth, { TYPE as MACHINE_AUTH } from './machineAuth';

@@ -13,6 +9,2 @@ const TYPES = {

export {
Auth0WebAuth,
MachineAuth,
TYPES
};
export { Auth0WebAuth, MachineAuth, TYPES };
import axios from 'axios';
/**
* @typedef {Object} MachineAuthSessionInfo
* @property {string} apiToken
* @property {number} expiresAt
*/
* @typedef {Object} MachineAuthSessionInfo
* @property {string} apiToken
* @property {number} expiresAt
*/

@@ -62,4 +62,5 @@ /**

return this._getNewSessionInfo(audienceName)
.then((sessionInfo) => sessionInfo.apiToken);
return this._getNewSessionInfo(audienceName).then(
(sessionInfo) => sessionInfo.apiToken
);
}

@@ -79,7 +80,5 @@

const {
apiToken,
expiresAt
} = this._sessionInfo[audienceName];
const tokenExpiresAtBufferMs = this._sdk.config.auth.tokenExpiresAtBufferMs || 0;
const { apiToken, expiresAt } = this._sessionInfo[audienceName];
const tokenExpiresAtBufferMs =
this._sdk.config.auth.tokenExpiresAtBufferMs || 0;
const bufferedExpiresAt = expiresAt - tokenExpiresAtBufferMs;

@@ -109,15 +108,12 @@

this._tokenPromise = axios
.post(
`${this._sdk.config.audiences.contxtAuth.host}/v1/oauth/token`,
{
audience: audience.clientId,
client_id: this._sdk.config.auth.clientId,
client_secret: this._sdk.config.auth.clientSecret,
grant_type: 'client_credentials'
}
)
.post(`${this._sdk.config.audiences.contxtAuth.host}/v1/oauth/token`, {
audience: audience.clientId,
client_id: this._sdk.config.auth.clientId,
client_secret: this._sdk.config.auth.clientSecret,
grant_type: 'client_credentials'
})
.then(({ data }) => {
return {
apiToken: data.access_token,
expiresAt: Date.now() + (data.expires_in * 1000)
expiresAt: Date.now() + data.expires_in * 1000
};

@@ -133,3 +129,5 @@ })

if (!(err.response && err.response.status)) {
throw new Error('There was a problem getting a token from the ContxtAuth server. Please check your configuration settings.');
throw new Error(
'There was a problem getting a token from the ContxtAuth server. Please check your configuration settings.'
);
}

@@ -136,0 +134,0 @@

@@ -59,3 +59,5 @@ import axios from 'axios';

expect(fn).to.throw('clientSecret is required for the MachineAuth config');
expect(fn).to.throw(
'clientSecret is required for the MachineAuth config'
);
});

@@ -81,3 +83,4 @@ });

getNewSessionInfo = this.sandbox.stub(MachineAuth.prototype, '_getNewSessionInfo')
getNewSessionInfo = this.sandbox
.stub(MachineAuth.prototype, '_getNewSessionInfo')
.resolves(expectedSessionInfo);

@@ -88,3 +91,4 @@ });

beforeEach(function() {
isAuthenticated = this.sandbox.stub(MachineAuth.prototype, 'isAuthenticated')
isAuthenticated = this.sandbox
.stub(MachineAuth.prototype, 'isAuthenticated')
.returns(false);

@@ -105,4 +109,5 @@

it('returns a promise with the new apiToken', function() {
return expect(promise).to.be.fulfilled
.and.to.eventually.equal(expectedApiToken);
return expect(promise).to.be.fulfilled.and.to.eventually.equal(
expectedApiToken
);
});

@@ -113,3 +118,4 @@ });

beforeEach(function() {
isAuthenticated = this.sandbox.stub(MachineAuth.prototype, 'isAuthenticated')
isAuthenticated = this.sandbox
.stub(MachineAuth.prototype, 'isAuthenticated')
.returns(true);

@@ -132,4 +138,5 @@

it('returns a promise with the previously acquired apiToken', function() {
return expect(promise).to.be.fulfilled
.and.to.eventually.equal(expectedApiToken);
return expect(promise).to.be.fulfilled.and.to.eventually.equal(
expectedApiToken
);
});

@@ -250,3 +257,5 @@ });

});
post = this.sandbox.stub(axios, 'post').callsFake(() => expectedPromise);
post = this.sandbox
.stub(axios, 'post')
.callsFake(() => expectedPromise);
saveSession = this.sandbox.stub(MachineAuth.prototype, '_saveSession');

@@ -265,3 +274,5 @@

const [endpoint, credentials] = post.firstCall.args;
expect(endpoint).to.equal(`${sdk.config.audiences.contxtAuth.host}/v1/oauth/token`);
expect(endpoint).to.equal(
`${sdk.config.audiences.contxtAuth.host}/v1/oauth/token`
);
expect(credentials).to.deep.equal({

@@ -281,3 +292,6 @@ audience: expectedAudience.clientId,

return promise.then(() => {
expect(saveSession).to.be.calledWith(audienceName, expectedSessionInfo);
expect(saveSession).to.be.calledWith(
audienceName,
expectedSessionInfo
);
});

@@ -293,4 +307,5 @@ });

it('returns a fulfilled promise with the api token and an expiration time', function() {
return expect(promise).to.be.fulfilled
.and.to.eventually.deep.equal(expectedSessionInfo);
return expect(promise).to.be.fulfilled.and.to.eventually.deep.equal(
expectedSessionInfo
);
});

@@ -318,18 +333,21 @@ });

context('when there is not a configuration for chosen audience', function() {
let promise;
context(
'when there is not a configuration for chosen audience',
function() {
let promise;
beforeEach(function() {
const audienceName = faker.hacker.adjective();
beforeEach(function() {
const audienceName = faker.hacker.adjective();
this.sandbox.stub(axios, 'post');
this.sandbox.stub(axios, 'post');
const machineAuth = new MachineAuth(sdk);
promise = machineAuth._getNewSessionInfo(audienceName);
});
const machineAuth = new MachineAuth(sdk);
promise = machineAuth._getNewSessionInfo(audienceName);
});
it('returns a rejected promise', function() {
return expect(promise).to.be.rejectedWith('No valid audience found');
});
});
it('returns a rejected promise', function() {
return expect(promise).to.be.rejectedWith('No valid audience found');
});
}
);

@@ -379,3 +397,5 @@ context('when there is an error getting a token', function() {

};
initialSessionInfo = times(faker.random.number({ min: 1, max: 10 })).reduce((memo) => {
initialSessionInfo = times(
faker.random.number({ min: 1, max: 10 })
).reduce((memo) => {
memo[faker.hacker.verb()] = {

@@ -399,5 +419,7 @@ apiToken: faker.internet.password(),

it("saves the new session info the auth module's instance", function() {
expect(machineAuth._sessionInfo[audienceName]).to.include(expectedSessionInfo);
expect(machineAuth._sessionInfo[audienceName]).to.include(
expectedSessionInfo
);
});
});
});

@@ -75,3 +75,5 @@ import {

if (input.facility_groupings) {
facility.facility_groupings = input.facility_groupings.map(formatGroupingFromServer);
facility.facility_groupings = input.facility_groupings.map(
formatGroupingFromServer
);
}

@@ -78,0 +80,0 @@

@@ -5,3 +5,3 @@ import omit from 'lodash.omit';

describe('utils/facilities/formatFacilityFromServer', function () {
describe('utils/facilities/formatFacilityFromServer', function() {
let formatOrganizationFromServer;

@@ -11,18 +11,21 @@ let formatTagsFromServer;

beforeEach(function () {
beforeEach(function() {
this.sandbox = sandbox.create();
formatOrganizationFromServer = this.sandbox.stub(facilitiesUtils, 'formatOrganizationFromServer')
formatOrganizationFromServer = this.sandbox
.stub(facilitiesUtils, 'formatOrganizationFromServer')
.callsFake((organization) => organization);
formatTagsFromServer = this.sandbox.stub(facilitiesUtils, 'formatTagsFromServer')
formatTagsFromServer = this.sandbox
.stub(facilitiesUtils, 'formatTagsFromServer')
.callsFake((tags) => tags);
formatGroupingFromServer = this.sandbox.stub(facilitiesUtils, 'formatGroupingFromServer')
formatGroupingFromServer = this.sandbox
.stub(facilitiesUtils, 'formatGroupingFromServer')
.callsFake((grouping) => grouping);
});
afterEach(function () {
afterEach(function() {
this.sandbox.restore();
});
context('when all possible fields are in the facility object', function () {
context('when all possible fields are in the facility object', function() {
let expectedFacility;

@@ -32,22 +35,25 @@ let facility;

beforeEach(function () {
beforeEach(function() {
facility = fixture.build('facility', null, {
fromServer: true
});
expectedFacility = omit({
...facility,
createdAt: facility.created_at,
geometryId: facility.geometry_id,
info: facility.Info,
organization: facility.Organization,
organizationId: facility.organization_id,
weatherLocationId: facility.weather_location_id
}, [
'created_at',
'geometry_id',
'Info',
'Organization',
'organization_id',
'weather_location_id'
]);
expectedFacility = omit(
{
...facility,
createdAt: facility.created_at,
geometryId: facility.geometry_id,
info: facility.Info,
organization: facility.Organization,
organizationId: facility.organization_id,
weatherLocationId: facility.weather_location_id
},
[
'created_at',
'geometry_id',
'Info',
'Organization',
'organization_id',
'weather_location_id'
]
);

@@ -57,4 +63,6 @@ formattedFacility = formatFacilityFromServer(facility);

it('formats the necessary children objects', function () {
expect(formatOrganizationFromServer).to.be.calledWith(facility.Organization);
it('formats the necessary children objects', function() {
expect(formatOrganizationFromServer).to.be.calledWith(
facility.Organization
);
expect(formatTagsFromServer).to.be.calledWith(facility.tags);

@@ -66,3 +74,3 @@ facility.facility_groupings.forEach((grouping) =>

it('converts the object keys to the camelCase', function () {
it('converts the object keys to the camelCase', function() {
expect(formattedFacility).to.deep.equal(expectedFacility);

@@ -72,46 +80,49 @@ });

context('when the facilities object does not have all possible keys', function () {
it('does not include the facility info if facility info is in the initial data', function () {
const facility = fixture.build('facility', null, {
fromServer: true
context(
'when the facilities object does not have all possible keys',
function() {
it('does not include the facility info if facility info is in the initial data', function() {
const facility = fixture.build('facility', null, {
fromServer: true
});
delete facility.Info;
const formattedFacility = formatFacilityFromServer(facility);
expect(formattedFacility).to.not.include.keys(['info']);
});
delete facility.Info;
const formattedFacility = formatFacilityFromServer(facility);
expect(formattedFacility).to.not.include.keys(['info']);
});
it('does not include the organization if organization info is not in the initial data', function() {
const facility = fixture.build('facility', null, {
fromServer: true
});
delete facility.Organization;
const formattedFacility = formatFacilityFromServer(facility);
it('does not include the organization if organization info is not in the initial data', function () {
const facility = fixture.build('facility', null, {
fromServer: true
expect(formatOrganizationFromServer).to.be.not.called;
expect(formattedFacility).to.not.include.keys(['organization']);
});
delete facility.Organization;
const formattedFacility = formatFacilityFromServer(facility);
expect(formatOrganizationFromServer).to.be.not.called;
expect(formattedFacility).to.not.include.keys(['organization']);
});
it('does not include the tags if tags are not in the initial data', function() {
const facility = fixture.build('facility', null, {
fromServer: true
});
delete facility.tags;
const formattedFacility = formatFacilityFromServer(facility);
it('does not include the tags if tags are not in the initial data', function () {
const facility = fixture.build('facility', null, {
fromServer: true
expect(formatTagsFromServer).to.be.not.called;
expect(formattedFacility).to.not.include.keys(['tags']);
});
delete facility.tags;
const formattedFacility = formatFacilityFromServer(facility);
expect(formatTagsFromServer).to.be.not.called;
expect(formattedFacility).to.not.include.keys(['tags']);
});
it('does not include the facilities groupings if groupings are not in the initial data', function() {
const facility = fixture.build('facility', null, {
fromServer: true
});
delete facility.facility_groupings;
const formattedFacility = formatFacilityFromServer(facility);
it('does not include the facilities groupings if groupings are not in the initial data', function () {
const facility = fixture.build('facility', null, {
fromServer: true
expect(formatGroupingFromServer).to.be.not.called;
expect(formattedFacility).to.not.include.keys(['facility_groupings']);
});
delete facility.facility_groupings;
const formattedFacility = formatFacilityFromServer(facility);
expect(formatGroupingFromServer).to.be.not.called;
expect(formattedFacility).to.not.include.keys(['facility_groupings']);
});
});
}
);
});

@@ -16,3 +16,4 @@ /**

...options,
include_groupings: options && options.includeGroupings ? options.includeGroupings : false
include_groupings:
options && options.includeGroupings ? options.includeGroupings : false
};

@@ -19,0 +20,0 @@

import times from 'lodash.times';
import formatFacilityOptionsToServer from './formatFacilityOptionsToServer';
describe('utils/facilities/formatFacilityOptionsToServer', function () {
it('provides a default object if no options passed', function () {
describe('utils/facilities/formatFacilityOptionsToServer', function() {
it('provides a default object if no options passed', function() {
const options = formatFacilityOptionsToServer();

@@ -12,7 +12,9 @@ expect(options).to.deep.equal({

it('provides an object that includes any custom options', function () {
const customOptions = times(faker.random.number({
min: 1,
max: 10
})).reduce(memo => {
it('provides an object that includes any custom options', function() {
const customOptions = times(
faker.random.number({
min: 1,
max: 10
})
).reduce((memo) => {
memo[faker.hacker.adjective()] = faker.helpers.createTransaction();

@@ -31,8 +33,10 @@ return memo;

it('provides an object that includes the `include_groupings` that the API service can understand', function () {
it('provides an object that includes the `include_groupings` that the API service can understand', function() {
const expectedIncludeGroupings = faker.random.boolean();
const customOptions = times(faker.random.number({
min: 1,
max: 10
})).reduce(memo => {
const customOptions = times(
faker.random.number({
min: 1,
max: 10
})
).reduce((memo) => {
memo[faker.hacker.adjective()] = faker.helpers.createTransaction();

@@ -46,3 +50,4 @@ return memo;

const options = formatFacilityOptionsToServer({ ...customOptions,
const options = formatFacilityOptionsToServer({
...customOptions,
includeGroupings: expectedIncludeGroupings

@@ -49,0 +54,0 @@ });

import omit from 'lodash.omit';
import formatFacilityToServer from './formatFacilityToServer';
describe('utils/facilities/formatFacilityToServer', function () {
describe('utils/facilities/formatFacilityToServer', function() {
let expectedFacility;

@@ -9,21 +9,24 @@ let facility;

beforeEach(function () {
beforeEach(function() {
facility = fixture.build('facility');
expectedFacility = omit({
...facility,
geometry_id: facility.geometryId,
Info: facility.info,
organization_id: facility.organizationId,
weather_location_id: facility.weatherLocationId
}, [
'createdAt',
'facility_groupings',
'geometryId',
'id',
'info',
'organization',
'organizationId',
'tags',
'weatherLocationId'
]);
expectedFacility = omit(
{
...facility,
geometry_id: facility.geometryId,
Info: facility.info,
organization_id: facility.organizationId,
weather_location_id: facility.weatherLocationId
},
[
'createdAt',
'facility_groupings',
'geometryId',
'id',
'info',
'organization',
'organizationId',
'tags',
'weatherLocationId'
]
);

@@ -33,5 +36,5 @@ formattedFacility = formatFacilityToServer(facility);

it('converts the object keys to snake case and capitalizes certain keys', function () {
it('converts the object keys to snake case and capitalizes certain keys', function() {
expect(formattedFacility).to.deep.equal(expectedFacility);
});
});

@@ -10,3 +10,5 @@ import omit from 'lodash.omit';

beforeEach(function() {
groupingFacility = fixture.build('facilityGroupingFacility', null, { fromServer: true });
groupingFacility = fixture.build('facilityGroupingFacility', null, {
fromServer: true
});
expectedGroupingFacility = omit(

@@ -23,3 +25,5 @@ {

formattedGroupingFacility = formatGroupingFacilityFromServer(groupingFacility);
formattedGroupingFacility = formatGroupingFacilityFromServer(
groupingFacility
);
});

@@ -26,0 +30,0 @@

@@ -1,4 +0,2 @@

import {
formatFacilityFromServer
} from './index';
import { formatFacilityFromServer } from './index';

@@ -5,0 +3,0 @@ /**

@@ -10,7 +10,3 @@ import omit from 'lodash.omit';

beforeEach(function() {
organization = fixture.build(
'organization',
null,
{ fromServer: true }
);
organization = fixture.build('organization', null, { fromServer: true });
expectedOrganization = omit(

@@ -17,0 +13,0 @@ {

@@ -0,1 +1,4 @@

import formatCostCenterFacilityFromServer from './formatCostCenterFacilityFromServer';
import formatCostCenterFromServer from './formatCostCenterFromServer';
import formatCostCenterToServer from './formatCostCenterToServer';
import formatFacilityFromServer from './formatFacilityFromServer';

@@ -11,2 +14,5 @@ import formatFacilityToServer from './formatFacilityToServer';

export {
formatCostCenterFacilityFromServer,
formatCostCenterFromServer,
formatCostCenterToServer,
formatFacilityFromServer,

@@ -13,0 +19,0 @@ formatFacilityToServer,

@@ -15,5 +15,3 @@ 'use strict';

helper: path.join(__dirname, 'helpers.js'),
partial: [
path.join(__dirname, 'partials', 'sig-link-html.hbs')
]
partial: [path.join(__dirname, 'partials', 'sig-link-html.hbs')]
});

@@ -20,0 +18,0 @@ const outputPath = path.resolve(outputDir, 'README.md');

@@ -43,3 +43,5 @@ 'use strict';

sortBy(
identifiers(options).filter((identifier) => identifier.kind === 'typedef'),
identifiers(options).filter(
(identifier) => identifier.kind === 'typedef'
),
'longname'

@@ -46,0 +48,0 @@ ),

@@ -17,4 +17,7 @@ 'use strict';

buildIndex({ data, outputDir: OUTPUT_DIR });
data.filter((item) => item.kind === 'class')
.forEach((item) => buildClass({ data, name: item.name, outputDir: OUTPUT_DIR }));
data
.filter((item) => item.kind === 'class')
.forEach((item) =>
buildClass({ data, name: item.name, outputDir: OUTPUT_DIR })
);
buildTypedefs({ data, outputDir: OUTPUT_DIR });

@@ -6,6 +6,5 @@ 'use strict';

factory.define('audience')
.attrs({
clientId: () => faker.internet.password(),
host: () => faker.internet.url()
});
factory.define('audience').attrs({
clientId: () => faker.internet.password(),
host: () => faker.internet.url()
});

@@ -7,3 +7,4 @@ 'use strict';

factory.define('facility')
factory
.define('facility')
.option('fromServer', false)

@@ -31,12 +32,19 @@ .sequence('id')

.attr('facility_groupings', ['id', 'fromServer'], (id, fromServer) => {
return times(faker.random.number({
min: 0,
max: 5
}), () => {
return factory.build('facilityGrouping', {
facilityId: id
}, {
fromServer
});
});
return times(
faker.random.number({
min: 0,
max: 5
}),
() => {
return factory.build(
'facilityGrouping',
{
facilityId: id
},
{
fromServer
}
);
}
);
})

@@ -51,12 +59,19 @@ .attr('name', ['city'], (city) => `${faker.address.cityPrefix()} ${city}`)

.attr('tags', ['id', 'fromServer'], (id, fromServer) => {
return times(faker.random.number({
min: 0,
max: 5
}), () => {
return factory.build('facilityTag', {
facilityId: id
}, {
fromServer
});
});
return times(
faker.random.number({
min: 0,
max: 5
}),
() => {
return factory.build(
'facilityTag',
{
facilityId: id
},
{
fromServer
}
);
}
);
})

@@ -63,0 +78,0 @@ .after((facility, options) => {

@@ -6,3 +6,4 @@ 'use strict';

factory.define('facilityGrouping')
factory
.define('facilityGrouping')
.option('fromServer', false)

@@ -9,0 +10,0 @@ .attrs({

@@ -6,3 +6,4 @@ 'use strict';

factory.define('facilityGroupingFacility')
factory
.define('facilityGroupingFacility')
.option('fromServer', false)

@@ -23,6 +24,8 @@ .attrs({

facilityGroupingFacility.facility_grouping_id = facilityGroupingFacility.facilityGroupingId;
facilityGroupingFacility.facility_grouping_id =
facilityGroupingFacility.facilityGroupingId;
delete facilityGroupingFacility.facilityGroupingId;
facilityGroupingFacility.facility_id = facilityGroupingFacility.facilityId;
facilityGroupingFacility.facility_id =
facilityGroupingFacility.facilityId;
delete facilityGroupingFacility.facilityId;

@@ -29,0 +32,0 @@

@@ -6,9 +6,8 @@ 'use strict';

factory.define('facilityInfo')
.attrs({
'General Manager': () => faker.name.findName(),
latitude: () => faker.address.latitude(),
longitude: () => faker.address.longitude(),
rail_access: () => faker.random.boolean(),
square_feet: () => faker.random.number()
});
factory.define('facilityInfo').attrs({
'General Manager': () => faker.name.findName(),
latitude: () => faker.address.latitude(),
longitude: () => faker.address.longitude(),
rail_access: () => faker.random.boolean(),
square_feet: () => faker.random.number()
});

@@ -6,3 +6,4 @@ 'use strict';

factory.define('facilityTag')
factory
.define('facilityTag')
.option('fromServer', false)

@@ -9,0 +10,0 @@ .sequence('id')

@@ -6,2 +6,4 @@ 'use strict';

require('./audience');
require('./costCenter');
require('./costCenterFacility');
require('./defaultAudiences');

@@ -8,0 +10,0 @@ require('./facility');

@@ -6,3 +6,4 @@ 'use strict';

factory.define('organization')
factory
.define('organization')
.attrs({

@@ -9,0 +10,0 @@ createdAt: () => faker.date.past().toISOString(),

@@ -6,3 +6,4 @@ 'use strict';

factory.define('userProfile')
factory
.define('userProfile')
.attrs({

@@ -9,0 +10,0 @@ name: () => faker.name.findName(),

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc