Skip to content

Instantly share code, notes, and snippets.

@overra
Created December 31, 2018 02:52
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 overra/fddbb6c0c788e81902272eab0585338e to your computer and use it in GitHub Desktop.
Save overra/fddbb6c0c788e81902272eab0585338e to your computer and use it in GitHub Desktop.
Sends response with prism wrapped gist code
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 = {'&': '&amp;', '<': '&lt;', '>': '&gt;'};
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