Skip to content

Instantly share code, notes, and snippets.

@chaseholdren
Created September 12, 2019 11:51
Show Gist options
  • Save chaseholdren/8c42793f3787e0b296f71304b86e4ff9 to your computer and use it in GitHub Desktop.
Save chaseholdren/8c42793f3787e0b296f71304b86e4ff9 to your computer and use it in GitHub Desktop.
ttw-time-to-work
import * as GoogleMaps from '@google/maps';
import { config } from 'dotenv';
// @ts-ignore
import { Firestore, Timestamp } from '@google-cloud/firestore';
const environment = config().parsed as {
GOOGLE_APPLICATION_CREDENTIALS: string;
MAPS_API_KEY: string;
};
const firestore = new Firestore({
projectId: 'ttw-time-to-work',
keyFilename: environment.GOOGLE_APPLICATION_CREDENTIALS,
});
const tripDurationInTrafficCollection = firestore.collection('trip-duration-in-traffic');
const googleMapsClient = GoogleMaps.createClient({
key: environment.MAPS_API_KEY,
Promise: Promise
});
const origin = '27854 Knickerbocker Road, Bay Village, OH';
const destination = '200, 3333 Richmond Road, Beachwood, OH';
const getDurationInTraffic = async (trafficModel: GoogleMaps.TrafficModel, departureTime: number) => {
const response = await googleMapsClient.distanceMatrix({
origins: [origin],
destinations: [destination],
units: 'imperial' as const,
departure_time: departureTime,
traffic_model: trafficModel,
}).asPromise();
const durationData = response.json.rows[0].elements[0].duration_in_traffic;
return {
...durationData,
trafficModel,
};
}
const recordTripDurationForEachTrafficModel = async () => {
const departureTime = Date.now();
const guessMadeAtTimestamp = Timestamp.now();
const trafficModels: GoogleMaps.TrafficModel[] = ['best_guess', 'optimistic', 'pessimistic'];
const trafficModelDurationPromises = trafficModels
.map((trafficModel) => getDurationInTraffic(trafficModel, departureTime));
const trafficModelDurations = await Promise.all(trafficModelDurationPromises);
const predictions = trafficModelDurations.reduce((aggValue, nextValue) => ({
...aggValue,
[nextValue.trafficModel]: {
value: nextValue.value,
text: nextValue.text,
}
}), {});
const doc = {
destination,
origin,
guessMadeAtTimestamp,
departureTime,
predictions,
departureTimeText: new Date(departureTime).toUTCString(),
}
console.log(JSON.stringify(doc, undefined, 2));
await tripDurationInTrafficCollection.add(doc);
console.log('Done :D');
}
const MS_IN_ONE_SECOND = 1000;
const MS_IN_ONE_MINUTE = MS_IN_ONE_SECOND * 60;
const runSafely = () => {
recordTripDurationForEachTrafficModel()
.catch(err => {
console.error(err);
});
};
runSafely();
setInterval(runSafely, MS_IN_ONE_MINUTE);
{
"name": "ttw-time-to-work",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "./node_modules/.bin/tslint -p tslint.json && ./node_modules/.bin/tsc",
"start": "npm run build && node ."
},
"keywords": [],
"author": "",
"engines": {"node": "8"},
"dependencies": {
"@firebase/app": "^0.4.14",
"@firebase/app-types": "^0.4.3",
"@firebase/database": "^0.4.12",
"@google-cloud/firestore": "^2.2.7",
"@google/maps": "^0.5.5",
"@types/dotenv": "^6.1.1",
"@types/google__maps": "^0.5.6",
"dotenv": "^8.1.0",
"firebase-admin": "^8.3.0",
"firebase-functions": "^3.2.0",
"ts-node": "^8.3.0",
"typescript": "^3.5.3"
}
}
{
"compilerOptions": {
"target": "esnext",
"esModuleInterop": true,
"lib": ["esnext", "scripthost"]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment