// Loaded from https://deno.land/x/tinyhttp@0.1.18/extend.ts import { NextFunction } from 'https://esm.sh/@tinyhttp/router' import { App, renderTemplate } from './app.ts' import { Request } from './request.ts' import { getRequestHeader, getFreshOrStale, getAccepts, getAcceptsCharsets, getAcceptsEncodings, getAcceptsLanguages, checkIfXMLHttpRequest, getHostname, getIP, getIPs, getProtocol, getSubdomains, getRangeFromHeader, reqIs } from './extensions/req/mod.ts' import { send, json, sendStatus, setHeader, setLocationHeader, end, sendFile, getResponseHeader, append, setLinksHeader, setContentType, formatResponse, setVaryHeader, attachment, download, setCookie, clearCookie, redirect } from './extensions/res/mod.ts' import { getQueryParams } from './utils/parseUrl.ts' import { Response } from './response.ts' export const extendMiddleware = (app: App) => (req: Req, res: Res, next: NextFunction) => { const { settings } = app res.locals = res.locals || Object.create(null) // Request extensions if (settings?.bindAppToReqRes) { req.app = app res.app = app } req.query = getQueryParams(req.url) req.connection = { remoteAddress: (req.conn.remoteAddr as Deno.NetAddr).hostname } req.get = getRequestHeader(req) req.accepts = getAccepts(req) req.acceptsCharsets = getAcceptsCharsets(req) req.acceptsEncodings = getAcceptsEncodings(req) req.acceptsLanguages = getAcceptsLanguages(req) req.range = getRangeFromHeader(req) req.xhr = checkIfXMLHttpRequest(req) req.is = reqIs(req) if (settings?.networkExtensions) { req.protocol = getProtocol(req) req.secure = req.protocol === 'https' req.hostname = getHostname(req) req.subdomains = getSubdomains(req, settings.subdomainOffset) req.ip = getIP(req) req.ips = getIPs(req) } // Response extensions res.end = end(req, res) res.send = send(req, res) res.sendFile = sendFile(req, res) res.sendStatus = sendStatus(req, res) res.json = json(req, res) res.setHeader = setHeader(res) res.set = setHeader(res) res.location = setLocationHeader(req, res) res.get = getResponseHeader(res) res.append = append(res) res.render = renderTemplate(res, app) res.links = setLinksHeader(res) res.redirect = redirect(req, res, next) res.type = setContentType(res) res.format = formatResponse(req, res, next) res.vary = setVaryHeader(res) res.download = download(req, res) res.attachment = attachment(res) res.cookie = setCookie(req, res) res.clearCookie = clearCookie(res) Object.defineProperty(req, 'fresh', { get: getFreshOrStale.bind(null, req, res), configurable: true }) req.stale = !req.fresh next?.() }