Created
December 31, 2018 02:52
-
-
Save overra/fddbb6c0c788e81902272eab0585338e to your computer and use it in GitHub Desktop.
Sends response with prism wrapped gist code
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
const fetch = require('isomorphic-unfetch') | |
const { json, send } = require('micro') | |
const { readFileSync } = require('fs') | |
const { resolve } = require('path') | |
// read template once | |
const template = readFileSync(resolve(__dirname, './static/code.html'), 'utf8'); | |
// encode html entities | |
const entities = {'&': '&', '<': '<', '>': '>'}; | |
const replaceTag = tag => entities[tag] || tag | |
const htmlEntities = str => str.replace(/[&<>]/g, replaceTag) | |
// these help with <pre> whitespace issues and keeping lines under 80 char | |
const pre = c => `<pre>${c}</pre>` | |
const code = (c, lang = 'js') => `<code class="language-${lang}">${c}</code>` | |
const getJson = url => fetch(url).then(res => res.json()) | |
module.exports = async (req, res) => { | |
const id = req.url.split('/').pop() | |
if (id === 'favicon.ico') return send(res, 404) | |
const { files } = await getJson(`https://api.github.com/gists/${id}`) | |
const source = Object.entries(files).reduce((source, [name, info]) => { | |
const file = ` | |
<pre>${name}</pre> | |
${pre(code(htmlEntities(info.content), info.language.toLowerCase()))} | |
` | |
return source + file | |
}, '') | |
send(res, 200, template + source) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment