Created
July 20, 2020 21:09
-
-
Save kleneway/2b7165a9b84235b273c56d2dfb8ef99e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
const cors = require("cors"); | |
const express = require("express"); | |
const smartcar = require("smartcar"); | |
const app = express().use(cors()); | |
const port = 8000; | |
const client = new smartcar.AuthClient({ | |
clientId: process.env.CLIENT_ID, | |
clientSecret: process.env.CLIENT_SECRET, | |
redirectUri: process.env.REDIRECT_URI, | |
scope: ["required:read_vehicle_info"], | |
testMode: true | |
}); | |
// global variable to save our accessToken | |
let access; | |
app.get("/login", function (req, res) { | |
const link = client.getAuthUrl(); | |
res.redirect(link); | |
}); | |
app.get("/exchange", function (req, res) { | |
const code = req.query.code; | |
return client.exchangeCode(code).then(function (_access) { | |
// in a production app you'll want to store this in some kind of persistent storage | |
access = _access; | |
res.sendStatus(200); | |
}); | |
}); | |
app.get("/vehicle", function (req, res) { | |
return smartcar | |
.getVehicleIds(access.accessToken) | |
.then(function (data) { | |
// the list of vehicle ids | |
return data.vehicles; | |
}) | |
.then(function (vehicleIds) { | |
// instantiate the first vehicle in the vehicle id list | |
const vehicle = new smartcar.Vehicle(vehicleIds[0], access.accessToken); | |
return vehicle.info(); | |
}) | |
.then(function (info) { | |
console.log(info); | |
// { | |
// "id": "xxxxxxxxxx", | |
// "make": "TESLA", | |
// "model": "Model S", | |
// "year": 2014 | |
// } | |
res.json(info); | |
}); | |
}); | |
app.get("/battery", function (req, res) { | |
return smartcar | |
.getVehicleIds(access.accessToken) | |
.then(function (data) { | |
// the list of vehicle ids | |
return data.vehicles; | |
}) | |
.then(function (vehicleIds) { | |
// instantiate the first vehicle in the vehicle id list | |
const vehicle = new smartcar.Vehicle(vehicleIds[0], access.accessToken); | |
return vehicle.battery(); | |
}) | |
.then(function (batteryData) { | |
console.log(batteryData); | |
// { | |
// "id": "xxxxxxxxx", | |
// "make": "TESLA", | |
// "model": "Model S", | |
// "year": 2014 | |
// } | |
res.json(batteryData); | |
}); | |
}); | |
app.listen(port, () => console.log(`Listening on port ${port}`)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment