@aurora-interactive/fankare-api-sdk
v0.1.5
Published
Developer-friendly & type-safe Typescript SDK specifically catered to leverage *openapi* API.
Readme
openapi
Developer-friendly & type-safe Typescript SDK specifically catered to leverage openapi API.
[!IMPORTANT] This SDK is not yet ready for production use. To complete setup please follow the steps outlined in your workspace. Delete this section before > publishing to a package manager.
Summary
Fankare Multimedia Social Platform API: The inner circle for creators and their biggest fans.
Table of Contents
SDK Installation
[!TIP] To finish publishing your SDK to npm and others you must run your first generation action.
The SDK can be installed with either npm, pnpm, bun or yarn package managers.
NPM
npm add <UNSET>PNPM
pnpm add <UNSET>Bun
bun add <UNSET>Yarn
yarn add <UNSET>[!NOTE] This package is published as an ES Module (ESM) only. For applications using CommonJS, use
await import()to import and use this package.
Requirements
For supported JavaScript runtimes, please consult RUNTIMES.md.
SDK Example Usage
Example
import { FankareSDK } from "openapi";
const fankareSDK = new FankareSDK({
bearerAuth: "<YOUR_BEARER_TOKEN_HERE>",
});
async function run() {
const result = await fankareSDK.authentication.registerUser({
username: "Nicklaus67",
email: "[email protected]",
password: "4rmpu4fcbiqyYPN",
displayName: "Abbey80",
});
console.log(result);
}
run();
Authentication
Per-Client Security Schemes
This SDK supports the following security scheme globally:
| Name | Type | Scheme |
| ------------ | ---- | ----------- |
| bearerAuth | http | HTTP Bearer |
To authenticate with the API the bearerAuth parameter must be set when initializing the SDK client instance. For example:
import { FankareSDK } from "openapi";
const fankareSDK = new FankareSDK({
bearerAuth: "<YOUR_BEARER_TOKEN_HERE>",
});
async function run() {
const result = await fankareSDK.authentication.registerUser({
username: "Nicklaus67",
email: "[email protected]",
password: "4rmpu4fcbiqyYPN",
displayName: "Abbey80",
});
console.log(result);
}
run();
Available Resources and Operations
Authentication
- registerUser - Register a new user
- loginUser - Authenticate user and receive a token
CreatorTimelines
- getCreatorPosts - Get a specific creator's timeline with pagination
CreatorsDiscovery
- getFeaturedCreators - Fetch a curated list of featured creators for the Guest Landing page
- getTrendingCreators - Fetch popular creators to discover in the sidebar
CustomCollections
- getCollections - Get all collections created by the user
- createCollection - Create a new custom grouping collection
- deleteCollection - Delete a custom collection
- getCollectionMembers - Get all members belonging to a custom collection
- addCollectionMember - Add a user to a custom collection
- removeCollectionMember - Remove a user from a custom collection
DirectMessaging
- getConversations - Fetch active DM threads
- getMessageHistory - Load message history with a specific user with pagination
- sendMessage - Send a direct text message
Internal
- assetProcessingCallback - [Internal] Celery worker callback to update the processing status of a single post asset
Me
- getMe - Get the authenticated user's own profile
- updateMe - Update the authenticated user's profile text fields
- requestAvatarUploadUrl - Request a presigned URL to upload or replace the authenticated user's avatar image
- confirmAvatarUpload - Confirm a completed avatar upload and atomically update the user record
- requestBannerUploadUrl - Request a presigned URL to upload or replace the authenticated user's profile banner image
- confirmBannerUpload - Confirm a completed banner upload and atomically update the user record
Notifications
- getNotifications - Fetch a paginated feed of notifications for the authenticated user
- getUnreadNotificationCount - Fetch the count of unread notifications for the authenticated user
- markNotificationsAsRead - Mark notifications as read
Posts
- getFeed - Get the consolidated timeline feed with pagination
- createPost - Initiate a new post: reserve asset slots and receive presigned upload URLs
- getPost - Fetch a single post by ID, including all asset statuses
- updatePost - Publish or update a post
- deletePost - Delete a post and cascade-delete all associated assets from object storage
- getPostLikes - Fetch the list of users who liked a post
- likePost - Like a post
- unlikePost - Unlike a post
- getPostComments - Fetch paginated comments for a post
- createComment - Add a comment to a post
- deleteComment - Delete a comment from a post
- confirmAssetUpload - Confirm media upload and initiate processing
- getCollectionFeed - Get a timeline filtered strictly by members of this collection with pagination
Settings
- getProfileSettings - Get the authenticated user's account profile settings
- updateProfileSettings - Update the authenticated user's account profile settings
- deactivateAccount - Soft-delete (deactivate) the authenticated user's account
- confirmEmailChange - Confirm a pending email address change
- getSubscriptionSettings - Get the authenticated user's subscription price setting
- updateSubscriptionSettings - Update the authenticated user's subscription price
- getNotificationSettings - Get the authenticated user's notification preferences
- updateNotificationSettings - Update the authenticated user's notification preferences
Subscriptions
- subscribeToUser - Subscribe to a user's feed
- unsubscribeFromUser - Unsubscribe from a user's feed
UserDiscovery
- searchUsers - Search global user profiles
- getUserProfile - Retrieve user profile metadata
- getFollowing - Get subscriptions list
- getFollowers - Fetch the authenticated user's paginated list of followers
- getFollowerCount - Fetch the authenticated user's follower count
- getUserFollowers - Fetch a specific user's paginated list of followers
- getUserFollowerCount - Fetch a specific user's follower count
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.
authenticationLoginUser- Authenticate user and receive a tokenauthenticationRegisterUser- Register a new usercreatorsDiscoveryGetFeaturedCreators- Fetch a curated list of featured creators for the Guest Landing pagecreatorsDiscoveryGetTrendingCreators- Fetch popular creators to discover in the sidebarcreatorTimelinesGetCreatorPosts- Get a specific creator's timeline with paginationcustomCollectionsAddCollectionMember- Add a user to a custom collectioncustomCollectionsCreateCollection- Create a new custom grouping collectioncustomCollectionsDeleteCollection- Delete a custom collectioncustomCollectionsGetCollectionMembers- Get all members belonging to a custom collectioncustomCollectionsGetCollections- Get all collections created by the usercustomCollectionsRemoveCollectionMember- Remove a user from a custom collectiondirectMessagingGetConversations- Fetch active DM threadsdirectMessagingGetMessageHistory- Load message history with a specific user with paginationdirectMessagingSendMessage- Send a direct text messageinternalAssetProcessingCallback- [Internal] Celery worker callback to update the processing status of a single post assetmeConfirmAvatarUpload- Confirm a completed avatar upload and atomically update the user recordmeConfirmBannerUpload- Confirm a completed banner upload and atomically update the user recordmeGetMe- Get the authenticated user's own profilemeRequestAvatarUploadUrl- Request a presigned URL to upload or replace the authenticated user's avatar imagemeRequestBannerUploadUrl- Request a presigned URL to upload or replace the authenticated user's profile banner imagemeUpdateMe- Update the authenticated user's profile text fieldsnotificationsGetNotifications- Fetch a paginated feed of notifications for the authenticated usernotificationsGetUnreadNotificationCount- Fetch the count of unread notifications for the authenticated usernotificationsMarkNotificationsAsRead- Mark notifications as readpostsConfirmAssetUpload- Confirm media upload and initiate processingpostsCreateComment- Add a comment to a postpostsCreatePost- Initiate a new post: reserve asset slots and receive presigned upload URLspostsDeleteComment- Delete a comment from a postpostsDeletePost- Delete a post and cascade-delete all associated assets from object storagepostsGetCollectionFeed- Get a timeline filtered strictly by members of this collection with paginationpostsGetFeed- Get the consolidated timeline feed with paginationpostsGetPost- Fetch a single post by ID, including all asset statusespostsGetPostComments- Fetch paginated comments for a postpostsGetPostLikes- Fetch the list of users who liked a postpostsLikePost- Like a postpostsUnlikePost- Unlike a postpostsUpdatePost- Publish or update a postsettingsConfirmEmailChange- Confirm a pending email address changesettingsDeactivateAccount- Soft-delete (deactivate) the authenticated user's accountsettingsGetNotificationSettings- Get the authenticated user's notification preferencessettingsGetProfileSettings- Get the authenticated user's account profile settingssettingsGetSubscriptionSettings- Get the authenticated user's subscription price settingsettingsUpdateNotificationSettings- Update the authenticated user's notification preferencessettingsUpdateProfileSettings- Update the authenticated user's account profile settingssettingsUpdateSubscriptionSettings- Update the authenticated user's subscription pricesubscriptionsSubscribeToUser- Subscribe to a user's feedsubscriptionsUnsubscribeFromUser- Unsubscribe from a user's feeduserDiscoveryGetFollowerCount- Fetch the authenticated user's follower countuserDiscoveryGetFollowers- Fetch the authenticated user's paginated list of followersuserDiscoveryGetFollowing- Get subscriptions listuserDiscoveryGetUserFollowerCount- Fetch a specific user's follower countuserDiscoveryGetUserFollowers- Fetch a specific user's paginated list of followersuserDiscoveryGetUserProfile- Retrieve user profile metadatauserDiscoverySearchUsers- Search global user profiles
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 { FankareSDK } from "openapi";
const fankareSDK = new FankareSDK({
bearerAuth: "<YOUR_BEARER_TOKEN_HERE>",
});
async function run() {
const result = await fankareSDK.authentication.registerUser({
username: "Nicklaus67",
email: "[email protected]",
password: "4rmpu4fcbiqyYPN",
displayName: "Abbey80",
}, {
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 { FankareSDK } from "openapi";
const fankareSDK = new FankareSDK({
retryConfig: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
bearerAuth: "<YOUR_BEARER_TOKEN_HERE>",
});
async function run() {
const result = await fankareSDK.authentication.registerUser({
username: "Nicklaus67",
email: "[email protected]",
password: "4rmpu4fcbiqyYPN",
displayName: "Abbey80",
});
console.log(result);
}
run();
Error Handling
FankareSDKError 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 |
Example
import { FankareSDK } from "openapi";
import * as errors from "openapi/models/errors";
const fankareSDK = new FankareSDK({
bearerAuth: "<YOUR_BEARER_TOKEN_HERE>",
});
async function run() {
try {
const result = await fankareSDK.authentication.registerUser({
username: "Nicklaus67",
email: "[email protected]",
password: "4rmpu4fcbiqyYPN",
displayName: "Abbey80",
});
console.log(result);
} catch (error) {
if (error instanceof errors.FankareSDKError) {
console.log(error.message);
console.log(error.statusCode);
console.log(error.body);
console.log(error.headers);
}
}
}
run();
Error Classes
Primary error:
FankareSDKError: The base class for HTTP error responses.
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 FankareSDKError:
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.
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 { FankareSDK } from "openapi";
const fankareSDK = new FankareSDK({
serverURL: "https://api.fankare.vip/api/v1",
bearerAuth: "<YOUR_BEARER_TOKEN_HERE>",
});
async function run() {
const result = await fankareSDK.authentication.registerUser({
username: "Nicklaus67",
email: "[email protected]",
password: "4rmpu4fcbiqyYPN",
displayName: "Abbey80",
});
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:
- route requests through a proxy server using undici's ProxyAgent
- use the
"beforeRequest"hook to add a custom header and a timeout to requests - use the
"requestError"hook to log errors
import { FankareSDK } from "openapi";
import { ProxyAgent } from "undici";
import { HTTPClient } from "openapi/lib/http";
const dispatcher = new ProxyAgent("http://proxy.example.com:8080");
const httpClient = new HTTPClient({
// 'fetcher' takes a function that has the same signature as native 'fetch'.
fetcher: (input, init) =>
// 'dispatcher' is specific to undici and not part of the standard Fetch API.
fetch(input, { ...init, dispatcher } as RequestInit),
});
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 FankareSDK({ 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 { FankareSDK } from "openapi";
const sdk = new FankareSDK({ debugLogger: console });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.
