@rainfall-digital/sdk
v0.1.3
Published
Developer-friendly & type-safe Typescript SDK specifically catered to leverage *@rainfall-digital/sdk* API.
Readme
@rainfall-digital/sdk
Developer-friendly & type-safe Typescript SDK specifically catered to leverage @rainfall-digital/sdk API.
Summary
Rainfall Digital API: The Rainfall Digital API empowers developers to seamlessly integrate with our robust platform, offering a comprehensive suite of endpoints for managing digital assets, product lines, and user authentication.
Key Features:
- Asset Management: Create, retrieve, and transfer digital assets with ease.
- Product Line Operations: Manage product lines and associated products efficiently.
- User Authentication: Secure token-based authentication system with magic link support.
- Event Tracking: Monitor and manage product-related events.
- Merchant Integration: Access merchant details and interact with merchant functionalities.
- Image Handling: Upload and manage images associated with products and assets.
Our API adheres to RESTful principles, ensuring intuitive interaction and seamless integration with your existing systems. With robust error handling and comprehensive documentation, we provide a developer-friendly experience fo you to take advantage of.
References
Table of Contents
SDK Installation
The SDK can be installed with either npm, pnpm, bun or yarn package managers.
NPM
npm add @rainfall-digital/sdkPNPM
pnpm add @rainfall-digital/sdkBun
bun add @rainfall-digital/sdkYarn
yarn add @rainfall-digital/sdk[!NOTE] This package is published with CommonJS and ES Modules (ESM) support.
Requirements
For supported JavaScript runtimes, please consult RUNTIMES.md.
SDK Example Usage
Example
import { Rainfall } from "@rainfall-digital/sdk";
const rainfall = new Rainfall();
async function run() {
const result = await rainfall.assets.list({
tokenAuth: process.env["RAINFALL_TOKEN_AUTH"] ?? "",
});
console.log(result);
}
run();
Authentication
Per-Client Security Schemes
This SDK supports the following security scheme globally:
| Name | Type | Scheme | Environment Variable |
| ----------- | ------ | ------- | --------------------- |
| tokenAuth | apiKey | API key | RAINFALL_TOKEN_AUTH |
To authenticate with the API the tokenAuth parameter must be set when initializing the SDK client instance. For example:
import { Rainfall } from "@rainfall-digital/sdk";
const rainfall = new Rainfall({
tokenAuth: process.env["RAINFALL_TOKEN_AUTH"] ?? "",
});
async function run() {
const result = await rainfall.general.refreshToken({
refresh: "<value>",
});
console.log(result);
}
run();
Per-Operation Security Schemes
Some operations in this SDK require the security scheme to be specified at the request level. For example:
import { Rainfall } from "@rainfall-digital/sdk";
const rainfall = new Rainfall();
async function run() {
const result = await rainfall.assets.list({});
console.log(result);
}
run();
Available Resources and Operations
Assets
- list - Get assets
- create - Create an asset
- get - Get asset
- claim - Claim asset
- createEvent - Create event
- setImage - Set image
- search - Search asset
General
- login - Login to your account
- logout - Logout from your account
- authLogout - Logout from your account
- refreshToken - Takes a refresh type JSON web token and returns an access type JSON web token if the refresh token is valid.
- authTokenVerify - Verify JWT access token
MagicLink
Media
- create - Create an image
Merchants
- get - Get merchant
Password
- change - Change your password
- reset - Reset your password
- resetConfirm - Confirm password reset
ProductEvents
ProductLines
- list - Get product lines
- get - Get product line
- assignProvisionalProducts - Assign provisional products
Products
- get - Get products
- fetchById - Get product
- createEvent - Create product event
ProvisionalLines
- list - List provisional lines
- create - Create Provisional Line
- createProducts - Create additional provisional products
- listProducts - List products from a provisional line
~~ProvisionalProducts~~
- ~~get~~ - List all provisional products :warning: Deprecated
Registration
- create - Register a new user
- resendEmailVerification - Resend email verification
- verifyEmail - Verify email address
Settings
- getPersonalAssets - Get Asset Settings
- updatePersonalAssets - Set Asset Settings
- updateAsset - Update Asset Setting
SharedEvents
- list - List shared events
- create - Create shared event
- get - Get shared event
- update - Update shared event
- patch - Partially update shared event
- delete - Delete shared event
Transfers
- list - Get transfers
- create - Create transfer
- get - Get transfer
- partialUpdate - Update expiration
- delete - Delete transfer
- acceptRequest - Accept transfer
- rejectRequest - Reject transfer
- getIncomingTransferCount - Incoming transfer count
UserProfile
- get - Retrieve user details
- update - Update user details
- partialUpdate - Partially update user details
Webhooks
- createTwilioEvent - Process SMS messages from Twilio to create product events.
This webhook endpoint receives SMS messages from Twilio and processes them to create product events. It validates the asset serial number, checks if the phone number is associated with the correct merchant, and generates a magic link for event submission.
Args: request: The HTTP request containing Twilio's webhook payload.
Returns: Response: A response with appropriate message and HTTP 200 OK status.
Standalone functions
All the methods listed above are available as standalone functions. These functions are ideal for use in applications running in the browser, serverless runtimes or other environments where application bundle size is a primary concern. When using a bundler to build your application, all unused functionality will be either excluded from the final bundle or tree-shaken away.
To read more about standalone functions, check FUNCTIONS.md.
assetsClaim- Claim assetassetsCreate- Create an assetassetsCreateEvent- Create eventassetsGet- Get assetassetsList- Get assetsassetsSearch- Search assetassetsSetImage- Set imagegeneralAuthLogout- Logout from your accountgeneralAuthTokenVerify- Verify JWT access tokengeneralLogin- Login to your accountgeneralLogout- Logout from your accountgeneralRefreshToken- Takes a refresh type JSON web token and returns an access type JSON web token if the refresh token is valid.magicLinkRequest- Request magic linkmagicLinkValidate- Validate magic linkmediaCreate- Create an imagemerchantsGet- Get merchantpasswordChange- Change your passwordpasswordReset- Reset your passwordpasswordResetConfirm- Confirm password resetproductEventsGet- Get eventproductEventsList- Get eventsproductLinesAssignProvisionalProducts- Assign provisional productsproductLinesGet- Get product lineproductLinesList- Get product linesproductsCreateEvent- Create product eventproductsFetchById- Get productproductsGet- Get productsprovisionalLinesCreate- Create Provisional LineprovisionalLinesCreateProducts- Create additional provisional productsprovisionalLinesList- List provisional linesprovisionalLinesListProducts- List products from a provisional lineregistrationCreate- Register a new userregistrationResendEmailVerification- Resend email verificationregistrationVerifyEmail- Verify email addresssettingsGetPersonalAssets- Get Asset SettingssettingsUpdateAsset- Update Asset SettingsettingsUpdatePersonalAssets- Set Asset SettingssharedEventsCreate- Create shared eventsharedEventsDelete- Delete shared eventsharedEventsGet- Get shared eventsharedEventsList- List shared eventssharedEventsPatch- Partially update shared eventsharedEventsUpdate- Update shared eventtransfersAcceptRequest- Accept transfertransfersCreate- Create transfertransfersDelete- Delete transfertransfersGet- Get transfertransfersGetIncomingTransferCount- Incoming transfer counttransfersList- Get transferstransfersPartialUpdate- Update expirationtransfersRejectRequest- Reject transferuserProfileGet- Retrieve user detailsuserProfilePartialUpdate- Partially update user detailsuserProfileUpdate- Update user detailswebhooksCreateTwilioEvent- Process SMS messages from Twilio to create product events.
This webhook endpoint receives SMS messages from Twilio and processes them to create product events. It validates the asset serial number, checks if the phone number is associated with the correct merchant, and generates a magic link for event submission.
Args: request: The HTTP request containing Twilio's webhook payload.
Returns: Response: A response with appropriate message and HTTP 200 OK status.
- ~~
provisionalProductsGet~~ - List all provisional products :warning: Deprecated
Retries
Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply provide a retryConfig object to the call:
import { Rainfall } from "@rainfall-digital/sdk";
const rainfall = new Rainfall();
async function run() {
const result = await rainfall.assets.list({
tokenAuth: process.env["RAINFALL_TOKEN_AUTH"] ?? "",
}, {
retries: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
});
console.log(result);
}
run();
If you'd like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization:
import { Rainfall } from "@rainfall-digital/sdk";
const rainfall = new Rainfall({
retryConfig: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
});
async function run() {
const result = await rainfall.assets.list({
tokenAuth: process.env["RAINFALL_TOKEN_AUTH"] ?? "",
});
console.log(result);
}
run();
Error Handling
RainfallError is the base class for all HTTP error responses. It has the following properties:
| Property | Type | Description |
| ------------------- | ---------- | --------------------------------------------------------------------------------------- |
| error.message | string | Error message |
| error.statusCode | number | HTTP response status code eg 404 |
| error.headers | Headers | HTTP response headers |
| error.body | string | HTTP body. Can be empty string if no body is returned. |
| error.rawResponse | Response | Raw HTTP response |
| error.data$ | | Optional. Some errors may contain structured data. See Error Classes. |
Example
import { Rainfall } from "@rainfall-digital/sdk";
import * as errors from "@rainfall-digital/sdk/models/errors";
const rainfall = new Rainfall();
async function run() {
try {
const result = await rainfall.assets.list({
tokenAuth: process.env["RAINFALL_TOKEN_AUTH"] ?? "",
});
console.log(result);
} catch (error) {
// The base class for HTTP error responses
if (error instanceof errors.RainfallError) {
console.log(error.message);
console.log(error.statusCode);
console.log(error.body);
console.log(error.headers);
// Depending on the method different errors may be thrown
if (error instanceof errors.ParseErrorResponse) {
console.log(error.data$.type); // models.string
console.log(error.data$.errors); // ParseError[]
}
}
}
}
run();
Error Classes
Primary errors:
RainfallError: The base class for HTTP error responses.ErrorResponse405: . Status code405.ErrorResponse406: . Status code406.ErrorResponse415: . Status code415.ErrorResponse500: . Status code500.ParseErrorResponse: . Status code400. *ErrorResponse401: . Status code401. *
Network errors:
ConnectionError: HTTP client was unable to make a request to a server.RequestTimeoutError: HTTP request timed out due to an AbortSignal signal.RequestAbortedError: HTTP request was aborted by the client.InvalidRequestError: Any input used to create a request is invalid.UnexpectedClientError: Unrecognised or unexpected error.
Inherit from RainfallError:
ErrorResponse404: . Status code404. Applicable to 21 of 56 methods.*ErrorResponse403: . Status code403. Applicable to 7 of 56 methods.*AssetsCreateValidationError: . Status code400. Applicable to 1 of 56 methods.*AssetsEventCreateValidationError: . Status code400. Applicable to 1 of 56 methods.*AssetsImageCreateValidationError: . Status code400. Applicable to 1 of 56 methods.*AuthLoginCreateValidationError: . Status code400. Applicable to 1 of 56 methods.*AuthTokenRefreshCreateValidationError: . Status code400. Applicable to 1 of 56 methods.*AuthTokenVerifyCreateValidationError: . Status code400. Applicable to 1 of 56 methods.*AuthMagicLinkCreateValidationError: . Status code400. Applicable to 1 of 56 methods.*AuthMagicLinkValidateCreateValidationError: . Status code400. Applicable to 1 of 56 methods.*AuthPasswordChangeCreateValidationError: . Status code400. Applicable to 1 of 56 methods.*AuthPasswordResetCreateValidationError: . Status code400. Applicable to 1 of 56 methods.*AuthPasswordResetConfirmCreateValidationError: . Status code400. Applicable to 1 of 56 methods.*AuthRegistrationCreateValidationError: . Status code400. Applicable to 1 of 56 methods.*AuthRegistrationResendEmailCreateValidationError: . Status code400. Applicable to 1 of 56 methods.*AuthRegistrationVerifyEmailCreateValidationError: . Status code400. Applicable to 1 of 56 methods.*AuthUserUpdateValidationError: . Status code400. Applicable to 1 of 56 methods.*AuthUserPartialUpdateValidationError: . Status code400. Applicable to 1 of 56 methods.*ImageCreateValidationError: . Status code400. Applicable to 1 of 56 methods.*ProductEventsListValidationError: . Status code400. Applicable to 1 of 56 methods.*GetProductsValidationError: . Status code400. Applicable to 1 of 56 methods.*CreateProvisionalLineValidationError: . Status code400. Applicable to 1 of 56 methods.*GetProvisionalProductsValidationError: . Status code400. Applicable to 1 of 56 methods.*SettingsPersonalAssetsUpdateValidationError: . Status code400. Applicable to 1 of 56 methods.*SettingsPersonalAssetsPartialUpdateValidationError: . Status code400. Applicable to 1 of 56 methods.*SharedEventsListValidationError: . Status code400. Applicable to 1 of 56 methods.*SharedEventsCreateValidationError: . Status code400. Applicable to 1 of 56 methods.*SharedEventsUpdateValidationError: . Status code400. Applicable to 1 of 56 methods.*SharedEventsPartialUpdateValidationError: . Status code400. Applicable to 1 of 56 methods.*TransfersListValidationError: . Status code400. Applicable to 1 of 56 methods.*TransfersCreateValidationError: . Status code400. Applicable to 1 of 56 methods.*TransfersPartialUpdateValidationError: . Status code400. Applicable to 1 of 56 methods.*TransfersRequestUpdateValidationError: . Status code400. Applicable to 1 of 56 methods.*Exception: . Status code401. Applicable to 1 of 56 methods.*ErrorResponse429: . Status code429. Applicable to 1 of 56 methods.*ResponseValidationError: Type mismatch between the data returned from the server and the structure expected by the SDK. Seeerror.rawValuefor the raw value anderror.pretty()for a nicely formatted multi-line string.
* Check the method documentation to see if the error is applicable.
Server Selection
Override Server URL Per-Client
The default server can be overridden globally by passing a URL to the serverURL: string optional parameter when initializing the SDK client instance. For example:
import { Rainfall } from "@rainfall-digital/sdk";
const rainfall = new Rainfall({
serverURL: "https://rainf4ll.com",
});
async function run() {
const result = await rainfall.assets.list({
tokenAuth: process.env["RAINFALL_TOKEN_AUTH"] ?? "",
});
console.log(result);
}
run();
Custom HTTP Client
The TypeScript SDK makes API calls using an HTTPClient that wraps the native
Fetch API. This
client is a thin wrapper around fetch and provides the ability to attach hooks
around the request lifecycle that can be used to modify the request or handle
errors and response.
The HTTPClient constructor takes an optional fetcher argument that can be
used to integrate a third-party HTTP client or when writing tests to mock out
the HTTP client and feed in fixtures.
The following example shows how to use the "beforeRequest" hook to to add a
custom header and a timeout to requests and how to use the "requestError" hook
to log errors:
import { Rainfall } from "@rainfall-digital/sdk";
import { HTTPClient } from "@rainfall-digital/sdk/lib/http";
const httpClient = new HTTPClient({
// fetcher takes a function that has the same signature as native `fetch`.
fetcher: (request) => {
return fetch(request);
}
});
httpClient.addHook("beforeRequest", (request) => {
const nextRequest = new Request(request, {
signal: request.signal || AbortSignal.timeout(5000)
});
nextRequest.headers.set("x-custom-header", "custom value");
return nextRequest;
});
httpClient.addHook("requestError", (error, request) => {
console.group("Request Error");
console.log("Reason:", `${error}`);
console.log("Endpoint:", `${request.method} ${request.url}`);
console.groupEnd();
});
const sdk = new Rainfall({ httpClient: httpClient });Debugging
You can setup your SDK to emit debug logs for SDK requests and responses.
You can pass a logger that matches console's interface as an SDK option.
[!WARNING] Beware that debug logging will reveal secrets, like API tokens in headers, in log messages printed to a console or files. It's recommended to use this feature only during local development and not in production.
import { Rainfall } from "@rainfall-digital/sdk";
const sdk = new Rainfall({ debugLogger: console });You can also enable a default debug logger by setting an environment variable RAINFALL_DEBUG to true.
Development
Maturity
This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.
Contributions
While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.
