Giter Club home page Giter Club logo

datadog-api-client-typescript's Introduction

Node.js Datadog API Client

License

This repository contains a Node.js API client for the Datadog API.

How to install

The package is under @datadog/datadog-api-client and can be installed through NPM or Yarn:

# NPM
npm install @datadog/datadog-api-client

# Yarn
yarn add @datadog/datadog-api-client

Getting Started

Here's an example getting a monitor:

import { client, v1 } from '@datadog/datadog-api-client';

const configuration = client.createConfiguration();
const apiInstance = new v1.MonitorsApi(configuration);

let params:v1.MonitorsApiGetMonitorRequest = {
  // number | The ID of the monitor
  monitorId: 1,
};

apiInstance.getMonitor(params).then((data: v1.Monitor) => {
  console.log('API called successfully. Returned data: ' + data);
}).catch((error:any) => console.error(error));

Authentication

By default the library will use the DD_API_KEY and DD_APP_KEY environment variables to authenticate against the Datadog API. To provide your own set of credentials, you need to set the appropriate keys on the configuration:

import { client } from '@datadog/datadog-api-client';

const configurationOpts = {
  authMethods: {
    apiKeyAuth: "<API KEY>",
    appKeyAuth: "<APPLICATION KEY>"
  },
};

const configuration = client.createConfiguration(configurationOpts);

Unstable Endpoints

This client includes access to Datadog API endpoints while they are in an unstable state and may undergo breaking changes. An extra configuration step is required to enable these endpoints:

configuration.unstableOperations["<version>.<operationName>"] = true

where <operationName> is the name of the method used to interact with that endpoint. For example: listLogIndexes, or getLogsIndex.

Changing Server

When talking to a different server, like the eu instance, change the server variables:

import { client } from '@datadog/datadog-api-client';

const configuration = client.createConfiguration();

configuration.setServerVariables({
  site: "datadoghq.eu"
});

Disable compressed payloads

If you want to disable GZIP compressed responses, set the compress flag on your configuration options:

import { client } from '@datadog/datadog-api-client';
const configurationOpts = {
  httpConfig: {
    compress: false
  },
};

const configuration = client.createConfiguration(configurationOpts);

Enable requests logging

If you want to enable requests logging, set the debug flag on your configuration object:

import { client } from '@datadog/datadog-api-client';
const configurationOpts = {
  debug: true
};

const configuration = client.createConfiguration(configurationOpts);

Enable retry

To enable the client to retry when rate limited (status 429) or status 500 and above:

import { client } from '@datadog/datadog-api-client';
const configurationOpts = {
  enableRetry: true
};

const configuration = client.createConfiguration(configurationOpts);

The interval between 2 retry attempts will be the value of the x-ratelimit-reset response header when available. If not, it will be :

(backoffMultiplier ** current_retry_count) * backoffBase

The maximum number of retry attempts is 3 by default and can be modified with

maxRetries

Adding timeout to requests

To add timeout or other mechanism to cancel requests, you need an abort controller, for example the one implemented by abort-controller. You can then pass the `signal method to the HTTP configuration options:

import { client, v1 } from '@datadog/datadog-api-client';
import AbortController from 'abort-controller';

const controller = new AbortController();
const timeout = setTimeout(
  () => { controller.abort(); },
  1000,
);
const configurationOpts = {
  httpConfig: {
    signal: controller.signal
  },
};

const configuration = client.createConfiguration(configurationOpts);

const apiInstance = new v1.MonitorsApi(configuration);
apiInstance.listMonitors().then((data: v1.Monitor[]) => {
  console.log('API called successfully. Returned data: ' + data);
}).catch((error:any) => console.error(error)).finally(() => clearTimeout(timeout));

Pagination

Several listing operations have a pagination method to help consume all the items available. For example, to retrieve all your incidents:

import { client, v2 } from "@datadog/datadog-api-client";

async function main() {
  const configuration = client.createConfiguration();
  configuration.unstableOperations["v2.listIncidents"] = true;
  const apiInstance = new v2.IncidentsApi(configuration);

  for await (const incident of apiInstance.listIncidentsWithPagination()) {
      console.log("Got incident " + incident.id);
  }
}

main();

Zstd compression

Zstd compression support requires users to supply their own zstd compressor callback function. The callback should accept string arg and return compressed Buffer data. Callback signature (body: string) => Buffer. For example, using zstd.ts package:

import { compressSync } from 'zstd.ts'
import { client, v2 } from "@datadog/datadog-api-client";

async function main() {
  const configurationOpts = {
    zstdCompressorCallback: (body: string) => compressSync({input: Buffer.from(body, "utf8")})
  }
  const configuration = client.createConfiguration(configurationOpts);
  const apiInstance = new v2.MetricsApi(configuration);
  const params: v2.MetricsApiSubmitMetricsRequest = {
      body: {
          series: [
              {
                  metric: "system.load.1",
                  type: 0,
                  points: [
                      {
                          timestamp: Math.round(new Date().getTime() / 1000),
                          value: 0.7,
                      },
                  ],
              },
          ],
      },
      contentEncoding: "zstd1",
  };

  apiInstance.submitMetrics(params).then((data: v2.IntakePayloadAccepted) => {
    console.log(
      "API called successfully. Returned data: " + JSON.stringify(data)
    );
  }).catch((error: any) => console.error(error));
}

main();

Configure proxy

You can provide custom HttpLibrary implementation with proxy support to configuration object. See example below:

import pako from "pako";
import bufferFrom from "buffer-from";
import fetch from "node-fetch";
import { HttpsProxyAgent } from "https-proxy-agent";
import { v1, client } from "@datadog/datadog-api-client";

const proxyAgent = new HttpsProxyAgent('http://127.0.0.11:3128');

class HttpLibraryWithProxy implements client.HttpLibrary {
    public debug = false;

    public send(request: client.RequestContext): Promise<client.ResponseContext> {
        const method = request.getHttpMethod().toString();
        let body = request.getBody();

        let compress = request.getHttpConfig().compress;
        if (compress === undefined) {
            compress = true;
        }

        const headers = request.getHeaders();
        if (typeof body === "string") {
            if (headers["Content-Encoding"] === "gzip") {
                body = bufferFrom(pako.gzip(body).buffer);
            } else if (headers["Content-Encoding"] === "deflate") {
                body = bufferFrom(pako.deflate(body).buffer);
            }
        }

        const resultPromise = fetch(request.getUrl(), {
            method: method,
            body: body as any,
            headers: headers,
            signal: request.getHttpConfig().signal,
            compress: compress,
            agent: proxyAgent,
        }).then((resp: any) => {
            const headers: { [name: string]: string } = {};
            resp.headers.forEach((value: string, name: string) => {
                headers[name] = value;
            });

            const body = {
                text: () => resp.text(),
                binary: () => resp.buffer(),
            };
            const response = new client.ResponseContext(resp.status, headers, body);
            return response;
        });

        return resultPromise;
    }
}

const configuration = client.createConfiguration({httpApi: new HttpLibraryWithProxy()});
const apiInstance = new v1.DashboardsApi(configuration);

apiInstance
    .listDashboards()
    .then((data: v1.DashboardSummary) => {
        console.log(
            "API called successfully. Returned data: " + JSON.stringify(data)
        );
    })
    .catch((error: any) => console.error(error));

Documentation

Documentation for API endpoints can be found in GitHub pages.

Contributing

As most of the code in this repository is generated, we will only accept PRs for files that are not modified by our code-generation machinery (changes to the generated files would get overwritten). We happily accept contributions to files that are not autogenerated, such as tests and development tooling.

Author

[email protected]

License

Apache License, v2.0

datadog-api-client-typescript's People

Contributors

ad-m avatar antonio-ramadas-dd avatar api-clients-generation-pipeline[bot] avatar bodograumann avatar chibat avatar dependabot[bot] avatar etnbrd avatar hantingzhang2 avatar jirikuncar avatar juan-fernandez avatar jybp avatar ksvirkou-hubspot avatar macjohnny avatar nathanbaulch avatar nevon avatar nkzou avatar nmuesch avatar nouemankhal avatar skarimo avatar spacether avatar therve avatar tifu avatar tim-chaplin-dd avatar victorien-provenzano avatar wing328 avatar zippolyte avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

datadog-api-client-typescript's Issues

Error LogsApi

Describe the bug
I'm trying to dispatch a single log to DataDog and decided to use this official lib instead of doing it via HTTP.

Following the exact example given here I'm getting the current error:

TypeError: missing required attribute 'code' on 'HTTPLogError' object
    at Function.HTTPLogError.deserialize (.../node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v1/models/HTTPLogError.js:26:19)

To Reproduce
Follow exactly as described on DataDog website

Expected behavior
Event being dispatch, or at least a readable error.

Environment and Versions (please complete the following information):
A clear and precise description of your setup:

  • ^1.0.0-beta.5
  • node v14.18.0

Additional context
Seems this package is in it's early development, shall I use something else?

Thank you

HostsApi method listHosts results in a deserialization error

Describe the bug
The listHosts function fails to deserialize the response, resulting in the following error:

TypeError: unknown type 'string'
at Function.ObjectSerializer.deserialize (/Users/graph-datadog/node_modules/@datadog/datadog-api-client/packages/datadog-api-client-v1/models/ObjectSerializer.ts:2163:15)
at Function.ObjectSerializer.deserialize (/Users/graph-datadog/node_modules/@datadog/datadog-api-client/packages/datadog-api-client-v1/models/ObjectSerializer.ts:2105:28)
at Function.ObjectSerializer.deserialize (/Users/graph-datadog/node_modules/@datadog/datadog-api-client/packages/datadog-api-client-v1/models/ObjectSerializer.ts:2171:52)
at Function.ObjectSerializer.deserialize (/Users/graph-datadog/node_modules/@datadog/datadog-api-client/packages/datadog-api-client-v1/models/ObjectSerializer.ts:2171:52)
at Function.ObjectSerializer.deserialize (/Users/graph-datadog/node_modules/@datadog/datadog-api-client/packages/datadog-api-client-v1/models/ObjectSerializer.ts:2105:28)
at Function.ObjectSerializer.deserialize (/Users/graph-datadog/node_modules/@datadog/datadog-api-client/packages/datadog-api-client-v1/models/ObjectSerializer.ts:2171:52)
at HostsApiResponseProcessor.<anonymous> (/Users/graph-datadog/node_modules/@datadog/datadog-api-client/packages/datadog-api-client-v1/apis/HostsApi.ts:312:38)
at step (/Users/graph-datadog/node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v1/apis/HostsApi.js:48:23)
at Object.next (/Users/graph-datadog/node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v1/apis/HostsApi.js:29:53)
at fulfilled (/Users/graph-datadog/node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v1/apis/HostsApi.js:20:58)

To Reproduce
Steps to reproduce the behavior:

  1. Create file called hostTest.ts
  2. Add the following code:
import { client, v1 } from '@datadog/datadog-api-client';
import fetch from "node-fetch"


(async () => {
  const configuration = client.createConfiguration({
    authMethods: {
      apiKeyAuth: 'xxx',
      appKeyAuth: 'xxx',
    },
    debug: true,
  });

  client.setServerVariables(configuration, {
    site: 'us5.datadoghq.com',
  });

  const a = new v1.HostsApi(configuration);
  const r = await a.listHosts().catch(e => console.error(e))

  console.log(r)

  // Using node-fetch

  const nodeR = await fetch(
    'https://api.us5.datadoghq.com/api/v1/hosts', 
    { 
      method: 'GET', 
      headers: {
        Accept: 'application/json',
        "DD-API-KEY": 'xxx',
        "DD-APPLICATION-KEY": 'xxx'
      }
    })
  console.log(await nodeR.json())

})();
  1. Execute with ts-node (provide dependencies)

Expected behavior
I expect to receive back an object with hosts similar to what node-fetch produces.

Screenshots
If applicable, add screenshots to help explain your problem.

Environment and Versions (please complete the following information):
Using node v14
Using @datadog/[email protected]
MacOS Ventura 13.1

Additional context
Add any other context about the problem here.

createEvent message returns error "The mediaType text/plain is not supported by ObjectSerializer.parse"

Running the Typescript create event example from api/latest/events documentation results in the following error:

Error: The mediaType text/plain is not supported by ObjectSerializer.parse.
    at Function.ObjectSerializer.parse (C:\Users\kat\projects\utilities\restart-mvis-accounts\node_modules\@datadog\datadog-api-client\dist\packages\datadog-api-client-v1\models\ObjectSerializer.js:1779:15)
    at EventsApiResponseProcessor.<anonymous> (C:\Users\kat\projects\utilities\restart-mvis-accounts\node_modules\@datadog\datadog-api-client\dist\packages\datadog-api-client-v1\apis\EventsApi.js:275:51)
    at step (C:\Users\kat\projects\utilities\restart-mvis-accounts\node_modules\@datadog\datadog-api-client\dist\packages\datadog-api-client-v1\apis\EventsApi.js:46:23)
    at Object.next (C:\Users\kat\projects\utilities\restart-mvis-accounts\node_modules\@datadog\datadog-api-client\dist\packages\datadog-api-client-v1\apis\EventsApi.js:27:53)
    at fulfilled (C:\Users\kat\projects\utilities\restart-mvis-accounts\node_modules\@datadog\datadog-api-client\dist\packages\datadog-api-client-v1\apis\EventsApi.js:18:58)
    at processTicksAndRejections (internal/process/task_queues.js:95:5)

To Reproduce
This is the example from the documentation:

"use strict";
exports.__esModule = true;
process.env.DD_API_KEY = 'redacted';
process.env.DD_SITE = 'datadoghq.com';
process.env.DD_AP_KEY = 'redacted';
var datadog_api_client_1 = require("@datadog/datadog-api-client");
var configuration = datadog_api_client_1.v1.createConfiguration();
var apiInstance = new datadog_api_client_1.v1.EventsApi(configuration);
var params = {
    // EventCreateRequest | Event request object
    body: {
        aggregationKey: 'aggregationKey_example',
        alertType: 'info',
        dateHappened: 1,
        deviceName: 'deviceName_example',
        host: 'host_example',
        priority: 'normal',
        relatedEventId: 1,
        sourceTypeName: 'sourceTypeName_example',
        tags: ['environment:test'],
        text: 'Oh boy!',
        title: 'Did you hear the news today?'
    },
};
apiInstance
    .createEvent(params)
    .then(function (data) {
    console.log("API called successfully. Returned data: ".concat(JSON.stringify(data)));
})["catch"](function (error) { return console.error(error); });

Environment and Versions (please complete the following information):

  • Version: 1.0.0-beta.6
  • Node: v14.18.1
  • OS: Windows 10

Circular dependency with 1.0.0-beta.9

Describe the bug
When consuming @datadog/[email protected] using rollup commonjs + node-resolve plugins a circular dependency is raised from the @datadog/datadog-api-client package. Replication steps to follow below

./node_modules/.bin/rollup -c rollup.config.js

index.js → dist/index.mjs...
(!) Circular dependencies
node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v1/http/http.js -> node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v1/http/isomorphic-fetch.js -> node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v1/http/http.js
node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v1/http/http.js -> node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v1/http/isomorphic-fetch.js -> /home/projects/nextjs-w4drlq/node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v1/http/http.js?commonjs-proxy -> node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v1/http/http.js
node_modules/@datadog/datadog-api-client/dist/index.js -> node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v1/index.js -> node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v1/apis/AWSIntegrationApi.js -> node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v1/models/ObjectSerializer.js -> node_modules/@datadog/datadog-api-client/dist/index.js
...and 12 more
created dist/index.mjs in 34.6s

To Reproduce
Steps to reproduce the behavior:

  1. open stackblitz https://stackblitz.com/edit/nextjs-w4drlq?file=rollup.config.js
  2. open a terminal in stackblitz linked above
  3. run npm install
  4. run ./node_modules/.bin/rollup -c rollup.config.js
  5. observe circular dependency in terminal after waiting for a few seconds to build

Expected behavior
Expect that rollup is able to complete a build with no circular dependency errors

Screenshots
N/A

Environment and Versions (please complete the following information):
A clear and precise description of your setup:

    "@datadog/datadog-api-client": "^1.0.0-beta.9",
    "@rollup/plugin-commonjs": "^21.0.3",
    "@rollup/plugin-node-resolve": "^13.1.3",
    "rollup": "^2.70.1"

Additional context
N/A

criticalRecovery and warningRecovery always fail for `createMonitor`

Describe the bug
This is a problem with the backend, but I cannot find the right repo.

I have a project with the following monitor, exported directly from the UI:

  type: MonitorType.QUERY_ALERT,
  query: `avg(last_1d):anomalies(max:system.cpu.user{env:${enviro},service:${monitor.service}} by {host}, 'agile', 2, direction='both', interval=300, alert_window='last_1h', count_default_zero='true', seasonality='weekly') > 0.5`,
  message: `[${monitor.service}] CPU usage is too high.`,
  options: {
    thresholds: {
      critical: 0.5,
      criticalRecovery: 0.25,
      warning: 0.2,
      warningRecovery: 0.1,
    },

For this use case the API monitorsApi.createMonitor always returns:

"error": {
      "code": 400,
      "body": {
        "errors": [
          "alert and alert recovery criteria are such that the monitor can be simultaneously in alert and alert recovery states"
        ]
      }
    }

No matter what values I put in criticalRecovery and warningRecovery both always error.

To Reproduce
Steps to reproduce the behavior:

  1. Using the API
  2. Create a QUERY_ALERT monitor with criticalRecovery and warningRecovery
  3. Request createMonitor
  4. See error

Expected behavior
These values should be accepted, as they match the website's.

Environment and Versions (please complete the following information):
"@datadog/datadog-api-client": "^1.0.0",

Additional context
This is a backend problem, the error happens after the request goes through. I'd be happy to forward it to the corresponding repo.

Document how to configure timeouts for api requests

Is your feature request related to a problem? Please describe.
We look for how to configure timeouts on clients but we cannot find documentation.

Describe the solution you'd like
Describe how to configure timeouts for api requests

Describe alternatives you've considered
Or document what timeout is set automatically

Additional context
Shrug

Documentation: add missing word in "Unstable Endpoints" section to add clarity

Describe the bug
Currently, in the "Unstable Endpoints" section, one word is missing. https://datadoghq.dev/datadog-api-client-typescript/#unstable-endpoints
It reads: where is the name of the method used to interact with that endpoint.
I believe it should say: where <operationName> is the name of the method used to interact with that endpoint.
Making this change would make the instructions clearer for new users.

Label the issue properly.

  • Add severity/ label.
  • Add documentation label if this issue is related to documentation changes.

I don't have permission to add a label, but this should have the documentation label

Since this is a small documentation change, would you be ok with me submitting a PR without setting up a dev environment/running tests? If so, I'll happily submit a PR to add the missing word.

Module '@datadog/datadog-api-client' has no exported member 'client'

Describe the bug
After the recent update to the ts datadog-api-client library, typescript build fails with Module '@datadog/datadog-api-client' has no exported member 'client'

This library has been running in production for some time with no issues. After update now build fails.

  • Severity: High - blocking builds.

To Reproduce
I placed this code in the header of my file:

import { client, v1 } from '@datadog/datadog-api-client'

And build fails with Module '@datadog/datadog-api-client' has no exported member 'client'

After attempting to get authentication working again first, I get this error:
image

Expected behavior
It is expected that the library will import and instantiate correctly as it did before.

Screenshots
image

Environment and Versions (please complete the following information):
A clear and precise description of your setup:

  • Version 1.0.0
  • Node: 16.14.2
  • Npm: 8.10

Type Error when submitting logs

Describe the bug
When trying to submit a log I receive a type error

To Reproduce
Follow the example from the docs.

import { v1 } from "@datadog/datadog-api-client";

const configuration = v1.createConfiguration();
      const apiInstance = new v1.LogsApi(configuration);

      let params: v1.LogsApiSubmitLogRequest = {
        // Array<HTTPLogItem> | Log to send (JSON format).
        body: [
          {
            ddsource: "nginx",
            ddtags: "env:staging,version:5.1",
            hostname: "i-012345678",
            message:
              "2019-11-19T14:37:58,995 INFO [process.name][20081] Hello World",
            service: "payment",
          },
          {
            ddsource: "nginx",
            ddtags: "env:staging,version:5.1",
            hostname: "i-012345678",
            message:
              "2019-11-19T14:37:58,995 INFO [process.name][20081] Hello World",
            service: "payment",
          },
        ],
        // ContentEncoding | HTTP header used to compress the media-type. (optional)
        contentEncoding: "gzip",
        // string | Log tags can be passed as query parameters with `text/plain` content type. (optional)
        ddtags: "env:prod,user:my-user",
      };

      apiInstance
        .submitLog(params)
        .then((data: any) => {
          console.log(
            "API called successfully. Returned data: " + JSON.stringify(data)
          );
        })
        .catch((error: any) => console.error(error));

I receive the following type error when the code is called.

TypeError: missing required attribute 'code' on 'HTTPLogError' object

Expected behavior
I expect the example code should run without an error, or the docs need to be updated to show a working example.

Environment and Versions (please complete the following information):

  • @datadog/datadog-api-client 1.0.0-beta.5
  • nodejs v14.15.1

Package size

Yo datadoggers, how's it going?

Is there any way to avoid that big package size?

image

I am deploying on lambda which runs on size constraints, and even by stripping away *.map and *.d.ts there's still 10mb of diet to do 🤷🏻

For now I'm replacing calls to the SDK with raw HTTP requests. However, I wanted to share that feedback because it makes the usage of the native TS SDK very prohibitive.

Error when getting dashboard with v1 API

Describe the bug
Getting an error when calling to get a dashboard using new v1.DashboardsApi(config).getDashboard({dashboardId})

Error: missing required property 'definition'
    at Function.ObjectSerializer.deserialize (/Users/taylorwebber/Projects/slackcat/node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v1/models/ObjectSerializer.js:1713:27)
    at Function.ObjectSerializer.deserialize (/Users/taylorwebber/Projects/slackcat/node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v1/models/ObjectSerializer.js:1657:55)
    at Function.ObjectSerializer.deserialize (/Users/taylorwebber/Projects/slackcat/node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v1/models/ObjectSerializer.js:1708:60)
    at DashboardsApiResponseProcessor.<anonymous> (/Users/taylorwebber/Projects/slackcat/node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v1/apis/DashboardsApi.js:639:38)
    at step (/Users/taylorwebber/Projects/slackcat/node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v1/apis/DashboardsApi.js:46:23)
    at Object.next (/Users/taylorwebber/Projects/slackcat/node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v1/apis/DashboardsApi.js:27:53)
    at fulfilled (/Users/taylorwebber/Projects/slackcat/node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v1/apis/DashboardsApi.js:18:58)

I believe it is a validation error related to the definition within the widgets array on the dashboard.

When I go to the dashboard and export the JSON manually or use curl to pull the data, the JSON is returned successfully and all the widgets returned have a definition property

To Reproduce
Steps to reproduce the behavior:

  1. Use v1.0.0-beta.6 of library
  2. Call to get dashboard
  3. Error thrown on request

Expected behavior
Return JSON of dashboard

Environment and Versions (please complete the following information):
Using version 1.0.0-beta.6 of @datadog/datadog-api-client

Request returns empty 429

There seems to be an internal Datadog bug
We are seeing the log messages: Got error deserializing error: Error: missing required property 'errors' coming from Datadog SDK, it seems to happen when our api calls returns 429

The error code body returned is empty:

HTTP-Code: 429
Message: ""

it seems like an internal issue where DD expects to have errors property for this error but doesn't

FetchError: request to https://api.datadoghq.com/api/v1/series failed

Hello! I am trying to send custom metrics to DataDog from the Google Cloud function. The code is like:

const params = {
	body: {
		series: [
			{
				metric: name,
				type: "count",
				points: [ [ new Date().getTime() / 1000, 1 ] ],
				tags: [
					`env:${process.env.NODE_ENV}`
				],
			},
		],
	},
};

apiInstance
	.submitMetrics(params)
	.catch((error) => logger.warn(`Cannot post custom ${name} to DataDog`, error));

The problem is that I receive many errors like
FetchError: request to https://api.datadoghq.com/api/v1/series failed, reason: connect ETIMEDOUT 3.233.147.157:443

and I see many such errors! So, some of the requests are successful and some cause an error. Why do I see such an issue? Thanks.

export v1 ObjectSerializer

Is your feature request related to a problem? Please describe.
This might be a bit outside of the intended use of this library, but could make it much more useful.
I'm building a CDK library that uses the exported models to add proper typing. In the i need to serialize those objects again to json. There is already the ObjectSerializer.ts which does exactly that, but its not exported as the models from the same folder, so i can't reuse this.

Describe the solution you'd like
Export the ObjectSerializer at https://github.com/DataDog/datadog-api-client-typescript/blob/master/packages/datadog-api-client-v1/models/ObjectSerializer.ts#L1807 to make it usable from outside of this library.

Describe alternatives you've considered
The workaround would be to copy that serializer into my code, but that will be a dependency nightmare, as the code seems to be generated.

Additional context
Add any other context or screenshots about the feature request here.

DataScalarColumn.values should be Array<number | null>

Describe the bug

v2.DataScalarColumn.items type should be values: Array<number | null> (currently: values?: Array<number>).

Example

I'm querying with datadog.v2.MetricsApi.queryScalarData with 2 queries (in body.data.attributs.queries):

  1. sum:my_metric{tag:a} by {group_tag}
  2. sum:my_metric{tag:b} by {group_tag}

then assigning the result into:

const [colGroup, colA, colB] = response.data!.attributes!.columns as [
  datadog.v2.GroupScalarColumn,
  datadog.v2.DataScalarColumn,
  datadog.v2.DataScalarColumn,
];

In some of the "rows" (for some group_tags), there's zero tag:as, which makes colA[i] === null but the type annotation does not document that.

Versions:

  • @datadog/datadog-api-client: 1.16.0

Cannot use in Workers because of `process` in userAgent.ts

Describe the bug

I tried running this in a Worker using both Miniflare & Wrangler and they crashed with ReferenceError: process is not defined

The stack traces point to

export const userAgent = `datadog-api-client-typescript/${version} (node ${process.versions.node}; os ${os.type()}; arch ${os.arch()})`

To Reproduce
Steps to reproduce the behavior:

  1. npm install @datadog/datadog-api-client
  2. import & use like:
    import { v1 } from '@datadog/datadog-api-client';
    const configuration = v1.createConfiguration();
    const apiInstance = new v1.LogsApi(configuration);
    
  3. build site (miniflare dev or wrangler dev
  4. observe ReferenceError: process is not defined and process exit

Expected behavior
library functions won't crash

  • if the node version cannot be determined
  • if process is missing (e.g. #494)

I wasn't sure what the changes to the UA string should be

  • Add workers or some other info about the runtime?
  • only add that if there is a node version
  • something else

Environment and Versions (please complete the following information):
A clear and precise description of your setup:

NPM and yarn installs don't work - Module '"@datadog/datadog-api-client"' has no exported member 'client' | Property 'RUMApi' does not exist on type 'typeof import

Describe the bug

I'm getting error Property 'RUMApi' does not exist on type 'typeof import when I try to follow the documentation, it also happens with client. I tried installed via both NPM and yarn but it's the same problem

To Reproduce

It's an issue in 2 different cases:

Case 1 (clientConfiguration):

import { client, v2 } from "@datadog/datadog-api-client";

const configuration = client.createConfiguration();
const apiInstance = new v2.RUMApi(configuration);

apiInstance
  .listRUMEvents()
  .then((data: v2.RUMEventsResponse) => {
    console.log(
      "API called successfully. Returned data: " + JSON.stringify(data)
    );
  })
  .catch((error: any) => console.error(error));

I get both errors: Module '"@datadog/datadog-api-client"' has no exported member 'client' AND Property 'RUMApi' does not exist on type 'typeof import

Case 2:

import { v2 } from "@datadog/datadog-api-client";

// API creds
const configurationOpts = {
  authMethods: {
    apiKeyAuth: "API_KEY",
    appKeyAuth: "APP_KEY"
  },
};

// set up config
const configuration = v2.createConfiguration(configurationOpts);
const apiInstance = new v2.RUMApi(configuration);

apiInstance
  .listRUMEvents()
  .then((data: v2.RUMEventsResponse) => {
    console.log(
      "API called successfully. Returned data: " + JSON.stringify(data)
    );
  })
  .catch((error: any) => console.error(error));

I only get Property 'RUMApi' does not exist on type 'typeof import

Expected behavior
I get no errors

Environment and Versions (please complete the following information):
A clear and precise description of your setup:

windows
node v14.6.0
yarn 1.22.18

Additional context

how do you fix this?

Allow multiple clients to different site (don't rely on global state)

We have a SaaS platform where we are interested in collecting metrics for more than one Datadog account; for example, we may want to collect our own metrics for internal use, but also send some metrics about jobs to our customers' Datadog accounts.

The problem is that this package implements server configuration as a singleton, in global state. If our internal config and the customer config have different values for the {site} server variable, then setting the value for one will override it in the global state maintained by the API's servers, here.

It would be much more convenient if this state were encapsulated in the client object rather than maintained globally (maybe with global state as the default and for backwards compatibility?). From a crass commercial perspective, it would also help us send Datadog more billable metrics… ;-)

FetchError: client socket disconnected before secure TLS connection is established

Describe the bug
I keep intermittently running into this error which seems to be originating inside node-fetch when calling v1.LogsApi.submitLog method. I am curious if someone here might know what's happening?

Error:

FetchError: request to https://http-intake.logs.datadoghq.com/v1/input failed, reason: Client network socket disconnected before secure TLS connection was established

Stack trace:

at ClientRequest.<anonymous> (node_modules/node-fetch/lib/index.js:1491:11)
    at ClientRequest.emit (node:events:394:28)
    at ClientRequest.emit (node:domain:475:12)
    at TLSSocket.socketErrorListener (node:_http_client:447:9)
    at TLSSocket.emit (node:events:394:28)
    at TLSSocket.emit (node:domain:475:12)
    at emitErrorNT (node:internal/streams/destroy:157:8)
    at emitErrorCloseNT (node:internal/streams/destroy:122:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)

@datadog/datadog-api-client - v1.4.0
node - v16.8.0

Log Aggregate API doesn't support Integer facets on group_by expression

Describe the bug
The API client is erroring out when attempting to do a group_by facet on an Integer. It appears the API from Datadog is returning the right result, but the API client is parsing it wrong and producing an error.

To Reproduce

  1. Have your service output JSON logs that contain a number field.
  2. Create a facet on that number field with the type "Integer".
  3. Make an API call to the logs aggregation endpoint, with a group_by set with that integer field as the facet.

I then get the following error: /Users/bradley/slash2/common/temp/node_modules/.pnpm/@DataDog[email protected]/node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v2/models/ObjectSerializer.js:1550
throw new TypeError(unknown type '${type}');
^

TypeError: unknown type 'string'
at ObjectSerializer.deserialize (/Users/bradley/slash2/common/temp/node_modules/.pnpm/@DataDog[email protected]/node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v2/models/ObjectSerializer.js:1550:23)
at ObjectSerializer.deserialize (/Users/bradley/slash2/common/temp/node_modules/.pnpm/@DataDog[email protected]/node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v2/models/ObjectSerializer.js:1518:57)
at ObjectSerializer.deserialize (/Users/bradley/slash2/common/temp/node_modules/.pnpm/@DataDog[email protected]/node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v2/models/ObjectSerializer.js:1556:60)
at ObjectSerializer.deserialize (/Users/bradley/slash2/common/temp/node_modules/.pnpm/@DataDog[email protected]/node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v2/models/ObjectSerializer.js:1498:55)
at ObjectSerializer.deserialize (/Users/bradley/slash2/common/temp/node_modules/.pnpm/@DataDog[email protected]/node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v2/models/ObjectSerializer.js:1556:60)
at ObjectSerializer.deserialize (/Users/bradley/slash2/common/temp/node_modules/.pnpm/@DataDog[email protected]/node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v2/models/ObjectSerializer.js:1556:60)
at LogsApiResponseProcessor. (/Users/bradley/slash2/common/temp/node_modules/.pnpm/@DataDog[email protected]/node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v2/apis/LogsApi.js:177:66)
at Generator.next ()
at fulfilled (/Users/bradley/slash2/common/temp/node_modules/.pnpm/@DataDog[email protected]/node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v2/apis/LogsApi.js:5:58)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

After tracing several of the internals of the library at the lines given in the stacktrace, I determined that the code is attempting to parse an integer as if it were a string.

Specifically, the condition on this code is failing:
else if (primitives.includes(type.toLowerCase()) &&
typeof data == type.toLowerCase()) {
return data;
}

Because typeof data is "number", but type is "string", it simply fails to parse this result.

Expected behavior
Code returns the faceted aggregate results, the same way the UI does.

Environment and Versions (please complete the following information):

API client is version 1.6.0
Using a pure JS script, NodeJS v18.9.0.

apiInstance.queryScalarData does not support Percentile as Aggregator

Describe the bug
Query Scalar Data Request does not support Percentile as Aggregator, when the Scalar API supports it

It is supported in Datadog Dashboard
Screen Shot 2023-02-10 at 10 23 53

It is supported by direct call to Scalar API
Screen Shot 2023-02-10 at 10 25 23

But It is not supported using Library, because the v2.MetricsApiQueryScalarDataRequest is enumerating the aggregator but without percentile as options

export type MetricsAggregator =
| typeof AVG
| typeof MIN
| typeof MAX
| typeof SUM
| typeof LAST
| UnparsedObject;
export const AVG = "avg";
export const MIN = "min";
export const MAX = "max";
export const SUM = "sum";
export const LAST = "last";

To Reproduce
This will be compilation error, because the aggregator can only be avg, max, min, sum, last

const params: v2.MetricsApiQueryScalarDataRequest = {
  body: {
    data: {
      attributes: {
        formulas: [
          {
            formula: "a",
            limit: {
              count: 10,
              order: "desc",
            },
          },
        ],
        from: 1671612804000,
        queries: [
          {
            aggregator: "percentile",
            dataSource: "metrics",
            query: "p99:system.cpu.user{*}",
            name: "a",
          },
        ],
        to: 1671620004000,
      },
      type: "scalar_request",
    },
  },
};

Expected behavior
Percentile should be accepted

Screenshots
Screenshots added above

Environment and Versions (please complete the following information):

  • version for this project in use: "@datadog/datadog-api-client": "1.9.0",
  • services, libraries, languages and tools list and versions: typescript

Additional context
n.a.

Error creating notebook with timeseries widget with multiple queries

Describe the bug
Basically I was creating a notebook with some timeseries widgets everything was fine until I tried to use multiple queries to have multiple lines in one widget, I checked the types, the error that came back from the API, the spec from the documentation and couldn't figure out what the issue was, so I created this small repo that's simple enough to reproduce it:

https://github.com/gg-mural/poc-timeseries-widget

Label the issue properly.

  • Add severity/ label.
  • Add documentation label if this issue is related to documentation changes.

To Reproduce
Steps to reproduce the behavior:

  1. Clone this repo: https://github.com/gg-mural/poc-timeseries-widget
  2. Run npm i
  3. Run DD_API_KEY="your-key" DD_APP_KEY="your-app-key" npx ts-node PoC.ts
  4. See error

Expected behavior
A notebook with a timeseries widget with 2 lines is created.

Screenshots
If applicable, add screenshots to help explain your problem.

Environment and Versions (please complete the following information):
A clear and precise description of your setup:

@datadog/datadog-api-client: "^1.0.0-beta.7"

typescript version 4.5.5

Additional context
Add any other context about the problem here.

dateToRFC3339String produces invalid dates

Describe the bug

My time zone is Hawaii. The offset is -10:00. One of my fixtures includes this date string: 2023-06-13T11:30:48-10:00 (equivalent to 2023-06-13T21:30:48.000Z). The timestamp breaks anything using the date or date-time object serializer dateToRFC3339String function. The serialized form is: 2023-06-13T31:30:48+10:00. Note the hour 31. The Datadog API returns a 400 Bad Request with an error on the relevant parameter.

To Reproduce
Steps to reproduce the behavior:

  1. Instantiate a date with hour 11 and offset -10
  2. Use that date for any date or date-time serialized parameter (I used start_date with V2 Estimated Cost by Org)
  3. Observe a 400 response from the Datadog API

Expected behavior

Dates in any time zone serialize properly.

Screenshots

Not/Applicable.

Environment and Versions (please complete the following information):

  • Node: v16.19.0
  • datadog-api: 1.10.10

Additional context

I think the problem is here. This causes the hour wrap around when the UTC hour plus offset exceeds 24. My test date is UTC hour 21 plus the offset (10) comes out to 31.

I don't understand why date components (ymd, hour/minute/seconds, etc) are pulled in UTC, then manipulated again by the offset. It seems easier to return something without the offset at this point.

Also, the API docs state the format is ISO860 but the code does not use it.

APIException HTTP-code: 429

Describe the bug
Sometimes when querying the metric API I get this 429 exception error.

To Reproduce
Hard to reproduce as this is inconsistent but basically trying to query a specific metric will sometimes ( often ) result in this error.

Expected behavior
To not run into this error

Screenshots
https://imgur.com/a/sbisC90

Environment and Versions (please complete the following information):
A clear and precise description of your setup:
Package version:
"@datadog/datadog-api-client": "^1.3.0",

Additional context
Query:


    apiInstance
      .queryMetrics(params)
      .then((data: v1.MetricsQueryResponse) => {
     return data
      })
      .catch((error) => console.error(error));

Uncatched API Exception in TeamsApi if StatusCode 403

Describe the bug

When trying to create teamMemberships with createTeamMembership even if surrounded by try catches like in

try {
        apiInstance.createTeamMembership(teamMembership);
      }
      catch (error) {
        throw new Error(`${error}`);
      }

The application is crashing with :

/workspace/node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v2/apis/TeamsApi.js:618
            throw new exception_1.ApiException(response.httpStatusCode, 'Unknown API Status Code!\nBody: "' + body + '"');
                  ^

ApiException [Error]: HTTP-Code: 403
Message: "Unknown API Status Code!\nBody: \"{\"errors\":[\"You do not have permission to do this.\"]}\""
    at TeamsApiResponseProcessor.<anonymous> (/workspace/node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v2/apis/TeamsApi.js:618:19)
    at Generator.next (<anonymous>)
    at fulfilled (/workspace/node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v2/apis/TeamsApi.js:5:58)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  code: 403,
  body: 'Unknown API Status Code!\n' +
    'Body: "{"errors":["You do not have permission to do this."]}"'
}

Node.js v18.16.1

To Reproduce
Steps to reproduce the behavior:

  1. Create a proper TeamsApiCreateTeamMembershipRequest like
{
    "body": {
        "data": {
            "attributes": {
                "role": "admin"
            },
            "relationships": {
                "user": {
                    "data": {
                        "id": "AN EXISTING USER ID",
                        "type": "users"
                    }
                }
            },
            "type": "team_memberships"
        }
    },
    "teamId": "AN EXISTING TEAM ID"
}
  1. Perform a createTeamMembership request with the said params

Expected behavior
I would expect the exception to be catched and not crashing the application.
Also the error message says Unknown API Status Code! while 403 is a known one

Environment and Versions (please complete the following information):
"@datadog/datadog-api-client": "^1.13.0",
Node.js v18.16.1

Additional context
The app key used misses some rights to perform that operation. It is known, I'm just talking about the API Exception management

Postmortems return as `undefined` with `.getIncident()`

Describe the bug
When using .getIncident() the data.data.relationships.postmortem and data.data.attributes.postmortemId attributes are undefined even when a postmortem is attached to the incident.

I've also opened a support request for this 653993

To Reproduce

  1. Create an incident in datadog, resolve it, and then generate a postmortem document to it.
  2. run the following code, assuming the incident you created was incident-29.
import { v2 } from "@datadog/datadog-api-client";

const configuration = v2.createConfiguration();
const apiInstance = new v2.IncidentsApi(configuration);
const params: v2.IncidentsApiGetIncidentRequest = {
    incidentId: 29,
};

apiInstance
.getIncident(params)
.then(async (data: any) => {
	console.log(data.data.relationships);
	console.log(data.data.attributes);
});

Expected behavior
I get the postmortem response as defined here.

Environment and Versions (please complete the following information):
"@datadog/datadog-api-client": "^1.0.0-beta.6"
Using node docker: node:lts-buster

List logs from Historical index

Is your feature request related to a problem? Please describe.
I cannot list logs in a historical index with API listLogsGet()

Describe the solution you'd like
I hope listLogsGet() works with historical indexes

Is there anyway to list logs in a historical index with APIs?

Thanks very much !

v1.searchSLO SearchSLOResponse does not match actual API response

Describe the bug

  • Cannot use searchSLO without enabling "unstableOperations" (which doesn't seem to be documented anywhere).
  • The typescript types and parsing of the API response does not match what the actual API returns. For example, the api response is "data.attributes.slos" whereas the SearchSLOResponse has "data.attributes.slo".
  • SearchSLOResponse "data.attributes.unparsedObject" is undefined.
  • etc

Label the issue properly.

This api is unusable as a result of this bug.

To Reproduce
Steps to reproduce the behavior:

Use the typescript project to search for an SLO and use the response.

Expected behavior
SearchSLOResponse should have all properties populated and match the actual response from the API.

Screenshots
Screen Shot 2022-09-27 at 10 47 36 AM

Environment and Versions (please complete the following information):

  • "typescript": "^4.8.3"
  • "@datadog/datadog-api-client": "^1.3.0"

Uncaught Exceptions When Initializing Client

Uncaught exceptions in DatadogLibrary when trying to initialize api clients.

Label the issue properly.

  • Add severity/ label.
  • Add documentation label if this issue is related to documentation changes.

To Reproduce
Steps to reproduce the behavior:

  1. Create a new react app: npx create-react-app system-status-display --template typescript
  2. Install the data dog client: npm install @datadog/datadog-api-client
  3. Create a Datadog.ts file like this:
    import { v1 } from "@datadog/datadog-api-client"; import { ConfigurationParameters } from "@datadog/datadog-api-client/dist/packages/datadog-api-client-v1/configuration"; const configurationOptions:ConfigurationParameters = { //@ts-ignore debug: true, httpConfig:{ compress: false } } const configurtion = v1.createConfiguration(configurationOptions); const apiInstance = new v1.SyntheticsApi(configurtion); export const getSyntheticTests = async ()=>{ let tests = await apiInstance.listTests(); return tests.tests; }
  4. Call the getSyntheticTestsMethod from App.tsx. Add this code inside the App component
    const getStuffFromDataDog = useEffect(()=>{ let serviceGroups:ServiceGroup[] = []; let apiServiceGroup: ServiceGroup = { name: "Apis", services: [] }; let datadogSynthetics = getSyntheticTests(); //set up x api stuff let belleXApiService: Service = { name: "X API", status:ServiceStatus.Good }; });
  5. When the Datadog client is initalized, I see this exception in the javascript console:

Uncaught ReferenceError: process is not defined
at Object../node_modules/@datadog/datadog-api-client/dist/userAgent.js (userAgent.ts:4)
at Object.options.factory (react refresh:6)
at webpack_require (bootstrap:24)
at fn (hot module replacement:61)
at Object../node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v1/http/http.js (http.ts:1)
at Object.options.factory (react refresh:6)
at webpack_require (bootstrap:24)
at fn (hot module replacement:61)
at Object../node_modules/@datadog/datadog-api-client/dist/packages/datadog-api-client-v1/index.js (index.ts:1)
at Object.options.factory (react refresh:6)

Expected behavior
DataDog api client should initialize and return the list of synthetic tests.

Environment and Versions (please complete the following information):
node js project in visual studio code on windows 10. Chrome Browser:

  • react
  • typescript
  • @datadog/datadog-api-client": "^1.0.0-beta.6

system-status-display.zip

Expose domain and endpoint list

Note:
If you have a feature request, you should contact support so the request can be properly tracked.

I have contacted support as well.

Is your feature request related to a problem? Please describe.
My team is building an OAuth 2.0 integration with Datadog. We will act as the client and Datadog will act as the authorization server. When the integration is kicked off from the Datadog UI your system sends a 'domain' and 'site' query parameter to our service indicating to what URL we should deliver our authorization code request payload.

We will be checking the URL implied by these parameters to verify that:

  • it is actually datadog

We will do this via an allow list.

I would like it to be possible to automatically generate this allow list by leveraging one of your programming language clients. That way we do not couple our system to following the release of new datadog endpoints.

AWS does this for example with their SDKs - users can automatically configure a client to a given 'region' without needing to know any particular details and if a URL comes from outside a system, that system can check the URL agains AWS's set.

Describe the solution you'd like
I would like the clients to expose URL validation capabilities that ensure a URL is a valid datadog URL.
Describe alternatives you've considered

  1. We will build an allow list ourselves until this is launched.A
  2. we will also rely on typescript as a fail safe since your client has type guards on configuring a client.
    (1) is stronger than (2) and so while we will do both I would stll like to automate this.

Additional context

I have an open support ticket for this request. The case ID is 1671182

Intermittent error querying metrics

Describe the bug
When calling v1.MetricsApi.queryMetrics() for 5 metrics over the last 5 minutes, most of the time I get a normal response, with the metric timeseries values if any.

However, for 30min-several hour windows, I instead get an exception:
Error: missing required property 'errors'
at Function.Object..ObjectSerializer.deserialize (C:\git\edge-management\node_src\node_modules@datadog\datadog-api-client\packages\datadog-api-client-v1\models\ObjectSerializer.ts:2178:17)
at MetricsApiResponseProcessor. (C:\git\edge-management\node_src\node_modules@datadog\datadog-api-client\packages\datadog-api-client-v1\apis\MetricsApi.ts:621:38)
at step (C:\git\edge-management\node_src\node_modules@datadog\datadog-api-client\dist\packages\datadog-api-client-v1\apis\MetricsApi.js:48:23)
at Object.next (C:\git\edge-management\node_src\node_modules@datadog\datadog-api-client\dist\packages\datadog-api-client-v1\apis\MetricsApi.js:29:53)
at fulfilled (C:\git\edge-management\node_src\node_modules@datadog\datadog-api-client\dist\packages\datadog-api-client-v1\apis\MetricsApi.js:20:58)
at processTicksAndRejections (internal/process/task_queues.js:95:5)

To Reproduce
Steps to reproduce the behavior:

Call v1.MetricsApi.queryMetrics() with valid credentials and params.
Usually I will get a response like:
image

however, during some windows I just get the Exception above, rather than any MetricsQueryResponse at all.
Nothing changes in the query params other than the fromData and toDate being calculated from the current time.

Environment and Versions (please complete the following information):
A clear and precise description of your setup:
I have reproduced the issue with 1.1.0 and 1.3.0, against the 'cytiva' organization.

alert_type should be status.

Describe the bug
The documentation for creating an Event specifies that we should set alert_type (in typescript alertType) to error, status, info, etc. However, this doesn't show up anywhere in the Event Explorer. Instead, if you add a property called status, then that's what shows up in the Event explorer. However, status isn't part of the Typescript definition file, so it registers as an error unless set using event["status"] notation. Both the documentation and the Typescript definitions should be updated. Or maybe the actual createEvent api at DataDog needs to be updated?

To Reproduce
Steps to reproduce the behavior:

  1. Goto the Event explorer
  2. Post an event to the https://api.datadoghq.com/api/v1/events endpoint using alert_type and see it get ignored
  3. Post an event to the https://api.datadoghq.com/api/v1/events endpoint using the undocumented and untyped status and see it show up.

Expected behavior
I would expect the alert_type to appear somewhere, and barring that, I would expect the typescript definition files to include status instead of alert_type and I would expect the documentation to tell us to send status instead of alert_type

Environment and Versions (please complete the following information):
A clear and precise description of your setup:

  • version for this project in use.
  • Currently using "@datadog/datadog-api-client": "1.0.0" npm package along with the v1 Endpoints as described in the Documentation for Typescript.
  • services, libraries, languages and tools list and versions.
  • Typescript
  • NodeJS

Better typing for metric type and points

Metrics types can only be one of three values: 'count', 'rate' and 'gauge', but there is no type safety to validate that you are submitting proper values.

Points should be array of tuple (timestamp, value). This could be more strongly typed to catch bugs.

Typing Inconsistency for "v1.SearchSLOResponse" on GET /api/v1/slo endpoints

Describe the bug
Bad key typing on the v1.SearchSLOResponse typescript type for GET /api/v1/slo/search. Proper response type is in snake_case while intellisense suggests camelCase for the property type.

Example 1:

const type = sloData.data.attributes.slos[0].data.attributes?.sloType // actual property is `.slo_type`

Example 2:

const status = sloData.data.attributes.slos[0].data.attributes?.overallStatus // actual property is `.overall_status`

To Reproduce

  1. in a typescript environment create a GET request to https://api.datadoghq.com/api/v1/slo/search
  2. Ensure the response type is using v1.SearchSLOResponse
  3. View the response data and observe examples listed above within code-editors intellisense

Expected behavior

  • When using the property in code you should see a snake_case suggestion.

Screenshots
Screenshot 2023-12-19 at 3 01 46 PM

Environment and Versions (please complete the following information):

  • datadog/datadog-api-client version 1.19.0
  • Typescript

Proxy support

Is your feature request related to a problem? Please describe.
We want to use this library behind a proxy. Unfortunately it only provides the option to pass a whole new http client. But we only need to add a proxy.

Describe the solution you'd like
Allow passing a proxy agent.

Describe alternatives you've considered
Use some library that magically reads the http_proxy environment variables. This would work too, but the first solution would be a bit less magic for the user.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.