function jsonAPI(anExport, aFunction) { var runkitExpress = require("@runkit/runkit/express-endpoint/1.0.0") var bodyParser = require('body-parser'); var app = runkitExpress(anExport) app.set('json spaces', 2); app.use(require('compression')()) app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); // add CORS headers, so the API is available anywhere app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Expose-Headers", "runkit-rate-limit-remaining"); res.header("Access-Control-Expose-Headers", "tonic-rate-limit-remaining"); var reqHeaders = req.get("Access-Control-Request-Headers") if (reqHeaders) res.header("Access-Control-Allow-Headers", reqHeaders); var reqMethods = req.get("Access-Control-Request-Methods") if (reqMethods) res.header("Access-Control-Allow-Methods", reqMethods); next() }) app.all('/', async function(request, response, next) { try { var requestData = { method: request.method, body: request.body, query: request.query } var responseData = await (aFunction.length === 2 ? (new Promise(function(resolve) { aFunction(requestData, resolve) })) : aFunction(requestData)) if (responseData) response.json(responseData) else response.status(201).end() } catch(anException) { response.status(500) response.json({ message: "unable to process request", error: anException.toString() }) } }) return app; } module.exports = jsonAPI;
This helper creates a simple JSON API that accepts JSON request data and returns a JSON response. It can be used two different ways, depending on the callback's signature. The incoming data is an object with three properties: - "method": the request method used - "body": the data sent in the body of the request - "query": any query parameters sent in the request If the "arity" (the number of arguments) of the provided callback function is 1, then you can return a response directly, or a promise that eventually resolves to the data. Here's an example use: If the "arity" is 2, then the second parameter is a "done" callback that you should call yourself whenever you want to return a response. You can pass the response as the only argument to the callback. Here's an example use:


  • posted 4 months ago by methradeth
    what are the arguments "anExport" and "aFunction" and where are the passed in?
  • posted 4 months ago by alphanumeric010101
    I think those are just placeholder for "aFunction" that you would write yourself. anException is, likewise, an error that you are watching for.

sign in to comment