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)
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
submitRequestfunction. - Fields:
sidandpin: Used for authentication, included in request headers.apiUrlandendpoint: Specify the base API URL and the specific endpoint for the request.method: HTTP method to use (default isPOST).transformData: Optional function to process and transform the request data before sending.additionalHeaders: Additional headers to include in the request.onSuccessandonError: Callback functions for handling success and error responses.autoGeneratedBody: Iftrue, includes a defaultfeedbackBdyfield 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 theSubmitRequestOptionsinterface.
- Implementation:
- Headers:
- Constructs request headers, including
sidandpinfor authentication and optionaladditionalHeaders.
- Constructs request headers, including
- Data Transformation:
- If a
transformDatafunction is provided, it transforms the input data. - Ensures all values in the transformed data are strings to standardize the request payload.
- If a
- Request Body:
- Prepares the JSON body, optionally including a
feedbackBdyfield ifautoGeneratedBodyistrue.
- Prepares the JSON body, optionally including a
- Request Execution:
- Sends the request using
fetchto a dynamically constructed URL (apiUrl + endpoint). - Handles the response:
- Calls
onSuccessif the request succeeds. - Calls
onErrorif the request fails or an error occurs.
- Calls
- Sends the request using
- Headers:
3. checkFeedbackTot Function
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
GETrequest to an API endpoint. - Parameters:
sidandpin: Used for authentication, included in request headers.endpoint: The API endpoint to check feedback status.
- Implementation:
- Constructs headers similar to
submitRequest. - Sends a
GETrequest 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.
- If the response code is
- Constructs headers similar to
Use Cases
-
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.
-
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
-
Flexible Configuration:
tipThe
submitRequestfunction offers extensive customization via headers, data transformation, and callbacks, making it highly adaptable for various use cases.- Supports different HTTP methods (
POST,PUT,PATCH).
- Supports different HTTP methods (
-
Error Handling:
warningThe function logs errors for debugging. If provided, the
onErrorcallback is invoked for better error handling.- Logs errors for debugging and invokes the
onErrorcallback if provided.
- Logs errors for debugging and invokes the
-
Standardized Payload:
tipBy 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.
-
Dynamic URL Construction:
tipThe
submitRequestfunction dynamically combinesapiUrlandendpointto construct the target URL, simplifying the integration with various API routes.- Combines
apiUrlandendpointto build the target URL.
- Combines
-
Feedback Checking:
The
checkFeedbackTotfunction makes it easy to track whether a daily action, like feedback submission, has been completed, offering a boolean response for clarity.checkFeedbackTotmakes 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.");
}
})();