-
-
Save jmfirth/a202d0dc9c52c64be6e8523552e0fc4a to your computer and use it in GitHub Desktop.
Example plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { join } from 'path' | |
import { parse } from 'url' | |
import requireModule from 'next/dist/server/require.js' | |
function getPath (url) { | |
return parse(url || '/').pathname | |
} | |
export default (addRoute) => { | |
addRoute('/api/:path+', async (url, { req, res, params }, { | |
dir = process.cwd(), | |
dev = false | |
} = {}) => { | |
let data = null | |
try { | |
const mod = await requireModule(join(dir, '.next', 'dist', getPath(url))) | |
const fn = mod.default | |
if (!fn) { | |
throw new Error('Endpoint is malformed; `export default function ({req, res, params}, {dir, dev}) { }`') | |
} | |
data = { | |
success: true, | |
body: fn({ req, res, params }, { dir, dev }) | |
} | |
} catch (e) { | |
data = { | |
error: true, | |
message: dev ? e.message : 'Internal server error' | |
} | |
} | |
const json = JSON.stringify(data) | |
res.setHeader('Content-Type', 'application/json') | |
res.setHeader('Content-Length', Buffer.byteLength(json)) | |
res.end(json) | |
}, 'GET') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment