Skip to content

Commit

Permalink
expose trackVerified() (#107)
Browse files Browse the repository at this point in the history
* expose trackVerified()

* update verify call

* fix location parsing

* add desktop app error

* remove config fallback

* address feedback

* include port in desktop app check
  • Loading branch information
nickpatrick authored Jul 31, 2023
1 parent 029a6c7 commit a21c72a
Show file tree
Hide file tree
Showing 7 changed files with 240 additions and 5 deletions.
1 change: 1 addition & 0 deletions demo/views/layouts/main.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
<div class="collapse show" id="home-collapse">
<ul class="btn-toggle-nav list-unstyled fw-normal pb-1 small">
<li><a href="./track-a-user" class="link-dark rounded">Track a user</a></li>
<li><a href="./track-verified" class="link-dark rounded">Track verified</a></li>
<li><a href="./start-a-trip" class="link-dark rounded">Start a trip</a></li>
<li><a href="./log-a-conversion" class="link-dark rounded">Log a conversion</a></li>
<li class="border-top my-3"></li>
Expand Down
138 changes: 138 additions & 0 deletions demo/views/track-verified.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
<div class="content flex-grow-1 p-4">
<h1 class="mb-4">Track verified</h1>
<div id="error-alert" class="alert alert-danger fade show" role="alert" style="display: none;">
<strong>Error:</strong> <span id="error-text">Something went wrong. Check the developer console for details.</span>
</div>

<p>Use the Radar Verify app to verify the user's current location.</p>

<div class="mt-5 mb-3 form-row">
<label for="user-id" class="col-form-label" style="width: 128px;">User ID</label>
<div>
<input type="text" class="form-control" id="user-id" value="test-user-id" style="width: 250px;">
</div>
</div>

<div>
<button id="track-verified" type="button" class="btn btn-primary" disabled>Call track verified</button>
</div>

<div id="loader" class="spinner-border text-primary mt-4" role="status" style="display: none;">
</div>

<div>
<div id="map" class="mt-4" style="width: 100%; height: 500px; display: none;"></div>
</div>

<div id="response-details" style="display: none;">
<h6 class="mt-4">Location</h6>
<div class="mt-2">
<pre><code id="location" class="code-sample language-json"></code><pre>
</div>

<h6 class="mt-2">User</h6>
<div class="mt-2">
<pre><code id="user" class="code-sample language-json"></code><pre>
</div>

<h6 class="mt-2">Events</h6>
<div class="mt-2">
<pre><code id="events" class="code-sample language-json"></code><pre>
</div>
</div>

<div class="mt-4">
<pre><code class="code-sample language-html">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta charset="utf-8" /&gt;
&lt;meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" /&gt;
&lt;link href="https://js.radar.com/v{{sdk_version}}/radar.css" rel="stylesheet"&gt;
&lt;script src="https://js.radar.com/v{{sdk_version}}/radar.min.js"&gt;&lt;/script&gt;
&lt;/head&gt;

&lt;body&gt;
&lt;div id="map" style="width: 100%; height: 500px;" /&gt;

&lt;script&gt;
$('#track-verified').click(() =&gt; {
Radar.initialize('&lt;RADAR_PUBLISHABLE_KEY&gt;');

Radar.trackVerified({ userId: 'test-user-id' })
.then(({ location, user, events }) =&gt; {
console.log(location);
console.log(user);
console.log(events);
});
});
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</code>
</pre>
</div>
</div>

<script>
$('#publishableKey').on('change', () => {
const publishableKey = $('#publishableKey').val();
if (publishableKey) {
$('#track-verified').prop('disabled', false);
}
});
let map;
$('#track-verified').click(() => {
$('#error-alert').hide();
$('#response-details').hide();
const publishableKey = $('#publishableKey').val();
Radar.initialize(publishableKey, { debug: true });
$('#loader').show();
const userId = $('#user-id').val();
Radar.trackVerified({ userId })
.then(({ location, user, events }) => {
console.log('TRACK RESPONSE', { location, user, events });
$('#loader').hide();
console.log(location);
console.log(user);
console.log(events);
$('#map').show();
if (!map) {
map = Radar.ui.map({
container: 'map',
});
}
map.setCenter([location.longitude, location.latitude]);
if (map.getZoom() < 14) {
map.setZoom(14);
}
const html = `
<p>${user.userId}</p>
<p>${location.latitude},${location.longitude}</p>
`.trim();
const marker = Radar.ui.marker({ html })
.setLngLat([location.longitude, location.latitude])
.addTo(map);
$('#response-details').show();
$('#location').html(JSON.stringify(location, null, 2));
$('#user').html(JSON.stringify(user, null, 2));
$('#events').html(JSON.stringify(events, null, 2));
hljs.highlightAll();
})
.catch((err) => {
console.error(err);
$('#loader').hide();
$('#error-alert').show();
$('#error-text').html(err.message);
});
});
</script>
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.

76 changes: 76 additions & 0 deletions src/api/verify.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import SDK_VERSION from '../version';
import Config from '../config';
import Device from '../device';
import Http from '../http';
import Logger from '../logger';
import Session from '../session';
import Storage from '../storage';

import type { RadarTrackParams, RadarTrackResponse } from '../types';

class VerifyAPI {
static async trackVerified(params: RadarTrackParams) {
const options = Config.get();

// user indentification fields
const userId = params.userId || Storage.getItem(Storage.USER_ID);
const deviceId = params.deviceId || Device.getDeviceId();
const installId = params.installId || Device.getInstallId();
const sessionId = Session.getSessionId();
const description = params.description || Storage.getItem(Storage.DESCRIPTION);

// save userId
if (!userId) {
Logger.warn('userId not provided for trackVerified.');
} else {
Storage.setItem(Storage.USER_ID, userId);
}

// other info
const metadata = params.metadata || Storage.getJSON(Storage.METADATA);

const body = {
...params,
description,
deviceId,
foreground: true,
installId,
sessionId,
metadata,
sdkVersion: SDK_VERSION,
stopped: true,
userId,
};

const response: any = await Http.request({
method: 'GET',
path: 'verify',
data: body,
host: 'http://localhost:52516',
});

const { user, events } = response;
let location;
if (user.location && user.location.coordinates && user.locationAccuracy) {
location = {
latitude: user.location.coordinates[1],
longitude: user.location.coordinates[0],
accuracy: user.locationAccuracy,
};
}

const trackRes = {
user,
events,
location,
} as RadarTrackResponse;

if (options.debug) {
trackRes.response = response;
}

return trackRes;
}
}

export default VerifyAPI;
8 changes: 8 additions & 0 deletions src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,14 @@ export class RadarLocationPermissionsError extends RadarError {
}
}

export class RadarDesktopAppError extends RadarError {
constructor() {
super('Desktop app not running.');
this.name = 'RadarDesktopAppError';
this.status = 'ERROR_DESKTOP_APP';
}
}

// HTTP Errors
export class RadarBadRequestError extends RadarError {
code: number;
Expand Down
13 changes: 10 additions & 3 deletions src/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import Logger from './logger';

import {
RadarBadRequestError,
RadarDesktopAppError,
RadarForbiddenError,
RadarNotFoundError,
RadarPaymentRequiredError,
Expand All @@ -27,10 +28,12 @@ class Http {
method,
path,
data,
host,
}: {
method: HttpMethod;
path: string;
data?: any;
host?: string;
}) {
return new Promise<HttpResponse>((resolve, reject) => {
const options = Config.get();
Expand All @@ -43,9 +46,9 @@ class Http {
}

// setup request URL
const host = options.host;
const urlHost = host || options.host;
const version = options.version;
let url = `${host}/${version}/${path}`;
let url = `${urlHost}/${version}/${path}`;

// remove undefined values from request data
let body: any = {};
Expand Down Expand Up @@ -129,7 +132,11 @@ class Http {
}

xhr.onerror = function() {
reject(new RadarServerError());
if (host && host.includes('localhost:52516')) {
reject(new RadarDesktopAppError());
} else {
reject(new RadarServerError());
}
}

xhr.ontimeout = function() {
Expand Down
5 changes: 5 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import RoutingAPI from './api/routing';
import SearchAPI from './api/search';
import TrackAPI from './api/track';
import TripsAPI from './api/trips';
import VerifyAPI from './api/verify';

import MapUI from './ui/map';
import AutocompleteUI from './ui/autocomplete';
Expand Down Expand Up @@ -143,6 +144,10 @@ class Radar {
}
}

public static trackVerified(params: RadarTrackParams = {}) {
return VerifyAPI.trackVerified(params);
}

public static getContext(params: Location) {
return ContextAPI.getContext(params);
}
Expand Down

0 comments on commit a21c72a

Please sign in to comment.