Skip to content

Commit

Permalink
use custom date reviver for date objects
Browse files Browse the repository at this point in the history
  • Loading branch information
felipecsl committed Dec 12, 2023
1 parent d74b007 commit 39e74ae
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 4 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "tda-wsjson-client",
"version": "0.10.1",
"version": "0.10.2",
"description": "WebSocket client for the TD Ameritrade wsjson API",
"main": "dist/web.bundle.js",
"types": "dist/web.d.ts",
Expand Down
15 changes: 14 additions & 1 deletion src/client/wsJsonClientProxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,9 @@ export default class WsJsonClientProxy implements WsJsonClient {
const { buffer, socket } = this;
return new Promise((resolve, reject) => {
socket.onmessage = ({ data }) => {
buffer.emit(JSON.parse(data as string) as ProxiedResponse);
// make sure date objects are reconstructed across the wire
const parsedMsg = JSON.parse(data as string, dateReviver);
buffer.emit(parsedMsg as ProxiedResponse);
};
socket.onopen = () => {
logger("proxy ws connection opened");
Expand Down Expand Up @@ -271,3 +273,14 @@ export default class WsJsonClientProxy implements WsJsonClient {
.map(({ response }) => response as T);
}
}

function dateReviver(_: string, value: any): any {
if (typeof value === "string") {
// Regular expression to check if the string matches ISO 8601 date format
const isoDateRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$/;
if (isoDateRegex.test(value)) {
return new Date(value);
}
}
return value; // return the value unchanged if not a date string
}
5 changes: 3 additions & 2 deletions src/example/testApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,9 +177,10 @@ async function run() {
const { client } = await authClient.authenticateWithRetry(token);
const app = new TestApp(client);
await Promise.all([
app.quotes(["ABNB", "UBER"]),
app.accountPositions(),
// app.quotes(["ABNB", "UBER"]),
// app.accountPositions(),
app.optionChain("TSLA"),
// app.optionChainQuotes("AAPL"),
]);
}

Expand Down

0 comments on commit 39e74ae

Please sign in to comment.