badgen/preview/serve.js

52 wiersze
1.5 KiB
JavaScript
Czysty Zwykły widok Historia

2018-07-11 03:03:51 +00:00
const path = require('path')
2018-07-20 02:55:51 +00:00
const http = require('http')
const url = require('url')
2018-07-11 03:26:10 +00:00
const qs = require('querystring')
2018-07-11 03:03:51 +00:00
const serveMarked = require('serve-marked')
2018-07-01 08:11:23 +00:00
const badgen = require('..')
2018-07-20 03:15:46 +00:00
const dockerIcon = require('../test/docker-icon-b64.js')
2018-07-20 02:55:51 +00:00
2018-07-01 08:11:23 +00:00
// @example
// http://localhost:3000/npm/v1.2.3
const serveBadge = (req, res) => {
const { pathname, query } = url.parse(req.url)
2018-07-20 02:55:51 +00:00
const { style, emoji, docker } = qs.parse(query)
const icon = docker && dockerIcon
const [ subject, status, color ] = pathname.split('/')
2018-07-11 03:26:10 +00:00
.filter(Boolean)
.map(s => qs.unescape(s))
2018-07-01 08:11:23 +00:00
res.writeHead(200, { 'Content-Type': 'image/svg+xml;charset=utf-8' })
2018-07-20 02:55:51 +00:00
res.end(badgen({subject, status, color, style, emoji, icon}))
2018-07-01 08:11:23 +00:00
}
2018-07-11 03:03:51 +00:00
// @example
// http://localhost:3000
const md = path.join(__dirname, 'PREVIEW.md')
const serveIndex = serveMarked(md, {
title: 'Badgen - Fast badge generator',
preset: 'merri',
inlineCSS: `
2018-07-19 03:19:09 +00:00
body { color: #333; padding-bottom: 5em }
2018-07-11 03:03:51 +00:00
a { text-decoration: none; color: #06D }
a:hover { text-decoration: underline }
table { border-spacing: 0 }
td { padding: 0 1em 0 0; height: 24px; font: 14px/14px sans-serif }
td a { font: 14px/14px monospace; vertical-align: top }
`
})
2018-07-11 05:40:30 +00:00
const serve404 = (req, res) => {
res.writeHead(404)
res.end()
}
2018-07-11 03:03:51 +00:00
http.createServer((req, res) => {
switch (req.url) {
2018-07-11 03:26:10 +00:00
case '/': return serveIndex(req, res)
2018-07-11 05:40:30 +00:00
case '/favicon.ico': return serve404(req, res)
2018-07-11 03:26:10 +00:00
default: return serveBadge(req, res)
2018-07-11 03:03:51 +00:00
}
}).listen(3000)