Skip to main content

requester

This code defines two utility functions, submitRequest and checkFeedbackTot, for making HTTP requests in a JavaScript/TypeScript application, along with a TypeScript interface, SubmitRequestOptions. These functions are designed for a web application that interacts with an API using headers for authentication and data transformation.


Key Functionalities

1. SubmitRequestOptions<T> (TypeScript Interface)

tip

This interface defines the configuration options for the submitRequest function, providing flexibility to control various aspects of the request, such as authentication, headers, and request transformation.

  • This interface provides a blueprint for the options object that can be passed to the submitRequest function.
  • Fields:
    • sid and pin: Used for authentication, included in request headers.
    • apiUrl and endpoint: Specify the base API URL and the specific endpoint for the request.
    • method: HTTP method to use (default is POST).
    • transformData: Optional function to process and transform the request data before sending.
    • additionalHeaders: Additional headers to include in the request.
    • onSuccess and onError: Callback functions for handling success and error responses.
    • autoGeneratedBody: If true, includes a default feedbackBdy field in the request body.

2. submitRequest<T> Function

The submitRequest function is central to the data submission process. Be sure to configure it correctly to avoid errors in API communication.

  • Purpose: Submits data to an API endpoint with flexible configuration for headers, body transformation, and callbacks.
  • Parameters:
    • data: The payload to send with the request.
    • options: Configuration object adhering to the SubmitRequestOptions interface.
  • Implementation:
    • Headers:
      • Constructs request headers, including sid and pin for authentication and optional additionalHeaders.
    • Data Transformation:
      • If a transformData function is provided, it transforms the input data.
      • Ensures all values in the transformed data are strings to standardize the request payload.
    • Request Body:
      • Prepares the JSON body, optionally including a feedbackBdy field if autoGeneratedBody is true.
    • Request Execution:
      • Sends the request using fetch to a dynamically constructed URL (apiUrl + endpoint).
      • Handles the response:
        • Calls onSuccess if the request succeeds.
        • Calls onError if the request fails or an error occurs.

3. checkFeedbackTot Function

warning

The checkFeedbackTot function performs a GET request to check feedback status. Ensure that the endpoint is correct, and handle different HTTP status codes appropriately.

  • Purpose: Checks if feedback has already been submitted for the day by making a GET request to an API endpoint.
  • Parameters:
    • sid and pin: Used for authentication, included in request headers.
    • endpoint: The API endpoint to check feedback status.
  • Implementation:
    • Constructs headers similar to submitRequest.
    • Sends a GET request to the specified endpoint.
    • Parses the response to determine feedback status:
      • If the response code is '200', feedback has not been submitted today.
      • Otherwise (e.g., '409'), feedback has already been submitted.

Use Cases

  1. submitRequest:

    • Submit data to an API endpoint with customizable headers and payloads.
    • Use cases include:
      • Sending form data.
      • Creating or updating resources on a server.
      • Interacting with APIs that require specific authentication and payload structure.
  2. checkFeedbackTot:

    • Validate whether a feedback form or action has been completed for the day.
    • Typically used in applications requiring daily user input or actions.

Key Features

  1. Flexible Configuration:

    tip

    The submitRequest function offers extensive customization via headers, data transformation, and callbacks, making it highly adaptable for various use cases.

    • Supports different HTTP methods (POST, PUT, PATCH).
  2. Error Handling:

    warning

    The function logs errors for debugging. If provided, the onError callback is invoked for better error handling.

    • Logs errors for debugging and invokes the onError callback if provided.
  3. Standardized Payload:

    tip

    By ensuring all request data fields are strings, this approach prevents common issues with type mismatches in the payload.

    • Ensures all request data fields are strings, preventing type mismatches.
  4. Dynamic URL Construction:

    tip

    The submitRequest function dynamically combines apiUrl and endpoint to construct the target URL, simplifying the integration with various API routes.

    • Combines apiUrl and endpoint to build the target URL.
  5. Feedback Checking:

    The checkFeedbackTot function makes it easy to track whether a daily action, like feedback submission, has been completed, offering a boolean response for clarity.

    • checkFeedbackTot makes it easy to determine if a daily action is complete, returning a boolean for clarity.

Example Usage

submitRequest

submitRequest(
{ message: "Hello, API!" },
{
sid: "12345",
pin: "67890",
apiUrl: "https://example.com/api",
endpoint: "send-message",
method: "POST",
autoGeneratedBody: true,
onSuccess: (response) => console.log("Message sent successfully:", response),
onError: (error) => console.error("Failed to send message:", error),
}
);

checkFeedbackTot

(async () => {
const feedbackGiven = await checkFeedbackTot("12345", "67890", "check-feedback");
if (feedbackGiven) {
console.log("Feedback already submitted today.");
} else {
console.log("No feedback submitted yet.");
}
})();