Skip to content

Commit

Permalink
JSdocs for any request obeject
Browse files Browse the repository at this point in the history
  • Loading branch information
mimiMonads committed Mar 14, 2024
1 parent 1e17eeb commit 812805e
Show file tree
Hide file tree
Showing 4 changed files with 104 additions and 25 deletions.
28 changes: 19 additions & 9 deletions components/http/src/framework/optimizer/checker.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,34 @@
/**
* Customizes the context (CTX) for Vixeny's optimizer by filtering a list of elements based on removal and addition criteria,
* and by examining the usage of these elements within a given string. This function aims to refine the CTX by ensuring that
* only the relevant context elements are included
*
*/
export default (remove: string[]) =>
(elements: string[]) =>
(add: string[]) =>
(string: string) =>
(codeString: string): string[] =>
(
(filtered) =>
(filteredString: string): string[] =>
elements
.filter((x, index, arr) =>
!remove.includes(x) &&
// First filter: Remove elements as specified and handle 'resolve.' and 'branch.' prefix cases
.filter((element, index, arr) =>
!remove.includes(element) &&
(index === 0 ||
(!arr[index - 1].startsWith("resolve.") &&
!arr[index - 1].startsWith("branch.")))
!arr[index - 1].startsWith("branch.")))
)
.filter((v) => new RegExp(`\\b${v}\\b`).test(filtered)) // Exact match filtering using regular expression
// Second filter: Match elements against the code string for exact matches
.filter((element) => new RegExp(`\\b${element}\\b`).test(filteredString))
// Add the specified elements and ensure uniqueness
.concat(add)
.reduce(
(acc, v) => acc.includes(v) === false ? acc.concat(v) : acc,
(acc: string[], element) => acc.includes(element) === false ? acc.concat(element) : acc,
[] as string[],
) as string[]
)
)(
string.replace(/(?<!`|\$\{.*)(["'])(?:(?=(\\?))\2.)*?\1/g, " ")
// Preprocess the code string to remove string literals and normalize whitespace
codeString.replace(/(?<!`|\$\{.*)(["'])(?:(?=(\\?))\2.)*?\1/g, " ")
.replace(/\s+/g, " ")
.replace(/ +/g, " "),
);
54 changes: 40 additions & 14 deletions components/http/src/optimizer/anyRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,44 @@ import {
QueryOptions,
} from "../framework/optimizer/types.ts";

/**
* Creates a handler for processing HTTP requests and generating responses suitable for any framework.
* This function is designed to be highly adaptable, allowing for extensive customization of request processing
* and response generation based on a wide range of options.
*
* It's important to note that if you are handling operations that are asynchronous in nature (e.g., fetching data from
* a database or making network requests), you should ensure that the handling function is asynchronous and returns a Promise.
*
* Example usage:
* ```js
* import { createResponseHandler } from './path/to/this/file';
*
* const options = {...}; // Custom options for your handler
* const petition = {...}; // Define how to process the request and generate a response
*
* // Create a response handler with specified options and morphism
* const handler = createResponseHandler(options)(responseMorphism);
*
* // Example of using the handler with an asynchronous operation
* async function handleRequest(request: Request) {
* return await handler(request);
* }
* ```
*
*/
export default <O extends FunRouterOptions>(o?: O) =>
<
R extends MorphismMap,
B extends AnyMorphismMap,
Q extends QueryOptions,
P extends ParamOptions,
CR extends CryptoOptions,
MU extends MutableKey,
T = any,
>(
r: ObjectaAnyMorphism<R, B, Q, P, O, CR, MU, T>,
) =>
(response(o)(r as unknown as CommonRequestMorphism)) as unknown as (
re: Request,
) => T;
<
R extends MorphismMap,
B extends AnyMorphismMap,
Q extends QueryOptions,
P extends ParamOptions,
CR extends CryptoOptions,
MU extends MutableKey,
T = any, // The return type is based on the provided morphism configuration `r`.
>(
r: ObjectaAnyMorphism<R, B, Q, P, O, CR, MU, T>,
) =>
(response(o)(r as unknown as CommonRequestMorphism)) as unknown as (
re: Request,
) => Promise<T> | T;

3 changes: 1 addition & 2 deletions components/http/src/optimizer/objectNullRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,14 @@ import response from "../framework/optimizer/response.ts";
* name: "/serverPath", // It's recommended to use `/` to add it to the root.
* path: "./yourDir/",
* template: [
* pugStaticServerPlugin(pugModule.compileFile)({
* yourPlugin(pluginModule)({
* petition: functionForTemplates
* }),
* ],
* },
* ]);
* ```
*
* This function wraps a response object with additional processing capabilities, making it easy to integrate with Vixeny's routing and plugin system. It supports a wide range of options for customizing request handling and response generation.
*/
export default <O extends FunRouterOptions>(o?: O) =>
<
Expand Down
44 changes: 44 additions & 0 deletions components/http/src/optimizer/resolveComposer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,50 @@ type ResolveSetter = {
};
} & FunRouterOptions;

/**
* Resolve is mockable wich facilitates testing and development,
* by simulating responses from external APIs or complex logic without the need for actual data fetches.
*
* This function is particularly useful for scenarios requiring the simulation of external dependencies,
* such as API calls, allowing for consistent and controlled testing environments.
*
* ### Example Usage:
*
* The following example demonstrates how to replace an asynchronous resolve function for fetching weather data
* with a mocked synchronous function for controlled testing:
*
* ```typescript
* // Define the original asynchronous resolve function for fetching weather data
* const routes = wrap(options)()
* .stdPetition({
* path: "/weather",
* resolve: {
* currentWeather: {
* async f: () => await fetch("https://api.weather.com/current").then(res => res.json())
* }
* },
* f: (c) => c.resolve.currentWeather.temperature > 75 ? "It's warm outside" : "It's cool outside"
* });
*
* // Mock the resolve function for testing
* const mockedWeatherResolve = () => ({ temperature: 80 });
*
* // Inject the mocked resolve
* const mockRoutes = routes.handleRequest("/weather")({
* resolve: {
* currentWeather: mockedWeatherResolve
* }
* });
*
* // Test the behavior with mocked data
* test("/weather", async () => {
* expect(
* await mockRoutes(new Request("/weather")).then(res => res.text())
* ).toStrictEqual("It's warm outside");
* });
* ```
*/

export default (o?: ResolveSetter) => (f: ResolveOptions) =>
o && "mutable" in o
? (
Expand Down

0 comments on commit 812805e

Please sign in to comment.