feat: env defaults

This commit is contained in:
Mateusz Pstrucha committed 2022-04-19 17:27:34 +02:00
1 parent 6273dd4b3b
commit 24773df6bf
10 files changed
+85 -51

No files matched your search

+4 -3
View File
@@ -1,7 +1,5 @@
import Jwt from 'jsonwebtoken'
import database from './mongo.js'
import {
timeValid,
countTrackVotes,
@@ -27,6 +25,9 @@ import Track from './Track.js'
import { broadcast as wsBroadcast } from './socket.js'
import { DbError } from './errors.js'
import env from './env.js'
const { FB_SECRET } = env
/**
* Get Track placement in Top
@@ -165,7 +166,7 @@ const db = {
*/
verifyJwt: (jwt) => {
return new Promise((resolve, reject) => {
Jwt.verify(jwt ?? '', process.env.FB_SECRET, (err, decoded) => {
Jwt.verify(jwt ?? '', FB_SECRET, (err, decoded) => {
if (err) return reject(err)
resolve(decoded)
})
+35 -5
View File
@@ -1,15 +1,45 @@
import dotenv from 'dotenv'
const env = process.env.NODE_ENV,
const NODE_ENV = process.env.NODE_ENV,
dotfile = {
production: '.env',
development: '.env.dev',
}[env ?? 'production']
development: '.dev.env',
}[NODE_ENV ?? 'production']
console.info(`env: ${env}`)
console.info(`env: ${NODE_ENV}`)
const config = dotenv.config({ path: `./${dotfile}` })
if (config.error) throw `enviroment file ${dotfile} not found`
export default config
const env = {
HTTP_PORT: -1,
HTTP_DOMAIN: '',
WS_PORT: -1,
SPOTIFY_CLIENT_ID: '',
SPOTIFY_CLIENT_SECRET: '',
DB_HOST: '',
DB_PORT: 27017,
DB_AUTH: 'admin',
DB_NAME: '',
DB_USER: '',
DB_PASS: '',
PLAYER_SECRET: '',
TOP_TIME_VALID: 'period',
TOP_TIME_VALUE: 604800,
FB_APPID: '',
FB_SECRET: '',
CACHE_HOST: '',
CACHE_PORT: 6379,
}
for (let key in env) {
process.env[key] && (env[key] = env[key].constructor(process.env[key]))
}
export default env
+16 -5
View File
@@ -4,7 +4,6 @@ import express, { json, urlencoded } from 'express'
import cookieParser from 'cookie-parser'
import { createServer } from 'http'
import { broadcast } from './socket.js'
import db from './db.js'
import track from './routes/track.js'
@@ -15,13 +14,25 @@ import player from './routes/player.js'
import admin from './routes/admin.js'
import code from './routes/code.js'
import database from './mongo.js'
const { HTTP_PORT } = env
database.on('error', (err) => {
throw err
})
database.once('open', () => {
console.info(`mongo: connected`)
})
var app = express(),
http = createServer(app)
app.use(json())
app.use(urlencoded({ extended: false }))
app.use(cookieParser())
app.set('port', process.env.HTTP_PORT)
app.set('port', HTTP_PORT)
app.use('/track', track)
app.use('/search', search)
@@ -31,18 +42,18 @@ app.use('/player', player)
app.use('/admin', admin)
app.use('/code', code)
http.listen(process.env.HTTP_PORT)
http.listen(HTTP_PORT)
http.on('error', function (error) {
if (error.syscall !== 'listen') {
throw error
}
console.info(`Error: port ${process.env.HTTP_PORT}: ${error.code}`)
console.info(`Error: port ${HTTP_PORT}: ${error.code}`)
})
http.on('listening', function () {
console.info(`http: listening on ${process.env.HTTP_PORT}`)
console.info(`http: listening on ${HTTP_PORT}`)
})
setInterval(() => {
+6 -20
View File
@@ -1,31 +1,17 @@
import env from './env.js'
import mongoose from 'mongoose'
const {
DB_HOST,
DB_PORT,
DB_NAME,
dbAuth = 'admin',
DB_USER,
DB_PASS,
} = process.env
const { DB_HOST, DB_PORT, DB_NAME, DB_AUTH, DB_USER, DB_PASS } = env
mongoose.connect(`mongodb://${DB_HOST}:${DB_PORT}/${DB_NAME}`, {
user: DB_USER,
pass: DB_PASS,
authSource: dbAuth,
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
authSource: DB_AUTH,
// useNewUrlParser: true,
// useUnifiedTopology: true,
// useFindAndModify: false,
})
const database = mongoose.connection
database.on('error', (err) => {
throw err
})
database.once('open', () => {
console.info(`mongo: connected`)
})
export default database
+6 -3
View File
@@ -1,16 +1,19 @@
import env from '../env.js'
import Vote from '../models/Vote.js'
const { TOP_TIME_VALID, TOP_TIME_VALUE } = env
/**
* Date range for valid tracks.
* Oldest a vote can be
* @type Date
*/
const timeValid = (set) => {
switch (process.env.TOP_TIME_VALID) {
switch (TOP_TIME_VALID) {
default:
case 'period': // constant period
let now = set ?? new Date(),
period = process.env.TOP_TIME_VALUE
period = TOP_TIME_VALUE
if (now.getDay() == 1) {
let saturday = new Date(new Date().setDate(now.getDate() - 2))
@@ -30,7 +33,7 @@ const timeValid = (set) => {
return monday
case 'date': // fixed date
let date = new Date(...JSON.parse(process.env.TOP_TIME_VALUE))
let date = new Date(...JSON.parse(TOP_TIME_VALUE))
return date
}
}
+3 -3
View File
@@ -1,9 +1,9 @@
import redis from 'redis'
import env from './env.js'
const port = process.env.CACHE_PORT
const hostName = process.env.CACHE_HOST
const { CACHE_PORT: port, CACHE_HOST: host } = env
const client = redis.createClient({ host: hostName, port })
const client = redis.createClient({ host, port })
client.on('ready', function (error) {
console.info(`cache: connected`)
+4 -5
View File
@@ -2,12 +2,11 @@ import express from 'express'
import got from 'got'
import Jwt from 'jsonwebtoken'
import db from '../db.js'
import env from '../env.js'
const router = express.Router()
const appId = process.env.FB_APPID,
secret = process.env.FB_SECRET,
domain = process.env.HTTP_DOMAIN
const { FB_APPID, FB_SECRET, HTTP_DOMAIN } = env
router.get('/token', ({ query: { code } }, res) => {
if (code === undefined) return res.status(400).end('Facebook code required')
@@ -15,7 +14,7 @@ router.get('/token', ({ query: { code } }, res) => {
return res.status(400).end('Facebook code needs to be of non zero length')
got(
`https://graph.facebook.com/v12.0/oauth/access_token?client_id=${appId}&redirect_uri=https://${domain}/api/login/token&client_secret=${secret}&code=${code}`
`https://graph.facebook.com/v12.0/oauth/access_token?client_id=${FB_APPID}&redirect_uri=https://${HTTP_DOMAIN}/api/login/token&client_secret=${FB_SECRET}&code=${code}`
)
.json()
.then(({ access_token, expires_in }) => {
@@ -42,7 +41,7 @@ router.get('/token', ({ query: { code } }, res) => {
id,
perms,
},
jwt = Jwt.sign(payload, secret)
jwt = Jwt.sign(payload, FB_SECRET)
res.end(
[
+4 -1
View File
@@ -1,8 +1,11 @@
import express from 'express'
import db, { parseTop } from '../db.js'
import env from '../env.js'
import { countAllVotes } from '../mongo/votes.js'
const { PLAYER_SECRET } = env
const router = express.Router()
function update(data) {
@@ -11,7 +14,7 @@ function update(data) {
db.current.update(data)
}
const playerSecret = 'Bearer ' + process.env.PLAYER_SECRET
const playerSecret = 'Bearer ' + PLAYER_SECRET
// set current track
router.put(
+3 -2
View File
@@ -1,8 +1,9 @@
import WebSocket, { WebSocketServer } from 'ws'
import db from './db.js'
import env from './env.js'
const port = process.env.WS_PORT,
wss = new WebSocketServer({ port: port })
const { WS_PORT: port } = env,
wss = new WebSocketServer({ port })
console.info('ws: listening on ' + port)
+4 -4
View File
@@ -1,11 +1,11 @@
import SpotifyWebApi from 'spotify-web-api-node'
import env from './env.js'
import Track from './Track.js'
const spotify = new SpotifyWebApi({
clientId: process.env.SPOTIFY_CLIENT_ID,
clientSecret: process.env.SPOTIFY_CLIENT_SECRET,
})
const { SPOTIFY_CLIENT_ID: clientId, SPOTIFY_CLIENT_SECRET: clientSecret } = env
const spotify = new SpotifyWebApi({ clientId, clientSecret })
function grantToken() {
spotify