diff --git a/index.ts b/index.ts index 2ec52c9..8eac922 100644 --- a/index.ts +++ b/index.ts @@ -2,7 +2,7 @@ import fs from 'fs' import path from 'path' import http from 'http' -const serve404 = require('./libs/serve-404.js') +import serve404 from './libs/serve-404' const badgeHandlers = fs.readdirSync(path.join(__dirname, 'endpoints')) .filter(name => !name.startsWith('_')) diff --git a/libs/badgen-serve.ts b/libs/badgen-serve.ts index 99749fb..64fe0eb 100644 --- a/libs/badgen-serve.ts +++ b/libs/badgen-serve.ts @@ -4,11 +4,7 @@ import PathParser from 'path-parser' import serve404 from './serve-404.js' import serveBadge from './serve-badge.js' -export type BadgenParams = { - subject: string - status: string - color: string -} +import { BadgenParams } from './types' export type BadgenServeHandlerArgs = { [key: string]: string } export type BadgenServeHandler = (args: BadgenServeHandlerArgs) => Promise diff --git a/libs/serve-badge.js b/libs/serve-badge.ts similarity index 59% rename from libs/serve-badge.js rename to libs/serve-badge.ts index 9a57abd..313cfc2 100644 --- a/libs/serve-badge.js +++ b/libs/serve-badge.ts @@ -1,10 +1,16 @@ -const badgen = require('badgen') -const { send } = require('micro') -const icons = require('badgen-icons') +import badgen from 'badgen' +import icons from 'badgen-icons' -const CACHE_CONTROL = `public, max-age=10, stale-while-revalidate=604800, stale-if-error=604800` +import { BadgenParams } from './types' -module.exports = (req, res, options = {}) => { +type ServeBadgeOptions = { + code?: number + sMaxAge?: number, + query?: { [key: string]: any }, + params?: BadgenParams +} + +export default function (req, res, options: ServeBadgeOptions) { const { code = 200, sMaxAge = '604800', query = {}, params } = options const hostStyle = req.headers.host === 'flat.badgen.net' ? 'flat' : undefined @@ -24,7 +30,9 @@ module.exports = (req, res, options = {}) => { iconWidth: _icon.width }) + const staleControl = `stale-while-revalidate=604800, stale-if-error=604800` + res.setHeader('Cache-Control', `public, max-age=10, s-maxage=${sMaxAge}, ${staleControl}`) res.setHeader('Content-Type', 'image/svg+xml;charset=utf-8') - res.setHeader('Cache-Control', `${CACHE_CONTROL}, s-maxage=${sMaxAge}`) - send(res, code, badge) + res.statusCode = code + res.end(badge) } diff --git a/libs/types.ts b/libs/types.ts new file mode 100644 index 0000000..825a20a --- /dev/null +++ b/libs/types.ts @@ -0,0 +1,5 @@ +export type BadgenParams = { + subject: string + status: string + color: string +}