Skip to content
This repository has been archived by the owner on May 29, 2021. It is now read-only.

Commit

Permalink
Convert rejects to errors, include source map in dist (#78)
Browse files Browse the repository at this point in the history
  • Loading branch information
ahmedsakr authored Jan 23, 2021
1 parent 09be74f commit 1b66535
Show file tree
Hide file tree
Showing 15 changed files with 54 additions and 48 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ You just need node.js — and npm, obviously.

### Dependencies

The dependency list is tiny — **node-fetch** and **http-status**. They will be automatically installed when you install `wstrade-api` through `npm`.
The dependency list is tiny — **node-fetch**, **http-status**, and **source-map-support**. They will be automatically installed when you install `wstrade-api` through `npm`.

### Installing

Expand Down
2 changes: 2 additions & 0 deletions dist.js

Large diffs are not rendered by default.

1 change: 0 additions & 1 deletion dist/wstrade.js

This file was deleted.

9 changes: 3 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{
"name": "wstrade-api",
"version": "1.1.4",
"version": "1.2.0",
"description": "WealthSimple Trade API Wrapper",
"main": "dist/wstrade.js",
"main": "dist.js",
"scripts": {
"bundle": "webpack",
"lint": "npx eslint --fix src/ --ignore-pattern __test__",
Expand Down Expand Up @@ -43,6 +43,7 @@
},
"dependencies": {
"http-status": "^1.4.2",
"node-fetch": "^2.6.1"
"node-fetch": "^2.6.1",
"source-map-support": "^0.5.19"
}
}
4 changes: 1 addition & 3 deletions src/api/endpoints.js
Original file line number Diff line number Diff line change
Expand Up @@ -184,9 +184,7 @@ const WealthSimpleTradeEndpoints = {
const data = await response.json();

if (data.results.length === 0) {
return Promise.reject({
reason: 'Security does not exist',
});
throw new Error('Security does not exist');
}

return data.results;
Expand Down
2 changes: 1 addition & 1 deletion src/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export default {
} catch (error) {
// we might have failed because OTP was not provided
if (!this.otp) {
return Promise.reject('OTP not provided!');
throw new Error('OTP not provided!');
}

// Seems to be incorrect credentials or OTP.
Expand Down
14 changes: 7 additions & 7 deletions src/data.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,15 @@ export default {
/**
* Information about a security on the WealthSimple Trade Platform.
*
* @param {string|object} ticker The security symbol. An exchange may be added as a suffix, separated from
* the symbol with a colon, for example: AAPL:NASDAQ, ENB:TSX
* @param {string|object} userTicker The security id
* @param {boolean} extensive Pulls a more detailed report of the security using the
* /securities/{id} API
*/
getSecurity: async (ticker, extensive) => {
getSecurity: async (userTicker, extensive) => {
let result = null;

// Run some validation on the ticker
ticker = new Ticker(ticker);
const ticker = new Ticker(userTicker);

if (!extensive && configEnabled('securities_cache')) {
result = cache.get(ticker);
Expand All @@ -45,12 +44,13 @@ export default {
}

if (result.length > 1) {
return Promise.reject({ reason: 'Multiple securities matched query.' });
throw new Error('Multiple securities matched query.');
} if (result.length === 0) {
return Promise.reject({ reason: 'No securities matched query.' });
throw new Error('No securities matched query.');
}

result = result[0];
// Convert result from a singleton list to its raw entry
[result] = result;

if (extensive) {
// The caller has opted to receive the extensive details about the security.
Expand Down
2 changes: 1 addition & 1 deletion src/helpers/__test__/time.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { epochSeconds } from '../time';
import epochSeconds from '../time';

function wait(seconds) {
return new Promise((res, rej) => setTimeout(res, seconds * 1000));
Expand Down
3 changes: 2 additions & 1 deletion src/helpers/time.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/**
* Computes the current time in epoch seconds.
*/
export const epochSeconds = () => parseInt(Date.now() / 1000, 10);
const epochSeconds = () => parseInt(Date.now() / 1000, 10);
export default epochSeconds;
2 changes: 2 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
require('source-map-support').install();

const auth = require('./auth').default;
const headers = require('./headers').default;
const accounts = require('./accounts').default;
Expand Down
34 changes: 16 additions & 18 deletions src/network/https.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,25 @@ import implicitTokenRefresh from '../optional/implicit-token-refresh';
*/
function finalizeRequest(endpoint, data) {
// Make a copy so we don't modify the original one.
data = { ...data };

const params = { ...data };
let { url } = endpoint;

// No need to do anything if the URL is static (no parameters)
if (endpoint.parameters) {
// Swap all the parameter placeholders with the arguments.
for (let index = 0; index < Object.keys(endpoint.parameters).length; index++) {
if (data[endpoint.parameters[index]] === null || data[endpoint.parameters[index]] === undefined) {
throw new Error('URL Path parameter missing');
const parameterName = endpoint.parameters[index];

// we have to explicitly check for null and undefined since parameter
// values might be 0.
if (params[parameterName] === null || params[parameterName] === undefined) {
throw new Error(`URL Path parameter '${parameterName}' missing!`);
}

url = url.replace(`{${index}}`, data[endpoint.parameters[index]]);
url = url.replace(`{${index}}`, params[endpoint.parameters[index]]);

// Must remove this key from the payload as it has been consumed by the URL
delete data[endpoint.parameters[index]];
delete params[endpoint.parameters[index]];
}
}

Expand All @@ -35,7 +38,7 @@ function finalizeRequest(endpoint, data) {
return { url, payload: undefined };
}

return { url, payload: JSON.stringify(data) };
return { url, payload: JSON.stringify(params) };
}

/*
Expand Down Expand Up @@ -74,17 +77,12 @@ async function talk(endpoint, data) {
* data.
*/
export default async function handleRequest(endpoint, data) {
try {
// Submit the HTTP request to the WealthSimple Trade Servers
const response = await talk(endpoint, data);
// Submit the HTTP request to the WealthSimple Trade Servers
const response = await talk(endpoint, data);

if ([status.OK, status.CREATED].includes(response.status)) {
return endpoint.onSuccess(response);
}

return Promise.reject(await endpoint.onFailure(response));
} catch (error) {
// This is likely a network error; throw it to the caller to deal with.
throw error;
if ([status.OK, status.CREATED].includes(response.status)) {
return endpoint.onSuccess(response);
}

return Promise.reject(await endpoint.onFailure(response));
}
6 changes: 3 additions & 3 deletions src/optional/implicit-token-refresh.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { epochSeconds } from '../helpers/time';
import epochSeconds from '../helpers/time';
import auth from '../auth';

/*
Expand All @@ -13,12 +13,12 @@ export default async function implicitTokenRefresh() {
await auth.refresh();
} catch (error) {
// The refresh token is not valid.
return Promise.reject(`Unable to refresh expired token: ${error}`);
throw new Error(`Unable to refresh expired token: ${error}`);
}
} else {
// We are forced to reject as our access token has expired and we
// do not have a refresh token.
return Promise.reject('Access token expired');
throw new Error('Access token expired');
}
}
}
4 changes: 2 additions & 2 deletions src/orders/submit.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ export default {

// The WealthSimple Trade backend doesn't check for this, even though the app does..
if (isCanadianSecurity(security.stock.primary_exchange) && stop !== limit) {
return Promise.reject({ reason: 'TSX/TSX-V securities must have an equivalent stop and limit price.' });
throw new Error('TSX/TSX-V securities must have an equivalent stop and limit price.');
}

return handleRequest(endpoints.PLACE_ORDER, {
Expand Down Expand Up @@ -149,7 +149,7 @@ export default {

// The WealthSimple Trade backend doesn't check for this, even though the app does..
if (isCanadianSecurity(security.stock.primary_exchange) && stop !== limit) {
return Promise.reject({ reason: 'TSX/TSX-V securities must have an equivalent stop and limit price.' });
throw new Error('TSX/TSX-V securities must have an equivalent stop and limit price.');
}

return handleRequest(endpoints.PLACE_ORDER, {
Expand Down
10 changes: 9 additions & 1 deletion webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ const path = require('path');
module.exports = {
target: "node",
output: {
filename: "wstrade.js",
path: process.cwd(),
filename: "dist.js",
library: "wstrade-api",
libraryTarget: "umd"
},
devtool: 'inline-source-map',
resolve: {
modules: [path.resolve(__dirname, 'src'), 'node_modules']
},
Expand All @@ -22,6 +24,12 @@ module.exports = {
commonjs2: 'http-status',
amd: 'http-status',
root: '_',
},
"source-map-support": {
commonjs: 'source-map-support',
commonjs2: 'source-map-support',
amd: 'source-map-support',
root: '_',
}
},
module: {
Expand Down

0 comments on commit 1b66535

Please sign in to comment.