/
serverless.js
282 lines (246 loc) · 7.35 KB
/
serverless.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
import fs from 'fs'
import path from 'path'
import boxen from 'boxen'
import chalk from 'chalk'
import { config } from 'dotenv-defaults'
import execa from 'execa'
import { Listr } from 'listr2'
import prompts from 'prompts'
import terminalLink from 'terminal-link'
import { getPaths } from '../../lib'
import c from '../../lib/colors'
export const command = 'serverless'
export const aliases = ['aws serverless', 'sls']
export const description = 'Deploy to AWS via the serverless framework'
export const builder = (yargs) => {
yargs.option('stage', {
describe:
'serverless stage pass through param: https://www.serverless.com/blog/stages-and-environments',
default: 'production',
type: 'string',
})
yargs.option('sides', {
describe: 'which Side(s) to deploy',
choices: ['api', 'web'],
default: ['api', 'web'],
alias: 'side',
type: 'array',
})
yargs.option('verbose', {
describe: 'verbosity of logs',
default: true,
type: 'boolean',
})
yargs.option('pack-only', {
describe: 'Only build and pack, and dont push code up using serverless',
default: false,
type: 'boolean',
})
yargs.option('first-run', {
describe:
'Set this flag the first time you deploy, to configure your API URL on the webside',
default: false,
type: 'boolean',
})
yargs.epilogue(
`Also see the ${terminalLink(
'Redwood CLI Reference',
'https://redwoodjs.com/docs/cli-commands#deploy'
)}\n`
)
}
export const preRequisites = () => [
{
title: 'Checking if Serverless framework is installed...',
command: ['yarn serverless', ['--version']],
errorMessage: [
'Looks like Serverless is not installed.',
'Please run yarn add -W --dev serverless.',
],
},
]
export const buildCommands = ({ sides }) => {
return [
{
title: `Building ${sides.join(' & ')}...`,
command: ['yarn', ['rw', 'build', ...sides]],
},
{
title: 'Packing Functions...',
enabled: () => sides.includes('api'),
task: async () => {
// Dynamically import this function
// because its dependencies are only installed when `rw setup deploy serverless` is run
const { nftPack } = (await import('./packing/nft')).default
await nftPack()
},
},
]
}
export const deployCommands = ({ stage, sides, firstRun, packOnly }) => {
const slsStage = stage ? ['--stage', stage] : []
return sides.map((side) => {
return {
title: `Deploying ${side}....`,
task: async () => {
await execa('yarn', ['serverless', 'deploy', ...slsStage], {
cwd: path.join(getPaths().base, side),
shell: true,
stdio: 'inherit',
cleanup: true,
})
},
skip: () => {
if (firstRun && side === 'web') {
return 'Skipping web deploy, until environment configured'
}
if (packOnly) {
return 'Finishing early due to --pack-only flag. Your Redwood project is packaged and ready to deploy'
}
},
}
})
}
const loadDotEnvForStage = (dotEnvPath) => {
// Make sure we use the correct .env based on the stage
config({
path: dotEnvPath,
defaults: path.join(getPaths().base, '.env.defaults'),
encoding: 'utf8',
})
}
export const handler = async (yargs) => {
const rwjsPaths = getPaths()
const dotEnvPath = path.join(rwjsPaths.base, `.env.${yargs.stage}`)
// Make sure .env.staging, .env.production, etc are loaded based on the --stage flag
loadDotEnvForStage(dotEnvPath)
const tasks = new Listr(
[
...preRequisites(yargs).map(mapCommandsToListr),
...buildCommands(yargs).map(mapCommandsToListr),
...deployCommands(yargs).map(mapCommandsToListr),
],
{
exitOnError: true,
renderer: yargs.verbose && 'verbose',
}
)
try {
await tasks.run()
if (yargs.firstRun) {
const SETUP_MARKER = chalk.bgBlue(chalk.black('First Setup '))
console.log()
console.log(SETUP_MARKER, c.green('Starting first setup wizard...'))
const { stdout: slsInfo } = await execa(
`yarn serverless info --verbose --stage=${yargs.stage}`,
{
shell: true,
cwd: getPaths().api.base,
}
)
const deployedApiUrl = slsInfo.match(/HttpApiUrl: (https:\/\/.*)/)[1]
console.log()
console.log(SETUP_MARKER, `Found ${c.green(deployedApiUrl)}`)
console.log()
const { addDotEnv } = await prompts({
type: 'confirm',
name: 'addDotEnv',
message: `Add API_URL to your .env.${yargs.stage}? This will be used if you deploy the web side from your machine`,
})
if (addDotEnv) {
fs.writeFileSync(dotEnvPath, `API_URL=${deployedApiUrl}`)
// Reload dotenv, after adding the new file
loadDotEnvForStage(dotEnvPath)
}
if (yargs.sides.includes('web')) {
console.log()
console.log(SETUP_MARKER, 'Deploying web side with updated API_URL')
console.log(
SETUP_MARKER,
'First deploys can take a good few minutes...'
)
console.log()
const webDeployTasks = new Listr(
[
// Rebuild web with the new API_URL
...buildCommands({ ...yargs, sides: ['web'], firstRun: false }).map(
mapCommandsToListr
),
...deployCommands({
...yargs,
sides: ['web'],
firstRun: false,
}).map(mapCommandsToListr),
],
{
exitOnError: true,
renderer: yargs.verbose && 'verbose',
}
)
// Deploy the web side now that the API_URL has been configured
await webDeployTasks.run()
const { stdout: slsInfo } = await execa(
`yarn serverless info --verbose --stage=${yargs.stage}`,
{
shell: true,
cwd: getPaths().web.base,
}
)
const deployedWebUrl = slsInfo.match(/url: (https:\/\/.*)/)[1]
const message = [
c.bold('Successful first deploy!'),
'',
`View your deployed site at: ${c.green(deployedWebUrl)}`,
'',
'You can use serverless.com CI/CD by connecting/creating an app',
'To do this run `yarn serverless` on each of the sides, and connect your account',
'',
'Find more information in our docs:',
c.underline('https://redwoodjs.com/docs/deploy#serverless'),
]
console.log(
boxen(message.join('\n'), {
padding: { top: 0, bottom: 0, right: 1, left: 1 },
margin: 1,
borderColor: 'gray',
})
)
}
}
} catch (e) {
console.error(c.error(e.message))
process.exit(e?.exitCode || 1)
}
}
const mapCommandsToListr = ({
title,
command,
task,
cwd,
errorMessage,
skip,
enabled,
}) => {
return {
title,
task: task
? task
: async () => {
try {
const executingCommand = execa(...command, {
cwd: cwd || getPaths().base,
shell: true,
})
executingCommand.stdout.pipe(process.stdout)
await executingCommand
} catch (error) {
if (errorMessage) {
error.message = error.message + '\n' + errorMessage.join(' ')
}
throw error
}
},
skip,
enabled,
}
}