badgen.net/libs/badgen-serve.ts

66 wiersze
1.7 KiB
TypeScript
Czysty Zwykły widok Historia

2019-05-13 12:00:56 +00:00
import url from 'url'
2019-05-14 02:19:56 +00:00
import serve404 from './serve-404'
import serveBadge from './serve-badge'
2019-05-15 13:13:07 +00:00
import matchRoute from './match-route'
2019-05-13 12:00:56 +00:00
2019-05-14 01:36:25 +00:00
import { BadgenParams } from './types'
2019-05-13 12:00:56 +00:00
2019-05-26 04:38:30 +00:00
export type BadgenServeMeta = {
2019-05-26 05:09:19 +00:00
title: string
2019-05-26 04:38:30 +00:00
examples: { [url: string]: string }
2019-05-26 05:09:19 +00:00
help?: string
2019-05-26 04:38:30 +00:00
}
2019-05-13 12:00:56 +00:00
export type BadgenServeHandlerArgs = { [key: string]: string }
export type BadgenServeHandler = (args: BadgenServeHandlerArgs) => Promise<BadgenParams>
export type BadgenServeHandlers = { [key: string]: BadgenServeHandler }
2019-05-14 01:15:16 +00:00
export function badgenServe (handlers: BadgenServeHandlers): Function {
2019-05-13 12:00:56 +00:00
return async function httpHandler (req, res) {
const { pathname = '/', query } = url.parse(req.url, true)
// serve favicon
if (pathname === '/favicon.ico') {
return res.end()
}
// Lookup handler
let matchedArgs
const matchedScheme = Object.keys(handlers).find(scheme => {
2019-05-15 13:13:07 +00:00
matchedArgs = matchRoute(scheme, decodeURI(pathname))
2019-05-13 12:00:56 +00:00
return matchedArgs !== null
})
if (matchedScheme) {
2019-05-14 09:50:57 +00:00
try {
const params = await handlers[matchedScheme](matchedArgs)
return serveBadge(req, res, { params, query })
} catch (error) {
2019-05-26 07:54:24 +00:00
if (error.statusCode === 404) {
return serveBadge(req, res, {
code: 404,
params: {
subject: pathname.split('/')[1],
status: '404',
color: 'grey'
}
})
}
2019-05-14 09:50:57 +00:00
console.error(error)
return serveBadge(req, res, {
code: 500,
params: {
subject: 'badgen',
status: 'error',
color: 'red'
}
})
}
2019-05-13 12:00:56 +00:00
} else {
return serve404(req, res)
}
}
}