MCPcopy
hub / github.com/tinyhttp/tinyhttp / send

Function send

packages/send/src/send.ts:20–76  ·  view source on GitHub ↗
(req: Request, res: Response)

Source from the content-addressed store, hash-verified

18 * @param res Response
19 */
20export const send = <Request extends Req = Req, Response extends Res = Res>(req: Request, res: Response) => (
21 body: any
22): Response => {
23 let bodyToSend = body
24
25 if (Buffer.isBuffer(body)) {
26 bodyToSend = body
27 } else if (typeof body === 'object' && body !== null) {
28 // in case of object - turn it to json
29 bodyToSend = JSON.stringify(body, null, 2)
30 } else if (typeof body === 'string') {
31 // reflect this in content-type
32 const type = res.getHeader('Content-Type')
33
34 if (type && typeof type === 'string') {
35 res.setHeader('Content-Type', setCharset(type, 'utf-8'))
36 } else res.setHeader('Content-Type', setCharset('text/html', 'utf-8'))
37 }
38
39 // Set encoding
40 const encoding: 'utf8' | undefined = 'utf8'
41
42 // populate ETag
43 let etag: string | undefined
44 if (body && !res.getHeader('etag') && (etag = createETag(bodyToSend, encoding))) {
45 res.setHeader('etag', etag)
46 }
47
48 // strip irrelevant headers
49 if (res.statusCode === 204 || res.statusCode === 304) {
50 res.removeHeader('Content-Type')
51 res.removeHeader('Content-Length')
52 res.removeHeader('Transfer-Encoding')
53 bodyToSend = ''
54 }
55
56 if (req.method === 'HEAD') {
57 res.end('')
58 return
59 }
60
61 if (typeof body === 'object') {
62 if (body == null) {
63 res.end('')
64 return
65 } else if (Buffer.isBuffer(body)) {
66 if (!res.getHeader('Content-Type')) res.setHeader('content-type', 'application/octet-stream')
67 res.end(bodyToSend)
68 } else encoding ? json(res)(bodyToSend, encoding) : json(res)(bodyToSend)
69 } else {
70 if (typeof bodyToSend !== 'string') bodyToSend = bodyToSend.toString()
71
72 encoding ? res.end(bodyToSend, encoding) : res.end(bodyToSend)
73 }
74
75 return res
76}

Callers 4

sendStreamFunction · 0.90
sendStatusFunction · 0.90
send.test.tsFile · 0.90
extendMiddlewareFunction · 0.50

Calls 3

setCharsetFunction · 0.90
createETagFunction · 0.90
jsonFunction · 0.90

Tested by

no test coverage detected