import { Request, Response, NextFunction } from 'express';
import { parse as parseUrl } from 'url';
import { fsPath } from './common';

export function fileHandler(urlPath: string, filePath: string) {
  filePath = fsPath.resolve(filePath);
  return (req: Request, res: Response, next: NextFunction) => {
    // Only allow GET requests.
    if (req.method !== 'GET') {
      return next();
    }

    // Match the URL.
    const requestUrl = parseUrl(req.url, true);
    if (requestUrl.href !== urlPath && requestUrl.pathname !== urlPath) {
      return next();
    }

    res.sendFile(filePath);
  };
}
