forked from gothinkster/realworld-starter-kit
-
Notifications
You must be signed in to change notification settings - Fork 3
/
configure.js
63 lines (52 loc) · 1.6 KB
/
configure.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
/* eslint-disable import/no-named-as-default-member */
import fs from "fs";
import path from "path";
import bcrypt from "bcrypt";
import findFreePort from "find-free-port";
import url from "url";
import crypto from "crypto";
import readline from "readline";
const __dirname = path.dirname(url.fileURLToPath(import.meta.url));
export async function go() {
const prod = process.env.NODE_ENV === "production";
const HOST = process.env.HOST || (prod ? "0.0.0.0" : "localhost");
const PORT = prod
? await findFreePort(3000)
: process.env.PORT || (await findFreePort(3000));
const DATABASE_URL = process.env.DATABASE_URL || (await getDbFileName());
const SERVER_SECRET =
process.env.SERVER_SECRET || crypto.randomBytes(48).toString("hex");
const SALT_ROUNDS =
process.env.SALT_ROUNDS || (prod ? calculateSaltRounds() : "8");
let output = `HOST=${HOST}
PORT=${PORT}
DATABASE_URL=${DATABASE_URL}
SERVER_SECRET=${SERVER_SECRET}
SALT_ROUNDS=${SALT_ROUNDS}
`;
if (prod) output += "TRUST_FORWARDED_ORIGIN=1";
await fs.promises.writeFile(".env", output, { encoding: "utf-8" });
}
function calculateSaltRounds() {
let rounds;
for (rounds = 8; rounds < 30; ++rounds) {
const start = process.hrtime();
bcrypt.hashSync("topsecret", rounds);
const elapsed = process.hrtime(start)[1] / 1_000_000;
if (elapsed >= 250) break;
}
return rounds;
}
async function getDbFileName() {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise((resolve) => {
rl.question("Database connection URL? ", (answer) => {
resolve(answer);
rl.close();
});
});
}
go();