Skip to content

Instantly share code, notes, and snippets.

@jmfirth

jmfirth/api.js Secret

Created October 26, 2016 20:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmfirth/a202d0dc9c52c64be6e8523552e0fc4a to your computer and use it in GitHub Desktop.
Save jmfirth/a202d0dc9c52c64be6e8523552e0fc4a to your computer and use it in GitHub Desktop.
Example plugin
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