runkit's notebooks

  • JSON Endpoint Example 2 - /runkit/json-endpoint-example-2
    Last edited 7 years ago
    Send a request like ?url=http://google.com, get back the title of the page.
  • JSON Endpoint Example 1 - /runkit/json-endpoint-example-1
    Last edited 7 years ago
    Send a request to a URL like https://runkit.io/runkit/json-endpoint-example-1/branches/master?url=http://google.com, get back the title of the page in the url query parameter.
  • JSON API with Endpoint - /runkit/json-endpoint
    Last edited 7 years ago
    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;
  • Endpoint with Express - /runkit/express-endpoint
    Last edited 7 years ago
    var express = require("express"); function runkitExpress(anExport) { var mount = express(); var app = express(); // "mount" is our root app, and it mounts "app" at your notebook path // which is available in the RUNKIT_MOUNT_PATH environment variable mount.use(process.env.RUNKIT_MOUNT_PATH || "", app); if (anExport) { anExport.endpoint = mount; } // overwrite .listen since it is not needed app.listen = function(){} // return the express instance for use by the caller return app; } module.exports = runkitExpress
  • Hello, World API - /runkit/hello-world-api
    Last edited 7 years ago
    exports.endpoint = function(req, res) { res.end("Hello, World!"); }
  • Forecast - /runkit/forecast
    Last edited 7 years ago
    require("request"); // peer dependency var request = require('request-promise'); var _ = require('lodash'); var url = require('url'); var apiKey = process.env.OPENWEATHERMAP_KEY; function temperatureURL(city) { return url.format({ protocol: "http", host: "api.openweathermap.org", pathname: "data/2.5/forecast", query: {units: "imperial", mode: "json", q: city, APPID: apiKey} }); } async function threeDay(city) { if (!apiKey) { throw `<div> <h2>Whoops!</h2> <p>You need an API key to use this service. Sign up at <a href="http://home.openweathermap.org/users/sign_up"> openweathermap.org</a>, and grab your API key:<br /><br /> <img src="http://bit.ly/1GgoJZm" width="500" /></p> <p>Now, add <code>OPENWEATHERMAP_KEY</code> to your <a href="https://tonicdev.com/settings/environment"> environment settings</a>:<br /><br /> <img src="http://bit.ly/1kmRPfQ" width="500" /></p> </div>` } var response = await request(temperatureURL(city)); return _.map(JSON.parse(response)['list'], function(entry) { return entry["main"]["temp"]; }); }; module.exports = { threeDay: threeDay };
  • async/await - /runkit/async-await
    Last edited 7 years ago
    A common way to get around nesting callbacks everywhere in JavaScript is to use promises. But these require chaining a bunch of "then" functions together to do anything, which is still cumbersome. Putting "await" before any promise let's you write linear looking code, which works great with Tonic and our object viewers that show you the value of the last expression:
  • d3 Example from Beaker - /runkit/d3-example-from-beaker
    Last edited 7 years ago
    Original example using Python here: http://sharing.beakernotebook.com/gist/anonymous/e21582541d7c1fe60eb4
  • GitHub Statistics - /runkit/github-statistics
    Last edited 7 years ago
    const getJSON = require("async-get-json"); exports.getCommitActivity = async function (props) { const normalized = typeof props === "string" ? { repo: props } : props; const [user, repo] = normalized.repo.includes("/") ? normalized.repo.split("/") : [normalized.user, normalized.repo]; const COMMIT_ACTIVITY_API = `https://api.github.com/repos/${user}/${repo}/stats/commit_activity`; const items = await getJSON(COMMIT_ACTIVITY_API); // Return last week so we have a full week. return items[items.length - 2]; } exports.getMostPopularRepos = async function({ limit }) { const POPULAR_REPOS_API = "https://api.github.com/search/repositories"; const query = `?q=javascript&sort=stars&order=desc&per_page=${limit}`; return (await getJSON(POPULAR_REPOS_API + query)).items; }
  • d3 graph module - /runkit/d3-graph
    Last edited 7 years ago
    var R = require("ramda") module.exports = function(nodes, links, options = { }) { options.width = R.has("width", options) ? +options.width : 500; options.height = R.has("height", options) ? +options.height : 300; var JSONObject = { graph: { nodes, links }, width: options.width, height: options.height }; return "<center>" + "<style>.node { stroke: #fff; stroke-width: 1.5px; }" + ".link { stroke: #999; stroke-opacity: .6; }" + "</style>" + "<svg width = " + options.width + " height = " + options.height + " ></svg>" + "<script src='https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js'></script>" + "<script>(" + toHTMLD3Graph + ")(" + JSON.stringify(JSONObject)+ ")</script>"; } module.exports([{ "group":0, "name": 0}, { "group":0, "name": 1}],[{ source:0, target: 1, value:0.9}])