forked from opennextjs/opennextjs-netlify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsetupNetlifyFunctionForPage.js
47 lines (40 loc) · 1.8 KB
/
setupNetlifyFunctionForPage.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
const { copySync } = require('fs-extra')
const { join } = require('path')
const { TEMPLATES_DIR, FUNCTION_TEMPLATE_PATH } = require('../config')
const getNextDistDir = require('./getNextDistDir')
const getNetlifyFunctionName = require('./getNetlifyFunctionName')
const copyDynamicImportChunks = require('./copyDynamicImportChunks')
const { logItem } = require('./logger')
// Create a Netlify Function for the page with the given file path
const setupNetlifyFunctionForPage = async ({ filePath, functionsPath, isApiPage, publishPath }) => {
// Set function name based on file path
const functionName = getNetlifyFunctionName(filePath, isApiPage)
const functionDirectory = join(functionsPath, functionName)
if (isApiPage && functionName.endsWith('-background')) {
logItem(`👁 Setting up API page ${functionName} as a Netlify background function`)
}
// Copy function templates
const functionTemplateCopyPath = join(functionDirectory, `${functionName}.js`)
copySync(FUNCTION_TEMPLATE_PATH, functionTemplateCopyPath, {
overwrite: false,
errorOnExist: true,
})
// Copy function helpers
const functionHelpers = ['renderNextPage.js', 'createRequestObject.js', 'createResponseObject.js']
functionHelpers.forEach((helper) => {
copySync(join(TEMPLATES_DIR, helper), join(functionDirectory, helper), {
overwrite: false,
errorOnExist: true,
})
})
// Copy any dynamic import chunks
await copyDynamicImportChunks({ functionPath: functionDirectory, publishPath })
// Copy page
const nextPageCopyPath = join(functionDirectory, 'nextPage', 'index.js')
const nextDistDir = await getNextDistDir({ publishPath })
copySync(join(nextDistDir, 'serverless', filePath), nextPageCopyPath, {
overwrite: false,
errorOnExist: true,
})
}
module.exports = setupNetlifyFunctionForPage