Skip to content

Commit

Permalink
chore: updated readme.md & JS Docs documentation in code (#7)
Browse files Browse the repository at this point in the history
* chore: add missing documentation
* chore: add missing documentation part 2
  • Loading branch information
yashim-deriv authored Feb 19, 2024
1 parent a4ae103 commit bcb7bec
Show file tree
Hide file tree
Showing 6 changed files with 140 additions and 5 deletions.
50 changes: 48 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,57 @@
# Deriv Utility Library (@deriv/utils)

A utility library for Deriv web apps for common functionality like shared constants, formatting, sorting, etc.
## Overview

## Installation and Configuration
This utility library provides a comprehensive suite of utilities designed to support the development of web applications for Deriv. It encapsulates common functionalities such as handling constants, formatting, sorting, and more, with a focus on enhancing development efficiency and ensuring type safety.
<br />
<br />
This library is divided into two main namespaces:

- Constants
- `AppIDConstants`: Holds constants related to application IDs for different domains, facilitating domain-based app ID management.
- `CurrencyConstants`: Enumerates all currencies supported by Deriv, simplifying currency-related operations.
- `LocalStorageConstants`: An exhaustive list of all local storage keys used across Deriv web apps, ensuring consistency in local storage access.
- Utils
- `FormatUtils`: Contains utility functions for string formatting, including number formatting, currency symbol resolution, and more.
- `LocalStorageUtils`: Provides a typesafe wrapper around the browser's localStorage functionality, enhancing reliability and ease of use.
- `ObjectUtils`: Offers functions for manipulating objects, such as deep merging, cloning, and property extraction.
- `PromiseUtils`: Includes utilities for handling promises, such as timeout wrappers and promise chaining helpers.
- `URLUtils`: Contains functions for manipulating URLs, including parameter extraction, URL construction, and query string manipulation.
- `WebSocketUtils`: Encapsulates utilities specific to the Deriv WebSocket, addressing environment detection, login ID retrieval, and app ID management.

## Getting Started

To get started simply install deriv utils from the @deriv-com/utils package

```bash
npm i --save @deriv-com/utils
```

or

```bash
yarn add @deriv-com/utils
```

## Usage Example

Each of the namespaces listed above are exposed directly from the library root. In this example, we are using the `FormatUtils.formatMoney()` functionality to format different currencies to their correct decimal points or localised formatting.

```typescript
import { FormatUtils } from "@deriv-com/utils";

const formattedBalance = FormatUtils.formatMoney(1, { currency: "BTC" });
console.log(formattedBalance); // Should output 1.00000000
```

## Documentation

For detailed documentation on each utility and constant, refer to the specific files in the constants and utils directories. Each utility function and constant is documented with JSDoc comments, providing insights into their purpose, parameters, and return values. (A dedicated document page is in the pipeline)

## Contributing

We welcome contributions to the `@deriv-com/utils` library. If you have suggestions for improvements or find a bug, please open an issue or submit a pull request.

## Notes

- `@deriv-com/utils` outputs both ESM and CJS files but currently, this library only support code running in the browser environment. However, support for Node runtime is planned in the pipeline.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
"build": "tsc && vite build",
"test": "vitest run",
"test:dev": "vitest watch",
"test:coverage": "vitest run --coverage.enabled --coverage.provider=v8 --coverage.reporter=json-summary --coverage.reporter=json",
"test:coverage": "vitest run --coverage.enabled --coverage.provider=istanbul --coverage.reporter=json-summary --coverage.reporter=json",
"prepare": "rm -rf ./dist && npm run build",
"prepublishOnly": "npm run test"
},
Expand Down
4 changes: 2 additions & 2 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import * as ObjectUtils from "./object.utils";
import * as FormatUtils from "./format.utils";
import * as LocalStorageUtils from "./localstorage.utils";
import * as ObjectUtils from "./object.utils";
import * as PromiseUtils from "./promise.utils";
import * as URLUtils from "./url.utils";
import * as WebSocketUtils from "./websocket.utils";

export { ObjectUtils, FormatUtils, LocalStorageUtils, PromiseUtils, URLUtils, WebSocketUtils };
export { FormatUtils, LocalStorageUtils, ObjectUtils, PromiseUtils, URLUtils, WebSocketUtils };
24 changes: 24 additions & 0 deletions src/utils/localstorage.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,19 @@ import { LocalStorageConstants } from "../constants";

type TLocalStorageKeys = (typeof LocalStorageConstants)[keyof typeof LocalStorageConstants];

/**
* Retrieves a value from localStorage, providing type safety and parsing.
*
* This function attempts to retrieve the value associated with the given key from the browser's localStorage.
* It ensures the key is one of the predefined keys in `LocalStorageConstants` for type safety.
* The function automatically parses the stored JSON string back into its original data type `T`.
* If the stored value is the string "undefined", it converts this back into the JavaScript `undefined` type.
* Similarly, if the value is "null" or actually `null`, it returns `null`. If JSON parsing fails, it returns `null` to indicate an error or incompatible stored value.
*
* @template T The expected data type of the localStorage value.
* @param {TLocalStorageKeys} key - A type-safe key from `LocalStorageConstants`.
* @returns {(T | undefined | null)} - The value associated with the key, parsed as type `T`, or `undefined`/`null` to handle special cases or parsing errors.
*/
export const getValue = <T>(key: TLocalStorageKeys) => {
const value = localStorage.getItem(key);

Expand All @@ -15,6 +28,17 @@ export const getValue = <T>(key: TLocalStorageKeys) => {
}
};

/**
* Stores a value in localStorage under a specified key.
*
* Accepts a key from the predefined set in `LocalStorageConstants` to ensure type safety. The value to be stored
* is passed as a generic parameter `T`, which allows for any data type. This value is then stringified into JSON
* and stored.
*
* @template T The data type of the value to be stored.
* @param {TLocalStorageKeys} key - A type-safe key from `LocalStorageConstants`.
* @param {T} data - The data to store, which can be of any type. This will be stringified to JSON.
*/
export const setValue = <T>(key: TLocalStorageKeys, data: T) => {
localStorage.setItem(key, JSON.stringify(data));
};
39 changes: 39 additions & 0 deletions src/utils/url.utils.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,23 @@
import { LocalStorageConstants, AppIDConstants } from "../constants";
import { getActiveLoginid, getAppId, getEnvironmentFromLoginid } from "./websocket.utils";

/**
* Defines the structure for account information.
* @typedef {Object} AccountInfo
* @property {string} loginid - The loginid for the account.
* @property {string} currency - The currency code for the account.
* @property {string} token - The authentication token for the account.
*/
export type AccountInfo = { loginid: string; currency: string; token: string };

/**
* Extracts the login information from the URL's query parameters.
* This function parses the window's current URL search parameters looking for account, token, and currency information.
* It constructs an array of partially formed `AccountInfo` objects and filters out any entries that do not have all required properties.
* It also returns a list of parameter keys that are related to account information and can be deleted.
*
* @returns {{loginInfo: AccountInfo[], paramsToDelete: string[]}} An object containing an array of `AccountInfo` objects and an array of parameter keys to delete.
*/
export const getLoginInfoFromURL = () => {
const loginInfo: Partial<AccountInfo>[] = [];
const paramsToDelete: string[] = [];
Expand Down Expand Up @@ -35,6 +50,12 @@ export const getLoginInfoFromURL = () => {
return { loginInfo: filteredLoginInfo, paramsToDelete };
};

/**
* Filters and removes specified search parameters from the current URL.
* This function modifies the current URL's query string by removing the specified search parameters and then updates the history state.
*
* @param {string[]} searchParamsToRemove - An array of search parameter keys to remove from the current URL.
*/
export const filterSearchParams = (searchParamsToRemove: string[]) => {
const searchParams = new URLSearchParams(window.location.search);
searchParamsToRemove.forEach((p) => searchParams.delete(p));
Expand All @@ -43,6 +64,12 @@ export const filterSearchParams = (searchParamsToRemove: string[]) => {
window.history.pushState(null, "", newURL);
};

/**
* Constructs the OAuth URL with query parameters for language, app_id, and brand.
* The language is retrieved from local storage or defaults to "EN" if not set. The app_id and brand are obtained from constants.
*
* @returns {string} The constructed OAuth URL.
*/
export const getOauthURL = () => {
const language = window.localStorage.getItem(LocalStorageConstants.i18nLanguage) ?? "EN";

Expand All @@ -51,6 +78,12 @@ export const getOauthURL = () => {
}`;
};

/**
* Determines the server URL based on the active login ID.
* It first attempts to retrieve the server URL from local storage. If not found, it uses the active login ID to determine the server URL from predefined environments.
*
* @returns {string} The determined server URL.
*/
export const getServerURL = () => {
const configServerURL = window.localStorage.getItem(LocalStorageConstants.configServerURL);
if (configServerURL) return configServerURL;
Expand All @@ -59,6 +92,12 @@ export const getServerURL = () => {
return AppIDConstants.environments[getEnvironmentFromLoginid(activeLoginid)];
};

/**
* Constructs the WebSocket URL with query parameters for app_id, language, and brand.
* The server URL is determined by calling `getServerURL`, and the language is retrieved from local storage or defaults to "EN" if not set.
*
* @returns {string} The constructed WebSocket URL.
*/
export const getWebsocketURL = () => {
const serverURL = getServerURL();
const language = window.localStorage.getItem(LocalStorageConstants.i18nLanguage) ?? "EN";
Expand Down
26 changes: 26 additions & 0 deletions src/utils/websocket.utils.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,42 @@
import { LocalStorageConstants, AppIDConstants } from "../constants";

/**
* Retrieves the active login ID from either localStorage or the URL query parameters.
*
* This function first attempts to get the active login ID from localStorage using a predefined key from `LocalStorageConstants`.
* If not found in localStorage, it then tries to retrieve the login ID from the URL query parameters, specifically looking for `acct1`.
*
* @returns {string | null} The active login ID if available, otherwise `null`.
*/
export const getActiveLoginid = () => {
const urlSearchParams = new URLSearchParams(window.location.search);
const urlActiveLoginid = urlSearchParams.get("acct1");
return window.localStorage.getItem(LocalStorageConstants.activeLoginid) || urlActiveLoginid;
};

/**
* Determines the environment type based on the login ID.
*
* This function checks if the provided login ID starts with 'VR' which is the loginid prefix for virtual accounts. All others that do not match this
* is considered to be real accounts.
*
* @param {string | null} loginid - The login ID to evaluate.
* @returns {"real" | "demo"} The environment type as either 'real' or 'demo'.
*/
export const getEnvironmentFromLoginid = (loginid: string | null) => {
if (loginid && !/^VR/.test(loginid)) return "real";
return "demo";
};

/**
* Retrieves the application ID (app_id) from localStorage or based on the current domain.
*
* This function first tries to obtain the app_id from localStorage using a key specified in `LocalStorageConstants`.
* If not found, it checks a mapping defined in `AppIDConstants` to find an app_id associated with the current domain.
* If no domain-specific app_id is found, it defaults to "36300" which is the localhost app id.
*
* @returns {string} The application ID.
*/
export const getAppId = () => {
const configAppId = window.localStorage.getItem(LocalStorageConstants.configAppId);
if (configAppId) return configAppId;
Expand Down

0 comments on commit bcb7bec

Please sign in to comment.