# \[Unlock Workflow Power\] only with one Running.JS scheduled Task

**URL:** <https://community.dynatrace.com/t/unlock-workflow-power-only-with-one-running-js-scheduled-task/46734>\
**Category:** Dynatrace Tips\
**Tags:** credential-vault, automationengine, workflows, appengine, dynatrace-api, javascript\
**Created:** [July 22, 2024, 2:39pm UTC](https://community.dynatrace.com/t/unlock-workflow-power-only-with-one-running-js-scheduled-task/46734 "2024-07-22T14:39:45Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![uros\_djukic1](https://dub1.discourse-cdn.com/dynatrace/user_avatar/community.dynatrace.com/uros_djukic1/32/37084_2.png) [@uros\_djukic1](https://community.dynatrace.com/u/uros_djukic1)\
**Post date:** [July 22, 2024, 2:39pm UTC](https://community.dynatrace.com/t/unlock-workflow-power-only-with-one-running-js-scheduled-task/46734/1 "2024-07-22T14:39:45Z")

</div>

In our customer context, we used the Workflow to collect the availability rate on a specific scenario in a solution composed of external APIs. In order to feed the main dashboard of availability of “critical” applications. Thus meeting a functional need.

Valid and compliant for Dynatrace SaaS platform version 1.296.

\*\*\* client context

Formerly we had to use a Python script and implement a V1 extension, here the simple use of the Workflow with a little knowledge via Javascript makes our work easier!

\*\*\* WORKAROUND OVERVIEW

Before sharing my “only one Task JS” please find main lines of my running.JS :

1 .&nbsp; // Retrieve credentials from the credential vault for External API  
&nbsp; &nbsp;2.&nbsp;&nbsp;// fetching bearer Token value  
&nbsp; &nbsp;3.&nbsp;&nbsp;// collect APIs parameters from external endpoints  
&nbsp; &nbsp;4 . // ingest metric to Dynatrace

Find my script lightened but with the important steps, all-in-one running.JS task as depicted below :

| import { credentialVaultClient } from “@dynatrace-sdk/client-classic-environment-v2”;import { executionsClient } from ‘@dynatrace-sdk/client-automation’;import { execution } from ‘@dynatrace-sdk/automation-utils’;import { metricsClient } from “@dynatrace-sdk/client-classic-environment-v2”;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;**// Main()export default async function ({ execution\_id }) { ==\>&nbsp; Main function&nbsp;&nbsp; try {&nbsp; &nbsp; // Retrieve credentials from the credential vault for External endpoint API&nbsp; &nbsp; const External endpointCredentials = await credentialVaultClient.getCredentialsDetails(&nbsp; &nbsp; &nbsp; { id: “CREDENTIALS\_VAULT-XXX” }&nbsp; &nbsp; );&nbsp; &nbsp; const External endpointUsername = External endpointCredentials.username;&nbsp; &nbsp; const External endpointPassword = External endpointCredentials.password;&nbsp; &nbsp; if (!External endpointUsername || !External endpointPassword) {&nbsp; &nbsp; &nbsp; throw new Error(‘External endpoint credentials are not defined.’);&nbsp; &nbsp; }// fetching bearer Token value**&nbsp; &nbsp; async function fetchBearerToken() { **==\> function 1 : getToken from External endpoint** &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; const response = await fetch(‘[https://api.External](https://api.External) endpoint.XXX/auth/login’, {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; method: ‘POST’,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; body: JSON.stringify({ email: External endpointUsername, password: External endpointPassword }),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; headers: {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ‘Content-Type’: ‘application/json’,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ‘Accept’: ‘application/json’,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; // Parse response body as JSON&nbsp; &nbsp; } **// collect APIs parameters from External endpoint** &nbsp; &nbsp; async function fetchData(bearerToken) { **==\> function 2 : get parameters/data from External endpoint (i.e. scenarioName)**&nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; console.log(‘Bearer Token:’, bearerToken); **// make dates dynamic** function formatDate(date) {var d = new Date(date),&nbsp; &nbsp; &nbsp; &nbsp; month = ‘’ + (d.getMonth() + 1),&nbsp; &nbsp; &nbsp; &nbsp; day = ‘’ + d.getDate(),&nbsp; &nbsp; &nbsp; &nbsp; year = d.getFullYear();if (month.length \< 2)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; month = ‘0’ + month;if (day.length \< 2)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; day = ‘0’ + day;return [year, month, day].join(‘-’);};var today = new Date();var firstDay = new Date(today.getFullYear(),today.getMonth()-1,1);firstDay.setDate(Math.min(today.getDate(),firstDay.getDate()));var lastDay = formatDate(new Date(today.getFullYear(),today.getMonth(),0))+ ’ 00:00:00’;firstDay=formatDate(firstDay.getFullYear()+‘-’+(firstDay.getMonth()+1)+‘-’+firstDay.getDate())+ ’ 00:00:00’;console.log(firstDay);console.log(lastDay);&nbsp; &nbsp; &nbsp; &nbsp; const body = {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; “dates”: {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; “from”: firstDay,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; “to”: lastDay&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; **// Define the endpoint to fetch data from** &nbsp; &nbsp; &nbsp; &nbsp; const apiEndpoint = ‘[https://api.External](https://api.External) [endpoint.XXX.net/results/avail/XXX](http://endpoint.XXX.net/results/avail/XXX)’; **// Replace with the actual endpoint** &nbsp; &nbsp; &nbsp; &nbsp; // Try to parse response as JSON if needed&nbsp; &nbsp; }&nbsp; &nbsp; **// Fetch bearer token and data** &nbsp; &nbsp; const bearerToken = await fetchBearerToken();&nbsp; &nbsp; const scenarioData = await fetchData(bearerToken);&nbsp; &nbsp; **// Assuming the scenarioData contains the relevant fields directly** &nbsp; &nbsp; const get\_scenario\_name = scenarioData.scenarioName;&nbsp; &nbsp; const get\_scenario\_rate = scenarioData.ratePercent;&nbsp; &nbsp; **// Send the metrics to Dynatrace ==\>&nbsp; Ingest metrics via Dynatrace API** &nbsp;&nbsp; &nbsp; const environment = “/platform/classic/environment-api/v2/metrics/ingest”;&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; const response = await fetch(environment, {&nbsp; &nbsp; &nbsp; &nbsp; method: ‘POST’,&nbsp; &nbsp; &nbsp; &nbsp; headers: {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ‘Content-Type’: ‘text/plain; charset=utf-8’,&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; body: `External endpoint.availability.rate,scenario.name=${get_scenario_name} ${get_scenario_rate}`,&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; // Try to parse response as JSON if needed&nbsp; } catch (error) {&nbsp; &nbsp; console.error(‘Error in script execution:’, error);&nbsp; &nbsp; throw error;&nbsp; } |
| --- |

I hope it helps,

Thanks

 ![Workflowpics.png](https://global.discourse-cdn.com/dynatrace/original/3X/a/d/ad061ac9ceb9d08dfe549ee72895a02c94778060.png)
