-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.mjs
71 lines (60 loc) · 1.97 KB
/
server.mjs
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
import 'isomorphic-fetch'
import path, { dirname } from 'path'
import dotenv from 'dotenv'
import express from 'express'
import cors from 'cors'
import { fileURLToPath } from 'url'
import { logInfo } from './src/Logging.mjs'
import errorHandlerMiddleware from './error_handler.mjs'
const filename = fileURLToPath(import.meta.url)
const dotEnvPath = path.resolve('./.env')
dotenv.config({ path: dotEnvPath })
const app = express()
// Cors
app.use(cors())
// Serve static files from the React app
app.use(express.static(path.join(dirname(filename), 'build')))
app.get('/api/nrel/pvwatts/hourly/:capacity/:type/:losses/:tilt/:address', (req, res, next) => {
const apiKey = process.env.NREL_API_KEY
if (!apiKey) {
throw Error('NREL_API_KEY not set')
}
logInfo('nrel/pvwatts/hourly request', req.params)
const url = new URL('https://developer.nrel.gov/api/pvwatts/v8.json')
const params = {
api_key: process.env.NREL_API_KEY,
format: 'json',
system_capacity: parseFloat(req.params.capacity),
array_type: parseInt(req.params.type, 10),
tilt: parseFloat(req.params.tilt),
module_type: 0,
azimuth: 180,
address: req.params.address,
timeframe: 'hourly',
losses: parseFloat(req.params.losses),
}
Object.keys(params).forEach((key) => url.searchParams.append(key, params[key]))
fetch(url.toString())
.then((response) => response.json())
.then((obj) => {
logInfo(obj)
return obj.outputs.ac
})
.then((result) => {
res.status(200).json(result)
})
.catch(next)
})
app.get('/api/*', () => {
throw Error('Unknown API Request')
})
// The "catchall" handler: for any request that doesn't
// match one above, send back React's index.html file.
app.get('*', (req, res) => {
logInfo('Non-API Request - ', req.url)
res.sendFile(path.join(`${dirname(filename)}/build/index.html`))
})
const port = process.env.PORT || 3001
app.use(errorHandlerMiddleware)
app.listen(port)
logInfo(`PGE-Wall API Server listening on ${port}`)