All files / estuary-rpc-server errors.ts

63.63% Statements 7/11
0% Branches 0/6
0% Functions 0/4
63.63% Lines 7/11

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 511x   1x 1x 1x 1x                               1x                         1x                                
import { HTTP_STATUS_CODES } from "estuary-rpc";
 
export const DEFAULT_BAD_REQUEST = "Bad Request";
export const DEFAULT_INTERNAL_SERVER_ERROR = "Internal Server Error";
export const DEFAULT_NOT_FOUND = "Page Not Found";
export const DEFAULT_UNAUTHORIZED = "Unauthorized";
 
/**
 * Errors sent from client to server should be of this type, encoded in JSON
 * @group Server
 */
export type ErrorResponse = {
  status: "error";
  message: string;
};
 
/**
 * @param message Error Message
 * @returns Common JSON representation used for an error for transmission to the client
 * @group Server
 */
export function errorResponse(message: string) {
  return JSON.stringify({
    status: "error",
    message,
  });
}
 
/**
 *
 * @param respond Method allowing for a response to the client, obfuscating the underlying transport
 * @returns An object with two methods to be used for returning common errors to the client
 * @group Server
 */
export function createErrorHandlers(
  respond: (status: number, message?: string) => void
) {
  return {
    badRequest: (message?: string) =>
      respond(
        HTTP_STATUS_CODES.BAD_REQUEST,
        errorResponse(message || DEFAULT_BAD_REQUEST)
      ),
    internalServerError: (message?: string) =>
      respond(
        HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,
        errorResponse(message ?? DEFAULT_INTERNAL_SERVER_ERROR)
      ),
  };
}