diff --git a/docs/documentation.toml b/docs/documentation.toml index a15a1291..d50831ef 100644 --- a/docs/documentation.toml +++ b/docs/documentation.toml @@ -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") %>""" + diff --git a/src/core/functions/internal_functions/web/InternalModuleWeb.ts b/src/core/functions/internal_functions/web/InternalModuleWeb.ts index caac7014..eb2f5c36 100644 --- a/src/core/functions/internal_functions/web/InternalModuleWeb.ts +++ b/src/core/functions/internal_functions/web/InternalModuleWeb.ts @@ -7,10 +7,12 @@ export class InternalModuleWeb extends InternalModule { async create_static_templates(): Promise { 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 {} @@ -80,4 +82,31 @@ export class InternalModuleWeb extends InternalModule { } }; } + + generate_request(): ( + url: string, + path?: string, + ) => Promise { + 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"); + } + }; + } }