Skip to content

Commit

Permalink
Merge pull request #196 from radarlabs/token-handling
Browse files Browse the repository at this point in the history
avoid double request, add clearVerifiedLocationToken()
  • Loading branch information
nickpatrick authored Jan 22, 2025
2 parents c9dd389 + 2f99d42 commit 94819cb
Show file tree
Hide file tree
Showing 10 changed files with 65 additions and 75 deletions.
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ Radar.initialize('prj_test_pk_...', { /* options */ });
Add the following script in your `html` file
```html
<script src="https://js.radar.com/v4.4.9/radar.min.js"></script>
<script src="https://js.radar.com/v4.4.10/radar.min.js"></script>
```

Then initialize the Radar SDK
Expand All @@ -73,8 +73,8 @@ To create a map, first initialize the Radar SDK with your publishable key. Then
```html
<html>
<head>
<link href="https://js.radar.com/v4.4.9/radar.css" rel="stylesheet">
<script src="https://js.radar.com/v4.4.9/radar.min.js"></script>
<link href="https://js.radar.com/v4.4.10/radar.css" rel="stylesheet">
<script src="https://js.radar.com/v4.4.10/radar.min.js"></script>
</head>

<body>
Expand All @@ -98,8 +98,8 @@ To create an autocomplete input, first initialize the Radar SDK with your publis
```html
<html>
<head>
<link href="https://js.radar.com/v4.4.9/radar.css" rel="stylesheet">
<script src="https://js.radar.com/v4.4.9/radar.min.js"></script>
<link href="https://js.radar.com/v4.4.10/radar.css" rel="stylesheet">
<script src="https://js.radar.com/v4.4.10/radar.min.js"></script>
</head>

<body>
Expand Down Expand Up @@ -130,8 +130,8 @@ To power [geofencing](https://radar.com/documentation/geofencing/overview) exper
```html
<html>
<head>
<link href="https://js.radar.com/v4.4.9/radar.css" rel="stylesheet">
<script src="https://js.radar.com/v4.4.9/radar.min.js"></script>
<link href="https://js.radar.com/v4.4.10/radar.css" rel="stylesheet">
<script src="https://js.radar.com/v4.4.10/radar.min.js"></script>
</head>

<body>
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

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

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "radar-sdk-js",
"version": "4.4.9",
"version": "4.4.10",
"description": "Web Javascript SDK for Radar, location infrastructure for mobile and web apps.",
"homepage": "https://radar.com",
"type": "module",
Expand Down
8 changes: 6 additions & 2 deletions src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,17 +135,21 @@ class Radar {
}

public static startTrackingVerified(params: RadarStartTrackingVerifiedParams) {
return VerifyAPI.startTrackingVerified(params);
VerifyAPI.startTrackingVerified(params);
}

public static stopTrackingVerified() {
return VerifyAPI.stopTrackingVerified();
VerifyAPI.stopTrackingVerified();
}

public static getVerifiedLocationToken(params: RadarTrackVerifiedParams = {}) {
return VerifyAPI.getVerifiedLocationToken(params);
}

public static clearVerifiedLocationToken() {
VerifyAPI.clearVerifiedLocationToken();
}

public static setExpectedJurisdiction(countryCode?: string, stateCode?: string) {
VerifyAPI.setExpectedJurisdiction(countryCode, stateCode);
}
Expand Down
34 changes: 0 additions & 34 deletions src/api/track.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,6 @@ class TrackAPI {
let response: any;
if (fraud) {
const host = 'https://api-verified.radar.io';
const pingHost = 'ping.radar-verify.com';

const lang = navigator.language;
const langs = navigator.languages;
Expand All @@ -109,31 +108,9 @@ class TrackAPI {
},
});

let sclVal = -1;
let cslVal = -1;
/*
try {
const [sclRes, csl] = await Promise.all([
Http.request({
host: `https://${pingHost}`,
method: 'GET',
path: 'ping',
}),
ping(`wss://${pingHost}`),
]);
const { scl }: any = sclRes;
sclVal = scl;
cslVal = csl;
} catch (err) {
// do nothing, send scl = -1 and csl = -1
}
*/

const payload = {
payload: JSON.stringify({
...body,
scl: sclVal,
csl: cslVal,
lang,
langs,
}),
Expand All @@ -153,17 +130,6 @@ class TrackAPI {
},
});

if (options.debug && response && response.user) {
if (!response.user.metadata) {
response.user.metadata = {};
}

response.user.metadata['radar:debug'] = {
sclVal,
cslVal,
};
}

let { user, events, token, expiresAt, expiresIn, passed, failureReasons, _id } = response;
const location = { latitude, longitude, accuracy };
if (expiresAt) {
Expand Down
64 changes: 40 additions & 24 deletions src/api/verify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,31 +114,23 @@ class VerifyAPI {
return trackRes;
}

static async startTrackingVerified(params: RadarStartTrackingVerifiedParams) {
const doTrackVerified = async () => {
let trackRes;
try {
trackRes = await this.trackVerified(params);
} catch (err: any) {
Logger.error(`trackVerified error: ${err.message}`);
}

static startTrackingVerified(params: RadarStartTrackingVerifiedParams) {
const scheduleNextIntervalWithLastToken = async () => {
const { interval } = params;

let expiresIn = 0;
let minInterval = interval;

if (trackRes) {
expiresIn = (trackRes.expiresIn || expiresIn);
if (lastToken) {
const lastTokenElapsed = (performance.now() - lastTokenNow) / 1000;

const expiresIn = (lastToken.expiresIn || 0);

// if expiresIn is shorter than interval, override interval
minInterval = Math.min(expiresIn, interval);
// re-request early to maximize the likelihood that a cached token is available
minInterval = Math.min(expiresIn - lastTokenElapsed, interval);
}

// re-request early to maximize the likelihood that a cached token is available
if (minInterval > 20) {
minInterval = minInterval - 10;
}
minInterval = minInterval - 10;

// min interval is 10 seconds
if (minInterval < 10) {
Expand All @@ -150,9 +142,23 @@ class VerifyAPI {
}

tokenTimeoutId = setTimeout(doTrackVerified, minInterval * 1000);
}

const doTrackVerified = async () => {
try {
await this.trackVerified(params);
} catch (err: any) {
Logger.error(`trackVerified error: ${err.message}`);
}

scheduleNextIntervalWithLastToken();
};

doTrackVerified();
if (this.isLastTokenValid()) {
scheduleNextIntervalWithLastToken();
} else {
doTrackVerified();
}
}

static stopTrackingVerified() {
Expand All @@ -162,17 +168,27 @@ class VerifyAPI {
}

static async getVerifiedLocationToken(params: RadarTrackVerifiedParams) {
const lastTokenElapsed = (performance.now() - lastTokenNow) / 1000;

if (lastToken && lastToken.passed) {
if (lastTokenElapsed < (lastToken.expiresIn || 0)) {
return lastToken;
}
if (this.isLastTokenValid()) {
return lastToken;
}

return this.trackVerified(params);
}

static clearVerifiedLocationToken() {
lastToken = null;
}

static isLastTokenValid() {
if (!lastToken) {
return false;
}

const lastTokenElapsed = (performance.now() - lastTokenNow) / 1000;

return lastToken.passed && lastTokenElapsed < (lastToken.expiresIn || 0);
}

static setExpectedJurisdiction(countryCode?: string, stateCode?: string) {
expectedCountryCode = countryCode || null;
expectedStateCode = stateCode || null;
Expand Down
8 changes: 6 additions & 2 deletions src/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,12 +189,16 @@ class Http {
if (host && (host === 'http://localhost:52516' || host === 'https://radar-verify.com:52516')) {
reject(new RadarVerifyAppError());
} else {
reject(new RadarServerError());
reject(new RadarNetworkError());
}
}

xhr.ontimeout = function () {
reject(new RadarVerifyAppError());
if (host && (host === 'http://localhost:52516' || host === 'https://radar-verify.com:52516')) {
reject(new RadarVerifyAppError());
} else {
reject(new RadarNetworkError());
}
}

xhr.send(JSON.stringify(body));
Expand Down
2 changes: 1 addition & 1 deletion src/ui/RadarMap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ class RadarMap extends maplibregl.Map {
radarMapOptions,
{ style },
);
Logger.debug('map initailized with options', mapOptions);
Logger.debug('map initialized with options', mapOptions);

(mapOptions as maplibregl.MapOptions).transformRequest = (url, resourceType) => {
// this handles when a style is switched
Expand Down
2 changes: 1 addition & 1 deletion src/version.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export default '4.4.9';
export default '4.4.10';
2 changes: 1 addition & 1 deletion test/http.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ describe('Http', () => {
try {
await Http.request(httpRequestParams);
} catch (e: any) {
expect(e.status).toEqual('ERROR_SERVER');
expect(e.status).toEqual('ERROR_NETWORK');
}
});

Expand Down

0 comments on commit 94819cb

Please sign in to comment.