MCPcopy Create free account
hub / github.com/tinyhttp/tinyhttp / markdownStaticHandler

Function markdownStaticHandler

packages/markdown/src/index.ts:36–87  ·  view source on GitHub ↗
(dir?: string, opts: MarkdownServerHandlerOptions = {})

Source from the content-addressed store, hash-verified

34}
35
36export const markdownStaticHandler = (dir?: string, opts: MarkdownServerHandlerOptions = {}) => async <
37 Req extends Request = Request,
38 Res extends Response = Response
39>(
40 req: Req,
41 res: Res,
42 next: (err?: any) => void
43) => {
44 const { prefix = '/', stripExtension = true, markedOptions = null, caching = false } = opts
45
46 const url = req.originalUrl || req.url
47
48 const urlMatchesPrefix = url.startsWith(prefix)
49
50 const unPrefixedURL: string = prefix === '/' ? url.replace(prefix, '') : url.replace(prefix, '').slice(1)
51
52 const fullPath = path.join(dir, parse(unPrefixedURL).dir)
53
54 let files: string[]
55
56 try {
57 files = await readdir(fullPath)
58
59 let filename: string
60
61 if (url === prefix) {
62 const rgx = /(index|readme).(md|markdown)/i
63
64 const idxFile = files.find((file) => rgx.test(file))
65
66 if (idxFile) {
67 await sendStream(path.join(fullPath, idxFile), markedOptions, req, res, caching)
68 return
69 } else next()
70 }
71 if (stripExtension) {
72 filename = files.find((f) => {
73 const { name, ext } = parse(f)
74
75 return /\.(md|markdown)/.test(ext) && unPrefixedURL === name
76 })
77 } else {
78 filename = files.find((f) => f === decodeURI(unPrefixedURL))
79 }
80
81 if (urlMatchesPrefix && filename) {
82 await sendStream(path.join(fullPath, filename), markedOptions, req, res, caching)
83 } else next()
84 } catch {
85 next?.()
86 }
87}

Callers 2

index.jsFile · 0.90
markdown.test.tsFile · 0.90

Calls 3

sendStreamFunction · 0.85
findMethod · 0.80
parseFunction · 0.50

Tested by

no test coverage detected