Skip to content

Commit

Permalink
Merge pull request #1385 from Rooyca/master
Browse files Browse the repository at this point in the history
feat: new web function to make http requests
  • Loading branch information
Zachatoo authored Sep 4, 2024
2 parents 1e05b7a + 83d7eec commit 55e251d
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
21 changes: 21 additions & 0 deletions docs/documentation.toml
Original file line number Diff line number Diff line change
Expand Up @@ -619,4 +619,25 @@ example = """<% tp.web.random_picture("200x200") %>"""
name = "Random picture with size and query"
example = """<% tp.web.random_picture("200x200", "landscape,water") %>"""

[tp.web.functions.request]
name = "request"
description = "Makes a HTTP request to the specified URL. Optionally, you can specify a path to extract specific data from the response."
definition = "tp.web.request(url: string, path?: string)"

[[tp.web.functions.request.args]]
name = "url"
description = "The URL to which the HTTP request will be made."

[[tp.web.functions.request.args]]
name = "path"
description = "A path within the response JSON to extract specific data."

[[tp.web.functions.request.examples]]
name = "Simple request"
example = """<% tp.web.request("https://jsonplaceholder.typicode.com/todos/1") %>"""

[[tp.web.functions.request.examples]]
name = "Request with path"
example = """<% tp.web.request("https://jsonplaceholder.typicode.com/todos", "0.title") %>"""


29 changes: 29 additions & 0 deletions src/core/functions/internal_functions/web/InternalModuleWeb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@ export class InternalModuleWeb extends InternalModule {

async create_static_templates(): Promise<void> {
this.static_functions.set("daily_quote", this.generate_daily_quote());
this.static_functions.set("request", this.generate_request());
this.static_functions.set(
"random_picture",
this.generate_random_picture()
);

}

async create_dynamic_templates(): Promise<void> {}
Expand Down Expand Up @@ -80,4 +82,31 @@ export class InternalModuleWeb extends InternalModule {
}
};
}

generate_request(): (
url: string,
path?: string,
) => Promise<string> {
return async (url: string, path?: string) => {
try {
const response = await this.getRequest(url);
const jsonData = await response.json();

if (path && jsonData) {
return path.split('.').reduce((obj, key) => {
if (obj && obj.hasOwnProperty(key)) {
return obj[key];
} else {
throw new Error(`Path ${path} not found in the JSON response`);
}
}, jsonData);
}

return jsonData;
} catch (error) {
console.error(error);
throw new TemplaterError("Error fetching and extracting value");
}
};
}
}

0 comments on commit 55e251d

Please sign in to comment.