All files / estuary-rpc-server middleware.ts

34.78% Statements 16/46
10.34% Branches 6/58
7.69% Functions 1/13
34.88% Lines 15/43

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152  1x 1x   1x   1x             1x                                               1x                 1x   1x 1x   1x     1x                               1x                                                                               1x 1x                                                           1x                    
import { IncomingMessage, ServerResponse } from "http";
import { join, extname } from "path";
import { promises as fs } from "fs";
 
import { SimpleMeta, HTTP_STATUS_CODES } from "estuary-rpc";
 
import {
  errorResponse,
  DEFAULT_NOT_FOUND,
  DEFAULT_INTERNAL_SERVER_ERROR,
} from "./errors";
import { ServerOpts, StaticFileOpts } from "./types";
 
const MIME_TYPES = {
  ".html": "text/html",
  ".htm": "text/html",
  ".js": "text/javascript",
  ".css": "text/css",
  ".json": "application/json",
  ".png": "image/png",
  ".jpg": "image/jpg",
  ".jpeg": "image/jpg",
  ".gif": "image/gif",
  ".svg": "image/svg+xml",
  ".wav": "audio/wav",
  ".mp4": "video/mp4",
  ".woff": "application/font-woff",
  ".ttf": "application/font-ttf",
  ".eot": "application/vnd.ms-fontobject",
  ".otf": "application/font-otf",
  ".wasm": "application/wasm",
};
 
/**
 * Defines a unique string ID for all endpoints
 * @group Server
 */
export function methodId(meta: { method?: string; url?: string }) {
  return `${meta.method}:${meta.url}`;
}
 
/**
 * Parses the IncomingMessage into the URL object, useful for queryString parsing
 * @param req
 * @group Server
 */
export function getUrl(req: IncomingMessage): URL | undefined {
  let url: URL | undefined;
  try {
    url = new URL(req.url ?? "", `http://${req.headers.host ?? ""}`);
  } catch {}
  return url;
}
 
const contentCache: Record<string, Buffer | null> = {};
async function cachedDefaultContent(path?: string) {
  Iif (path === undefined || contentCache[path] === null) {
    return null;
  }
  Iif (contentCache[path]) {
    return contentCache[path];
  }
  contentCache[path] = await fs.readFile(path).catch(() => null);
  return contentCache[path];
}
/**
 * Method for serving the static file at filePath to a client
 *
 * @group Server
 */
export const serveStatic = async (
  _: IncomingMessage,
  res: ServerResponse,
  filePath: string,
  defaultPath?: string,
  defaultCode?: number
) => {
  const ext = String(extname(filePath)).toLowerCase();
 
  const contentType = MIME_TYPES[ext] ?? "application/octet-stream";
  const defaultContent = await cachedDefaultContent(defaultPath);
 
  fs.readFile(filePath)
    .then((content) => {
      res.writeHead(200, { "Content-Type": contentType });
      res.end(content, "utf-8");
    })
    .catch((error) => {
      if (error.code === "ENOENT" || error.code === "EISDIR") {
        res.writeHead(defaultCode ?? HTTP_STATUS_CODES.NOT_FOUND, {
          "Content-Type": defaultContent ? "text/html" : "application/json",
        });
        res.end(defaultContent ?? errorResponse(DEFAULT_NOT_FOUND), "utf-8");
      } else {
        console.log(error);
        res.writeHead(500, { "Content-Type": "application/json" });
        res.end(errorResponse(DEFAULT_INTERNAL_SERVER_ERROR), "utf-8");
      }
    });
};
 
/**
 * Creates a middleware object for serving static files. See {@link StaticFileOpts} for more detailed information
 * Can't really imagine needing to use this directly, instead you should just define the staticFiles field in the
 * {@link createApiServer}
 * @param staticFileOpts
 * @returns Static File Middles
 *
 * @group Server
 */
export const staticFileMiddleware =
  ({
    defaultFile = "404.html",
    apiPrefixes = [],
    defaultCode = HTTP_STATUS_CODES.NOT_FOUND,
    fileRoot = "./static",
    urlRoot = "",
  }: StaticFileOpts) =>
  async (req: IncomingMessage, res: ServerResponse) => {
    const filePath = join(fileRoot, req.url?.slice(urlRoot.length) ?? "");
    Iif (
      !req.url?.startsWith(urlRoot) ||
      apiPrefixes.some((prefix) => req.url?.startsWith(prefix))
    ) {
      return true;
    }
 
    await serveStatic(
      req,
      res,
      filePath,
      join(fileRoot, defaultFile),
      defaultCode
    );
    return false;
  };
 
/**
 * Gets the list of middlewares given serverOpts
 * @group Server
 */
export function automaticMiddleware<Meta extends SimpleMeta>(
  serverOpts: ServerOpts<Meta>
) {
  return [
    ...(serverOpts.staticFiles
      ? [staticFileMiddleware(serverOpts.staticFiles)]
      : []),
    ...(serverOpts.restMiddleware || []),
  ];
}