Skip to content

Commit

Permalink
Write out manifest file so can serve functions from 'gatsby serve'
Browse files Browse the repository at this point in the history
  • Loading branch information
KyleAMathews committed Apr 14, 2021
1 parent 10226e4 commit 452cc37
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 1 deletion.
50 changes: 50 additions & 0 deletions packages/gatsby/src/commands/serve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import chalk from "chalk"
import { match as reachMatch } from "@gatsbyjs/reach-router/lib/utils"
import onExit from "signal-exit"
import report from "gatsby-cli/lib/reporter"
import multer from "multer"

import telemetry from "gatsby-telemetry"

Expand Down Expand Up @@ -110,6 +111,55 @@ module.exports = async (program: IServeProgram): Promise<void> => {
router.use(express.static(`public`, { dotfiles: `allow` }))
const matchPaths = await readMatchPaths(program)
router.use(matchPathRouter(matchPaths, { root }))

const compiledFunctionsDir = path.join(
program.directory,
`.cache`,
`functions`
)

const functionsManifest = JSON.parse(
fs.readFileSync(path.join(compiledFunctionsDir, `manifest.json`))
)

app.use(
`/api/*`,
multer().none(),
express.urlencoded({ extended: true }),
express.text(),
express.json(),
express.raw(),
async (req, res, next) => {
const { "0": functionName } = req.params

if (functionsManifest[functionName]) {
const start = Date.now()

try {
const pathToFunction = functionsManifest[functionName]
delete require.cache[require.resolve(pathToFunction)]
const fn = require(pathToFunction)

const fnToExecute = (fn && fn.default) || fn

await Promise.resolve(fnToExecute(req, res))
} catch (e) {
console.error(e)
res.sendStatus(500)
}

const end = Date.now()
console.log(
`Executed function "/api/${functionName}" in ${end - start}ms`
)

return
} else {
next()
}
}
)

router.use((req, res, next) => {
if (req.accepts(`html`)) {
return res.status(404).sendFile(`404.html`, { root })
Expand Down
20 changes: 19 additions & 1 deletion packages/gatsby/src/internal-plugins/functions/gatsby-node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,24 @@ const createWebpackConfig = async ({
"process.env": `({})`,
}
)
const compiledFunctionsDir = path.join(
siteDirectoryPath,
`.cache`,
`functions`
)

// Write out manifest for use by `gatsby serve` and plugins
const manifest = {}
Array.from(knownFunctions).forEach(([, file]) => {
const name = path.parse(file).name
const compiledPath = path.join(compiledFunctionsDir, name + `.js`)
manifest[name] = compiledPath
})

fs.writeFileSync(
path.join(compiledFunctionsDir, `manifest.json`),
JSON.stringify(manifest, null, 4)
)

const entries = {}
Array.from(knownFunctions).forEach(([, file]) => {
Expand All @@ -110,7 +128,7 @@ const createWebpackConfig = async ({
const config = {
entry: entries,
output: {
path: path.join(siteDirectoryPath, `.cache`, `functions`),
path: compiledFunctionsDir,
filename: `[name].js`,
libraryTarget: `commonjs2`,
},
Expand Down

0 comments on commit 452cc37

Please sign in to comment.