- Notifications
You must be signed in to change notification settings - Fork6
JavaScript REST client and utils for Clever Cloud's API
License
CleverCloud/clever-client.js
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
🚧New Client Documentation Available: For the new command-pattern client (beta), seeNEW_CLIENT.md
This project contains a REST client for Clever Cloud's API and some utils.
First, you need to install the Node.js module:
npm install @clevercloud/client
All API REST paths are accessible as "functions" organized in "services".A call to a function of a service will just prepare the HTTP request and return the request params in an object via a promise.It won't authenticate the request and it won't send it.
You will need to chain some helpers to the function call to:
- Specify the API host (prod, preprod...)
- Add the right authentication headers (oAuth v1 or other...)
- Send the HTTP request with your favourite lib/code
- Handle the response with your favourite lib/code
Those helpers are ready to use for browsers or Node.js and for oAuth v1 signature auth.The recommended way is to wrap those helpers in one place of your app and to reuse it everywhere you need to send API calls.
Here's an example using ECMAScript modules with oAuth v1 signature and using thefetch API to send requests.
In a file, expose this function:
import{addOauthHeader}from'@clevercloud/client/esm/oauth.js';import{prefixUrl}from'@clevercloud/client/esm/prefix-url.js';import{request}from'@clevercloud/client/esm/request.fetch.js';exportfunctionsendToApi(requestParams){// load and cache config and tokensconstAPI_HOST='https://api.clever-cloud.com'consttokens={OAUTH_CONSUMER_KEY:'your OAUTH_CONSUMER_KEY',OAUTH_CONSUMER_SECRET:'your OAUTH_CONSUMER_SECRET',API_OAUTH_TOKEN:'your API_OAUTH_TOKEN',API_OAUTH_TOKEN_SECRET:'your API_OAUTH_TOKEN_SECRET',}returnPromise.resolve(requestParams).then(prefixUrl(API_HOST)).then(addOauthHeader(tokens)).then(request);// chain a .catch() call here if you need to handle some errors or maybe redirect to login}
NOTE: If your project relies on a specific REST library (axios, jQuery...), you'll have to write your own request function to plug the params to your lib instead of usingrequest.fetch.js.
Then, in any file of your app, import the API function you need directly (it helps with tree shaking), call it and add a.then(sendToApi) like this:
import{getAllEnvVars}from'@clevercloud/client/esm/api/v2/application.js';import{sendToApi}from'../send-to-api.js';constenvVars=awaitgetAllEnvVars({id:oid, appId}).then(sendToApi);
NOTE: It returns a promise, you may want to useawait with it.
A general documentation is proposed onour Website.As stated in the documentation:
You need to create an oAuth consumer token in the Clever Cloud console. Click on "Create...", then on "an oauth consumer" under your organization name. All created consumers will appear under the list of applications and add-ons.
Once you got the consumer, you still need to generate the aAuth tokens. You may do the whole aAuth dance in the browser.
If you use theclever-tools CLI, you can also generate tokens using the following command :
clever login
Once successfully logged in, you’ll be provided with a token / secret couple.
This stream is exposed the inner SSE source withcomponent-emitter, a tiny lib implementing an API that closely match bothEventTarget from the DOM andEventEmitter from Node.js.
Here's an example of how to useLogsStream to retrieve live logs from an app:
// Browser implementation or Node.js implementationimport{LogsStream}from'@clevercloud/client/esm/streams/logs.browser.js';// import { LogsStream } from '@clevercloud/client/esm/streams/logs.node.js';// Load and cache config and tokensconstAPI_HOST='https://api.clever-cloud.com';consttokens={OAUTH_CONSUMER_KEY:'your OAUTH_CONSUMER_KEY',OAUTH_CONSUMER_SECRET:'your OAUTH_CONSUMER_SECRET',API_OAUTH_TOKEN:'your API_OAUTH_TOKEN',API_OAUTH_TOKEN_SECRET:'your API_OAUTH_TOKEN_SECRET',};// Create a LogsStream instance (filter and deploymentId are optional)constlogsStream=newLogsStream({apiHost:API_HOST, tokens, appId, filter, deploymentId});// Listen to "log" eventslogsStream.on('log',(rawLogLine)=>console.log(rawLogLine));// Open the streamlogsStream.open();
This stream is exposed the inner WebSocket source withcomponent-emitter, a tiny lib implementing an API that closely match bothEventTarget from the DOM andEventEmitter from Node.js.
Here's an example of how to useEventsStream to retrieve events from the Clever Cloud platform:
// Browser and Node.js 21+ implementationimport{EventsStream}from'@clevercloud/client/esm/streams/events.js';// Load and cache config and tokensconstAPI_HOST='https://api.clever-cloud.com';consttokens={OAUTH_CONSUMER_KEY:'your OAUTH_CONSUMER_KEY',OAUTH_CONSUMER_SECRET:'your OAUTH_CONSUMER_SECRET',API_OAUTH_TOKEN:'your API_OAUTH_TOKEN',API_OAUTH_TOKEN_SECRET:'your API_OAUTH_TOKEN_SECRET',};// Create an EventsStream instance (appId is optional)consteventsStream=newEventsStream({apiHost:API_HOST, tokens, appId});// Listen to "event" eventseventsStream.on('event',(rawEvent)=>console.log(rawEvent));// Open the streameventsStream.open();
When an error (network failures, bad authentication...) occurs with the source stream, an error event is emitted:
stream.on('error',(error)=>console.error(error));
- By default, when a network failure is detected, an error is emitted and the stream is closed automatically.
- If you enable the auto retry behaviour, when a network failure is detected, it won't emit an error.
- If you enable the auto retry behaviour AND set a max number of retries, it will emit an error.
See "auto retry behaviour" section for more details...
You can close the stream at any time like this:
stream.close();
It won't remove event listeners from the stream instance so you can re-open it easily.
When you call.open() on a stream, it's not resilient to network failures by default.We have an opt-in auto retry behaviour to handle those, you can enable it when you open the stream like this:
stream.open({autoRetry:true});
Network failure are detected with a ping/pong system.When such a failure is detected and auto retry behaviour is enabled, the source stream is closed and a new open is attempted automatically.
You probably don't need to but you can listen to events related to this auto retry behaviour:
// "close" event is emitted each time a network failure is detected (or any unknown error not related to authentication)stream.on('close',(reason)=>console.log('Stream closed because of',reason));// "open" event is emitted on first .open() call and each time a new open is attemptedstream.on('open',()=>console.log('Stream open...'));// "ping" event is emitted each time a ping is received from the source streamstream.on('ping',()=>console.log('Received ping'));
When enabled, the auto retry behaviour will follow an infinite exponential backoff pattern.You can change the default timings and max number of retries like this:
stream.open({autoRetry:true,// Factor used to compute exponential backoff delays, defaults to 1.25backoffFactor:1.5,// First iteration timeout in ms, also used to compute exponential backoff delays, defaults to 1500initRetryTimeout:2000,// Maximum number of consecutive iterations the auto retry behaviour can do, defaults to InfinitymaxRetryCount:6,});
import{ApplicationLogStream}from'@clevercloud/client/esm/streams/application-log.js';// Load and cache config and tokensconstAPI_HOST='https://api.clever-cloud.com';consttokens={OAUTH_CONSUMER_KEY:'your OAUTH_CONSUMER_KEY',OAUTH_CONSUMER_SECRET:'your OAUTH_CONSUMER_SECRET',API_OAUTH_TOKEN:'your API_OAUTH_TOKEN',API_OAUTH_TOKEN_SECRET:'your API_OAUTH_TOKEN_SECRET',};// Create an EventsStream instance (appId is optional)constlogsStream=newApplicationLogStream({apiHost:API_HOST, tokens,ownerId:'YYY',appId:'XXX',// optionnal auto retry config// retryConfiguration: {// enabled: true,// backoffFactor: number,// initRetryTimeout: number,// maxRetryCount: number,// },// optionnal logs request params// since: Date,// until: Date,// service: string[],// limit: number,// deploymentId: string,// instanceId: string[],// filter: string,// field: string[],// throttleElements: number,// throttlePerInMilliseconds: number,});logsStream.on('open',(event)=>console.debug('stream opened!',event)).on('error',(event)=>console.error('error',event.error)).onLog((event)=>console.log(event.data.date,event.data.message));logsStream.start();// You can also pause the streamlogsStream.pause();// And resume itlogsStream.resume();
This project is licensed under theApache-2.0.
About
JavaScript REST client and utils for Clever Cloud's API
Topics
Resources
License
Contributing
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.