@ifvictr/

DeficientSeveralProjector

Express

No description

fork
loading
Files
  • index.js
  • db.js
  • package-lock.json
  • package.json
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
'use strict'

const express = require('express')
const smartcar = require('smartcar')

const app = express()
const port = 4000

const client = new smartcar.AuthClient({
    clientId: 'SMARTCAR_CLIENT_ID',
    clientSecret: 'SMARTCAR_CLIENT_SECRET',
    redirectUri: 'YOUR_CALLBACK_URI',
    scope: ['read_vehicle_info'],
    testMode: true, // launch the Smartcar auth flow in test mode
})

let vehicle

// Redirect to Smartcar's authentication flow
app.get('/login', (req, res) => {

    const link = client.getAuthUrl()

    // redirect to the link
    res.redirect(link)
})

app.get('/unlock', (req, res) => {
    vehicle.unlock()
})

// Handle Smartcar callback with auth code
app.get('/callback', (req, res, next) => {
    let access

    if (req.query.error) {
        // the user denied your requested permissions
        return next(new Error(req.query.error))
    }

    // exchange auth code for access token
    return client.exchangeCode(req.query.code)
        .then(_access => {
            // in a production app you'll want to store this in some kind of persistent storage
            access = _access
            return smartcar.getVehicleIds(access.accessToken)
        })
        .then(res => {
            // instantiate first vehicle in vehicle list
            vehicle = new smartcar.Vehicle(res.vehicles[0], access.accessToken)
            // get identifying information about a vehicle
            return vehicle.location()
        })
        .then(data => {
            console.log(data)
            // {
            //   "id": "36ab27d0-fd9d-4455-823a-ce30af709ffc",
            //   "make": "TESLA",
            //   "model": "Model S",
            //   "year": 2014
            // }

            // json response will be sent to the user
            res.json(data)
        })
});

app.listen(port, () => console.log(`Listening on port ${port}`))