# @serve.zone/api The `@serve.zone/api` module is a robust and versatile API client, designed to facilitate seamless communication with various cloud resources managed by the Cloudly platform. This API client extends a rich set of functionalities, offering developers a comprehensive and programmable interface for interacting with their multi-cloud infrastructure. ## Install To install the `@serve.zone/api` package, execute the following command in your terminal: ```bash npm install @serve.zone/api --save ``` This command will download the module and add it to your project's `package.json` dependencies, allowing you to utilize its capabilities within your application. ## Usage The `@serve.zone/api` client is tailored to handle various operations within a multi-cloud environment efficiently. Throughout this section, we will explore the different features and use-cases of this API client, aiding you in leveraging its full potential. ### Prerequisites Before integrating `@serve.zone/api` into your project, ensure the following prerequisites are satisfied: - You have Node.js installed on your system (preferably the latest Long-Term Support version). - You're utilizing a TypeScript-compatible environment for development. ### Establishing an API Client Instance The cornerstone of using `@serve.zone/api` is initializing a `CloudlyApiClient` instance. It serves as the main point of interaction, enabling communication with underlying cloud infrastructures managed by Cloudly. Here's a basic setup guide: ```typescript import { CloudlyApiClient, TClientType } from '@serve.zone/api'; async function initializeClient() { const client = new CloudlyApiClient({ registerAs: 'api' as TClientType, cloudlyUrl: 'https://yourcloudly.url:443' }); await client.start(); return client; } const cloudlyClient = await initializeClient(); ``` The above code initializes the `CloudlyApiClient` object, connecting your application to the configured Cloudly environment. ### Authentication and Identity Management To execute operations via the API client, authenticated access is necessary. The most prevalent method for this is obtaining an identity token using a service token: ```typescript import { CloudlyApiClient } from '@serve.zone/api'; async function authenticate(client: CloudlyApiClient, serviceToken: string) { const identity = await client.getIdentityByToken(serviceToken, { tagConnection: true, statefullIdentity: true }); console.log(`Authenticated identity:`, identity); return identity; } const serviceToken = 'your_service_token'; const identity = await authenticate(cloudlyClient, serviceToken); ``` In this function, the `getIdentityByToken` method authenticates using a service token and acquires an identity object that includes user details and security claims. ### Interacting with Cloudly Features #### Image Management Image management is one of the key features supported by the API Client. You can create, upload, and manage Docker images easily within your cloud ecosystem: ```typescript async function manageImages(client: CloudlyApiClient, identity) { // Creating a new image const newImage = await client.images.createImage({ name: 'my_new_image', description: 'A test image' }); console.log(`Created image:`, newImage); // Uploading an image version const imageStream = fetchYourImageStreamHere(); // Provide the source image stream await newImage.pushImageVersion('1.0.0', imageStream); console.log('Image version uploaded successfully.'); } await manageImages(cloudlyClient, identity); // Helper function for obtaining image stream (implement accordingly) function fetchYourImageStreamHere() { // Logic to fetch and return a readable stream for your image return new ReadableStream(); } ``` In this example, the `manageImages` function underscores the typical workflow of creating an image entry within Cloudly and then proceeding to upload a specific version using the `pushImageVersion` method. #### Cluster Configuration Another powerful capability is managing clusters, which allows for orchestrating and configuring Docker Swarm clusters: ```typescript async function configureCluster(client: CloudlyApiClient, identity) { // Fetching cluster configuration const clusterConfig = await client.getClusterConfigFromCloudlyByIdentity(identity); console.log(`Cluster configuration retrieved:`, clusterConfig); } await configureCluster(cloudlyClient, identity); ``` The `getClusterConfigFromCloudlyByIdentity` method retrieved the configuration needed to set up and manage your clusters within the multi-cloud environment. ### Advanced Communication via Typed Sockets The API client leverages `TypedRequest` and `TypedSocket` from the `@api.global` family, enabling statically-typed, real-time communication. Here's an example demonstrating socket integration: ```typescript async function configureSocketCommunication(client: CloudlyApiClient) { client.configUpdateSubject.subscribe({ next: (configData) => { console.log('Received configuration update:', configData); } }); client.serverActionSubject.subscribe({ next: (actionRequest) => { console.log('Server action requested:', actionRequest); } }); } configureSocketCommunication(cloudlyClient); ``` The client utilizes RxJS `Subject` to enable simple yet powerful handling of incoming socket requests, whereby one can act upon updates and actions as they occur. ### Integrating Certificates Certificate operations, such as obtaining SSL certificates for your domains, are also streamlined using this API client: ```typescript async function retrieveCertificate(client: CloudlyApiClient, domainName: string, identity) { const certificate = await client.getCertificateForDomain({ domainName: domainName, type: 'ssl', identity: identity }); console.log('Retrieved SSL Certificate:', certificate); } const yourDomain = 'example.com'; await retrieveCertificate(cloudlyClient, yourDomain, identity); ``` This example demonstrates fetching SSL certificates using given domain credentials and an authenticated identity. ### API Client Cleanup When operations are complete and the application is shutting down, it's crucial to gracefully terminate the API client connection: ```typescript async function cleanup(client: CloudlyApiClient) { await client.stop(); console.log('Cloudly API client disconnected gracefully.'); } await cleanup(cloudlyClient); ``` By invoking the `stop` method, the API client securely terminates its connection to ensure no resources are left hanging, preventing potential memory leaks. ### Miscellaneous Features This section would be remiss without mentioning various utility functionalities such as secret management, server actions, DNS configurator options, and more, all underpinned by an intelligently designed API, enriching cloud resource interactivity. In conclusion, by employing `@serve.zone/api`, developers gain unparalleled access to a multitude of modular functions pertinent to multi-cloud administration, significantly amplifying productivity and management effectiveness across diverse computing environments. ## License and Legal Information This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. **Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file. ### Trademarks This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH. ### Company Information Task Venture Capital GmbH Registered at District court Bremen HRB 35230 HB, Germany For any legal inquiries or if you require further information, please contact us via email at hello@task.vc. By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.