From 24773df6bf022beda923bf8ae9eb8a0f49509713 Mon Sep 17 00:00:00 2001 From: Mateusz Pstrucha Date: Tue, 19 Apr 2022 17:27:34 +0200 Subject: [PATCH] feat: env defaults --- db.js | 7 ++++--- env.js | 40 +++++++++++++++++++++++++++++++++++----- index.js | 21 ++++++++++++++++----- mongo.js | 26 ++++++-------------------- mongo/votes.js | 9 ++++++--- redis.js | 6 +++--- routes/login.js | 9 ++++----- routes/player.js | 5 ++++- socket.js | 5 +++-- spotify.js | 8 ++++---- 10 files changed, 85 insertions(+), 51 deletions(-) diff --git a/db.js b/db.js index 8160150..a1611c8 100644 --- a/db.js +++ b/db.js @@ -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) }) diff --git a/env.js b/env.js index 2bf3f9e..94be9c1 100644 --- a/env.js +++ b/env.js @@ -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 diff --git a/index.js b/index.js index 545bc4b..6c6ba33 100644 --- a/index.js +++ b/index.js @@ -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(() => { diff --git a/mongo.js b/mongo.js index dd7efd6..c4c4baf 100644 --- a/mongo.js +++ b/mongo.js @@ -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 diff --git a/mongo/votes.js b/mongo/votes.js index 75cc9b9..1805fb8 100644 --- a/mongo/votes.js +++ b/mongo/votes.js @@ -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 } } diff --git a/redis.js b/redis.js index 75f4041..c2d51b6 100644 --- a/redis.js +++ b/redis.js @@ -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`) diff --git a/routes/login.js b/routes/login.js index caa8e48..e4695bb 100644 --- a/routes/login.js +++ b/routes/login.js @@ -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( [ diff --git a/routes/player.js b/routes/player.js index 6e8a616..cc7cf39 100644 --- a/routes/player.js +++ b/routes/player.js @@ -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( diff --git a/socket.js b/socket.js index c22b166..fce05e2 100644 --- a/socket.js +++ b/socket.js @@ -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) diff --git a/spotify.js b/spotify.js index 0a04783..267e95b 100644 --- a/spotify.js +++ b/spotify.js @@ -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