-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
134 lines (114 loc) · 3.37 KB
/
server.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import express from 'express'
import fetch from 'node-fetch'
import path from 'path'
import connectToDatabase from './database/database.js'
import { fileURLToPath } from 'url'
import cors from 'cors'
import Birthday from './models/Birthday.js'
import dotenv from 'dotenv'
dotenv.config()
const port = process.env.PORT || 3000
const clientId = process.env.WEPA_CLIENT_ID
const clientSecret = process.env.WEPA_CLIENT_SECRET
let bearerToken
// Fetch new token
;(async () => {
try {
bearerToken = await getAccessToken()
} catch (error) {
console.error('Error fetching initial access token', error)
}
})()
const app = express()
// Connect to database
connectToDatabase()
const __dirname = path.dirname(fileURLToPath(import.meta.url))
app.set('views', 'public')
app.use(cors())
app.use(express.static(path.join(__dirname, 'public')))
// make API call with credentials derived from earlier bearer token
// Store API response into data variable
async function getAccessToken() {
const response = await fetch('https://api.wepanow.com/oauth/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: `Basic ${Buffer.from(
`${clientId}:${clientSecret}`
).toString('base64')}`,
},
body: `grant_type=client_credentials`,
})
if (!response.ok) {
throw new Error(
`Failed to obtain access token. HTTP status: ${response.status}`
)
}
const data = await response.json()
return data.access_token
console.log(data)
}
async function fetchPrinters() {
if (!bearerToken) {
bearerToken = await getAccessToken()
}
const response = await fetch(
'https://api.wepanow.com/resources/groups/146/kiosks',
{
headers: {
Authorization: `Bearer ${bearerToken}`,
},
}
)
if (response.status === 401) {
// Token is invalid, try to refresh it
bearerToken = await getAccessToken()
// Retry the request with the new token
return fetchPrinters()
}
if (!response.ok) {
throw new Error(`Failed to fetch printers. HTTP status: ${response.status}`)
}
return response.json()
}
app.get('/', async (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'))
})
app.get('/printers', async (req, res) => {
try {
const printers = await fetchPrinters()
res.json(printers)
} catch (error) {
res.status(500).send(`Failed to fetch printers ${error}`)
}
})
app.get('/birthdays', async (req, res) => {
try {
const birthdays = await Birthday.find({})
const today = new Date()
const thisMonth = today.getMonth() + 1 // getMonth() returns 0-11
const thisDay = today.getDate()
birthdays.forEach((birthday) => {
if (
birthday.birthMonth > thisMonth ||
(birthday.birthMonth === thisMonth && birthday.birthDay >= thisDay)
) {
// Birthday is later this year
birthday.distance =
(birthday.birthMonth - thisMonth) * 30 + (birthday.birthDay - thisDay)
} else {
// Birthday is next year
birthday.distance =
(12 - thisMonth + birthday.birthMonth) * 30 +
(birthday.birthDay - thisDay)
}
})
birthdays.sort((a, b) => a.distance - b.distance)
res.json(birthdays.slice(0, 5))
} catch (error) {
res.status(500).send('Error fetching birthdays')
}
})
app.listen(port, () => {
console.log(`Server listening on port:${port}`)
})