-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
executable file
·95 lines (86 loc) · 2.85 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = 'test';
}
const {
Utilities: { addImgOptMiddleware, loadEnvironment }
} = require('@magento/pwa-buildpack');
const { bestPractices, createUpwardServer } = require('@magento/upward-js');
const path = require('path');
async function serve() {
const config = loadEnvironment(__dirname);
if (config.error) {
// loadEnvironment takes care of logging it
process.exit(1);
}
const stagingServerSettings = config.section('stagingServer');
process.chdir(path.join(__dirname, 'dist'));
const upwardServerOptions = Object.assign(
// defaults
{
bindLocal: true,
logUrl: true
},
config.section('upwardJs'),
stagingServerSettings, // overrides upward options
{
env: process.env,
before(app) {
addImgOptMiddleware(app, {
...config.section('imageOptimizing'),
...config.section('imageService')
});
app.use(bestPractices());
}
}
);
let envPort;
if (process.env.PORT) {
console.log(`PORT is set in environment: ${process.env.PORT}`);
envPort = process.env.PORT;
} else if (stagingServerSettings.port) {
console.log(
`STAGING_SERVER_PORT is configured: ${stagingServerSettings.port}`
);
envPort = stagingServerSettings.port;
}
if (config.isProd) {
console.log(
`NODE_ENV=production, will not attempt to use custom host or port`
);
if (envPort) {
upwardServerOptions.port = envPort;
} else {
console.log(`No port set. Binding to random open port`);
upwardServerOptions.port = 0;
}
} else {
try {
// don't require configureHost until you need to, since loading
// the devcert library can have side effects.
const {
Utilities: { configureHost }
} = require('@magento/pwa-buildpack');
const { hostname, ports, ssl } = await configureHost(
Object.assign(config.section('customOrigin'), {
dir: __dirname,
interactive: false
})
);
upwardServerOptions.host = hostname;
upwardServerOptions.https = ssl;
upwardServerOptions.port = envPort || ports.staging || 0;
} catch (e) {
console.log(
'Could not configure or access custom host. Using loopback...',
e.message
);
}
}
console.log('Launching UPWARD server\n');
await createUpwardServer(upwardServerOptions);
console.log('\nUPWARD server running.');
}
serve().catch(e => {
console.error(e.stack);
process.exit(1);
});