diff --git a/MIGRATION.md b/MIGRATION.md new file mode 100644 index 00000000000..9cb46ed4892 --- /dev/null +++ b/MIGRATION.md @@ -0,0 +1,150 @@ +# Migration Notes: Moving from v1 Client to Logically Grouped Packages + +This guide goes over how to migrate your code from using the monolithic `@datadog/datadog-api-client` package to the new logically grouped packages structure. + +## Major changes + +### Package structure changes +- The `@datadog/datadog-api-client` package now only contains core components and configuration objects. +- Service-specific code (e.g., `Monitor`) has been moved to individual packages in `services/` directory + - Each API grouping is in its own dedicated package following the naming convention `@datadog/datadog-api-client-{apiName}` + +### Configuration object updates +- `serverVariables`, `operationServerVariables` and `unstableOperation` keys in the configuration object now follow the same format: + + ``` + { apiName }.{ apiVersion }.{operation} + ``` + +## Migration steps + +### 1. Package installation + +Install the required packages: + +```bash +# Service-specific packages (install only the ones you need) +npm install @datadog/datadog-api-client-monitors +# OR +yarn add @datadog/datadog-api-client-monitors +# ... and so on for other services +``` + +All of the clients directly depend on the `@datadog/datadog-api-client` package for core components such as `Configuration` object. +You can manually install the client using: + +```bash +npm install @datadog/datadog-api-client@^2.0.0-beta.1 +# OR +yarn add @datadog/datadog-api-client@^2.0.0-beta.1 +``` + +### 2. Update core imports +Replace imports of core components from the main package: + +```typescript +// Old +import { client } from "@datadog/datadog-api-client"; + +const configuration = client.createConfiguration() +``` + +```typescript +// New +import { createConfiguration } from "@datadog/datadog-api-client"; + +const configuration = createConfiguration() +``` + +### 3. Update service specific imports +Update imports for service-specific models and APIs: + +```typescript +// Old +import { v1 } from "@datadog/datadog-api-client"; + +const apiInstance = new v1.MonitorsApi(); +``` + +```typescript +// New +import { v1 } from "@datadog/datadog-api-client-monitors"; + +const apiInstance = new v1.MonitorsApi(); +``` + +### 4. Update configuration +Update your configuration object to use the new format `{ apiName }.{ apiVersion }.{ operation }` + +```typescript +// Old +const configuration = createConfiguration({ + operationServerIndices: { + "v2.LogsApi.submitLog": 0 + }, + unstableOperations: { + "v2.createOpenAPI": true + } +}); +``` + +```typescript +// New +const configuration = createConfiguration({ + operationServerIndices: { + "LogsApi.v2.submitLog": 0 + }, + operationServerVariables: { + "LogsApi.v2.submitLog": { + "site": "datadoghq.eu" + } + }, + unstableOperations: { + "APIManagementApi.v2.createOpenAPI": true + } +}); +``` + +## Example migration + +Here's a complete example showing how to migrate a typical use case: + +```typescript +// Old +import { v1, client } from "@datadog/datadog-api-client"; + +const configuration = client.createConfiguration({ + authMethods: { + apiKeyAuth: "YOUR_API_KEY", + appKeyAuth: "YOUR_APP_KEY" + } +}); + +const api = new v1.MonitorsApi(configuration); +``` + +```typescript +// New +import { Configuration, createConfiguration } from "@datadog/datadog-api-client"; +import { v1 } from "@datadog/datadog-api-client-monitors"; + +const configuration = createConfiguration({ + authMethods: { + apiKeyAuth: "YOUR_API_KEY", + appKeyAuth: "YOUR_APP_KEY" + } +}); + +const api = new v1.MonitorsApi(configuration); +``` + +## Available service packages + +See [#Clients] section in the following [README.md](./packages/datadog-api-client/README.md#clients) + +## Support + +If you encounter any issues during migration, please: +1. Check the [API documentation](https://docs.datadoghq.com/api/) +2. Open an issue in the [GitHub repository](https://github.com/DataDog/datadog-api-client-typescript) +3. Contact [Datadog Support](https://www.datadoghq.com/support/) diff --git a/README.md b/README.md index 3c796e51cea..4d1a8a325c3 100644 --- a/README.md +++ b/README.md @@ -2,319 +2,42 @@ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) -This repository contains the V2 rewrite of the TypeScript API client for the [Datadog API](https://docs.datadoghq.com/api/). The client is organized into logical API groups for better maintainability and usability. +This repository contains the V2 rewrite of the TypeScript API client for the [Datadog API](https://docs.datadoghq.com/api/). The client is organized into logical API groups for better maintainability and usability. For supported APIs, see `services/` directory. + +See [MIGRATION.md](./MIGRATION.md) for migration details. ## How to install -For detailed installation instructions, please refer to the README.md file in each client's directory under `services/{client}/`. +For detailed installation instructions, please refer to the `README.md` file in each client's directory under `services/{client}/`. -## Getting Started +The shared package which contains the configuration object can be found in `packages/datadog-api-client` directory. -Here's an example getting a monitor: +## Migration -```typescript -import { v1 } from '@datadog/datadog-api-client-monitors'; +See migration docs [MIGRATION.md](packages/datadog-api-client/README.md) -const apiInstance = new v1.MonitorsApiV1(); +## Getting Started -let params: v1.MonitorsApiGetMonitorRequest = { - // number | The ID of the monitor - monitorId: 1, -}; +See individual `README.md` in `services/{api}/` and `packages/datadog-api-client/` directories. -apiInstance.getMonitor(params).then((data: v1.Monitor) => { - console.log('API called successfully. Returned data: ' + data); -}).catch((error:any) => console.error(error)); +Here's an example of getting a monitor: +```bash +yarn add @datadog/datadog-api-client-monitors ``` -### 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: - ```typescript -import { createConfiguration } from '@datadog/datadog-api-client'; +import { createConfiguration } from "@datadog/datadog-api-client"; import { v1 } from '@datadog/datadog-api-client-monitors'; -const configurationOpts = { - authMethods: { - apiKeyAuth: "", - appKeyAuth: "" - }, -}; - -const configuration = createConfiguration(configurationOpts); -const apiInstance = new v1.MonitorsApiV1(configuration); -``` - -### 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: - -```typescript -configuration.unstableOperations["."] = true -``` - -where `` 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: - -```typescript -import { createConfiguration } from '@datadog/datadog-api-client'; - const configuration = createConfiguration(); +const apiInstance = new v1.MonitorsApiV1(configuration); -configuration.setServerVariables({ - site: "datadoghq.eu" -}); -``` - -### Disable compressed payloads - -If you want to disable GZIP compressed responses, set the `compress` flag -on your configuration options: - -```typescript -import { createConfiguration } from '@datadog/datadog-api-client'; -const configurationOpts = { - httpConfig: { - compress: false - }, -}; - -const configuration = createConfiguration(configurationOpts); -``` - -### Enable requests logging - -If you want to enable requests logging, set the `debug` flag on your configuration object: - -```typescript -import { createConfiguration } from '@datadog/datadog-api-client'; -const configurationOpts = { - debug: true -}; - -const configuration = createConfiguration(configurationOpts); -``` - -### Enable retry - -To enable the client to retry when rate limited (status 429) or status 500 and above: - -```typescript -import { createConfiguration } from '@datadog/datadog-api-client'; -const configurationOpts = { - enableRetry: true -}; - -const configuration = 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 : - -```typescript -(backoffMultiplier ** current_retry_count) * backoffBase -``` -The maximum number of retry attempts is 3 by default and can be modified with - -```typescript -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](https://www.npmjs.com/package/abort-controller). You can -then pass the `signal method to the HTTP configuration options: - -```typescript -import { createConfiguration } from '@datadog/datadog-api-client'; -import { v1 } from '@datadog/datadog-api-client-monitors' - -import AbortController from 'abort-controller'; - -const controller = new AbortController(); -const timeout = setTimeout( - () => { controller.abort(); }, - 1000, -); -const configurationOpts = { - httpConfig: { - signal: controller.signal - }, +let params: v1.MonitorsApiGetMonitorRequest = { + monitorId: 1, }; -const configuration = createConfiguration(configurationOpts); - -const apiInstance = new v1.MonitorsApi(configuration); -apiInstance.listMonitors().then((data: v1.Monitor[]) => { +apiInstance.getMonitor(params).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: - -```typescript -import { createConfiguration } from "@datadog/datadog-api-client"; -import { v2 } from "@datadog/datadog-api-client-incidents"; - -async function main() { - const configuration = 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: - -```typescript -import { compressSync } from 'zstd.ts' -import { createConfiguration } from "@datadog/datadog-api-client"; -import { v2 } from "@datadog/datadog-api-client-metrics"; - -async function main() { - const configurationOpts = { - zstdCompressorCallback: (body: string) => compressSync({input: Buffer.from(body, "utf8")}) - } - const configuration = 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: - -```typescript -import pako from "pako"; -import bufferFrom from "buffer-from"; -import fetch from "node-fetch"; -import { HttpsProxyAgent } from "https-proxy-agent"; - -import { createConfiguration, ResponseContext, RequestContext, HttpLibrary } from "@datadog/datadog-api-client"; -import { v1 } from "@datadog/datadog-api-client"; - -const proxyAgent = new HttpsProxyAgent('http://127.0.0.11:3128'); - -class HttpLibraryWithProxy implements HttpLibrary { - public debug = false; - - public send(request: RequestContext): Promise { - 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 ResponseContext(resp.status, headers, body); - return response; - }); - - return resultPromise; - } -} - -const configuration = 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)); +}).catch((error:any) => console.error(error)); ``` - -## Documentation - -Documentation for API endpoints can be found in [GitHub pages][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 - -support@datadoghq.com - -## License - -[Apache License, v2.0](LICENSE) - -[github pages]: https://datadoghq.dev/datadog-api-client-typescript/