1 | import fs from 'fs-extra'
|
2 | import path from 'path'
|
3 | import rsort from 'route-sort'
|
4 |
|
5 | import { hashContent } from './hashContent'
|
6 | import * as logger from './log'
|
7 | import { Presta } from './types'
|
8 | import { Env } from './constants'
|
9 |
|
10 | export function outputLambda(input: string, config: Presta): [string, string] {
|
11 | const { route } = require(input)
|
12 | const name = path.basename(input).split('.').reverse().slice(1).reverse().join('.')
|
13 | const output = path.join(
|
14 | config.functionsOutputDir,
|
15 | config.env === Env.PRODUCTION ? name + '-' + hashContent(fs.readFileSync(input, 'utf8')) + '.js' : name + '.js'
|
16 | )
|
17 |
|
18 | logger.debug({
|
19 | label: 'debug',
|
20 | message: `generating ${name} lambda`,
|
21 | })
|
22 |
|
23 |
|
24 | delete require.cache[input]
|
25 | delete require.cache[output]
|
26 |
|
27 | fs.outputFileSync(
|
28 | output,
|
29 | `import { wrapHandler } from 'presta';
|
30 | import * as file from '${input}';
|
31 | export const route = file.route
|
32 | export const handler = wrapHandler(file)`
|
33 | )
|
34 |
|
35 | return [route, output]
|
36 | }
|
37 |
|
38 | export function outputLambdas(inputs: string[], config: Presta) {
|
39 | const lambdas = inputs
|
40 | .map((input) => {
|
41 | try {
|
42 | return outputLambda(input, config)
|
43 | } catch (e) {
|
44 | logger.error({
|
45 | label: 'error',
|
46 | error: e as Error,
|
47 | })
|
48 | return null
|
49 | }
|
50 | })
|
51 | .filter(Boolean) as [string, string][]
|
52 |
|
53 | const sorted = rsort(lambdas.map((l) => l[0]))
|
54 | const manifest: { [route: string]: string } = {}
|
55 |
|
56 | for (const route of sorted) {
|
57 | const match = lambdas.find((l) => l[0] === route)
|
58 |
|
59 | if (match) {
|
60 | manifest[route] = match[1]
|
61 | }
|
62 | }
|
63 |
|
64 | fs.outputFileSync(config.functionsManifest, JSON.stringify(manifest))
|
65 |
|
66 | return lambdas
|
67 | }
|