-
Notifications
You must be signed in to change notification settings - Fork 14
/
server.js
67 lines (59 loc) · 1.57 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
require('dotenv').config();
const express = require('express');
const fs = require('fs');
const { createTokenTokBox, createTokenNexmo } = require('./helpers/token-generator');
const API_KEY = process.env.REACT_APP_API_KEY;
const API_SECRET = process.env.API_SECRET;
const PRIVATE_KEY_PATH = process.env.PRIVATE_KEY_PATH;
const CLIENT_URL = process.env.APP_CLIENT_URL;
const PORT = process.env.SERVER_PORT || 4000;
const isTokBoxApiKey = /^-?\d+$/.test(API_KEY);
let privateKey;
/**
* Ensure all the required variables are set for the environment
*/
if (!API_KEY || !CLIENT_URL) {
console.error('You need to set your env variables before running the project.');
return;
}
if (!API_SECRET && isTokBoxApiKey) {
console.error('You need to set your secret.');
return;
}
if (!isTokBoxApiKey) {
if (!PRIVATE_KEY_PATH) {
console.error('You need to set your private key.');
return;
}
privateKey = fs.readFileSync(PRIVATE_KEY_PATH);
}
/**
* Initialize the app
*/
const app = express();
/**
* CORS Middleware - Allow the client to consume the server API
*/
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', CLIENT_URL);
next();
});
/**
* /token - Get a jwt with the configured variables
* @returns {JSON}
*/
app.get('/token', (req, res) => {
const token = isTokBoxApiKey ?
createTokenTokBox(API_KEY, API_SECRET) :
createTokenNexmo(API_KEY, privateKey);
res.send(JSON.stringify({
API_KEY,
token,
}));
});
/**
* Run the server on the specified port
*/
app.listen(PORT, () => {
console.log(`Server running on port: ${PORT}`);
});