The @blocklet/did-space-js library exports a collection of utility functions designed to simplify common tasks you'll encounter while building your application. These helpers handle operations like DID formatting, URL normalization, encoding, and error parsing, allowing you to focus on your core application logic.
You can import these utilities directly from the package:
Import Utilities
import {
toABTDid,
toDid,
normalizeEndpoint,
getSpaceServiceEndpoint,
encode,
getErrorMessage,
getErrorStatusCode,
} from '@blocklet/did-space-js';DID Formatting
DID Space uses DIDs with a did:abt: prefix. These utilities help you convert between standard DIDs and the ABT-specific format, ensuring compatibility and proper validation.
toABTDid
Adds the did:abt: prefix to a valid DID string. This is useful when you need to construct a full ABT DID from a base DID.
Parameters
- did
string(required) — A valid standard DID string.
Returns
- abtDid
string— The DID string prefixed with 'did:abt:'
Example
toABTDid Example
import { toABTDid } from '@blocklet/did-space-js';
const baseDid = 'z3T6WZD3dBtaVUgwb3rtBey8BartrJDTLrmQr';
const abtDid = toABTDid(baseDid);
console.log(abtDid); // "did:abt:z3T6WZD3dBtaVUgwb3rtBey8BartrJDTLrmQr"
try {
toABTDid('invalid-did');
} catch (error) {
console.error(error.message); // "did(invalid-did) is not a valid did"
}toDid
Removes the did:abt: prefix from a DID string, returning the base DID. It also validates that the resulting string is a valid DID.
Parameters
- did
string(required) — A DID string, typically with the 'did:abt:' prefix.
Returns
- baseDid
string— The base DID string without the prefix.
Example
toDid Example
import { toDid } from '@blocklet/did-space-js';
const abtDid = 'did:abt:z3T6WZD3dBtaVUgwb3rtBey8BartrJDTLrmQr';
const baseDid = toDid(abtDid);
console.log(baseDid); // "z3T6WZD3dBtaVUgwb3rtBey8BartrJDTLrmQr"
try {
toDid('did:abt:invalid-did');
} catch (error) {
console.error(error.message); // "did(invalid-did) is not a valid did"
}Endpoint & URL Utilities
These functions help you manage and resolve the endpoints required to communicate with a DID Space.
normalizeEndpoint
Cleans up a DID Space endpoint URL by removing query parameters and any trailing /object/ segment. This ensures you have a consistent base URL for API calls.
Parameters
- endpoint
string(required) — A full DID Space endpoint URL.
Returns
- normalizedEndpoint
string— The cleaned-up base endpoint URL.
Example
normalizeEndpoint Example
import { normalizeEndpoint } from '@blocklet/did-space-js';
const fullEndpoint =
'https://73aa3e87-znkjt5vbgnezh4p6v4dsaye61e7pxxn3vk4j.did.abtnet.io/app/api/space/z3T6WZD3dBtaVUgwb3rtBey8BartrJDTLrmQr/app/zNKsSUmUVJntiVdAPpg8vYtEgnFvSppYLf4F/object/?some=query';
const normalized = normalizeEndpoint(fullEndpoint);
console.log(normalized); // "https://73aa3e87-znkjt5vbgnezh4p6v4dsaye61e7pxxn3vk4j.did.abtnet.io/app/api/space/z3T6WZD3dBtaVUgwb3rtBey8BartrJDTLrmQr/app/zNKsSUmUVJntiVdAPpg8vYtEgnFvSppYLf4F/"getSpaceServiceEndpoint
Resolves the actual service endpoint for a given DID Space. Some spaces may use a gateway URL that redirects to a different service URL for file operations. This function handles that resolution for you.
Parameters
- normalizedEndpoint
string(required) — A normalized DID Space endpoint URL, typically from normalizeEndpoint. - defaultValue
string— A fallback value to return if the endpoint cannot be resolved. Defaults to the normalizedEndpoint itself.
Returns
- serviceEndpoint
Promise<string>— A promise that resolves to the actual service endpoint URL.
Example
getSpaceServiceEndpoint Example
import { getSpaceServiceEndpoint } from '@blocklet/did-space-js';
async function resolveEndpoint(endpoint: string) {
const serviceEndpoint = await getSpaceServiceEndpoint(endpoint);
console.log(`Service URL for ${endpoint} is ${serviceEndpoint}`);
}
const spaceUrl =
'https://73aa3e87-znkjt5vbgnezh4p6v4dsaye61e7pxxn3vk4j.did.abtnet.io/app/api/space/z3T6WZD3dBtaVUgwb3rtBey8BartrJDTLrmQr/app/zNKsSUmUVJntiVdAPpg8vYtEgnFvSppYLf4F/';
resolveEndpoint(spaceUrl);Encoding
encode
Encodes a string into a URL-safe Base64 format. This is particularly useful for encoding file paths or keys that will be used in a URL, ensuring that special characters do not cause issues.
Parameters
- key
string(required) — The string to be encoded, such as a file path.
Returns
- encodedKey
string— The URL-safe Base64 encoded string.
Example
encode Example
import { encode } from '@blocklet/did-space-js';
const filePath = 'path/to/my important file.txt';
const encodedPath = encode(filePath);
console.log(encodedPath); // "cGF0aC90by9teSBpbXBvcnRhbnQgZmlsZS50eHQ"Error Handling
When an API call fails, the SDK throws an error. These utility functions help you parse the error object to extract a human-readable message and the HTTP status code, simplifying your error handling logic.
getErrorMessage
Extracts the most relevant error message from various types of error objects that can be thrown by the underlying HTTP client (got).
Parameters
- error
Error | RequestError(required) — The error object caught in a catch block.
Returns
- errorMessage
string— A user-friendly error message.
getErrorStatusCode
Extracts the HTTP status code from an HTTP error object.
Parameters
- error
HTTPError(required) — The error object caught in a catch block.
Returns
- statusCode
number— The HTTP status code (e.g., 404, 500).
Example
Error Handling Example
import { SpaceClient, GetObjectCommand } from '@blocklet/did-space-js';
import { getErrorMessage, getErrorStatusCode } from '@blocklet/did-space-js';
import getWallet from '@blocklet/sdk/lib/wallet';
const wallet = getWallet();
const client = new SpaceClient({
endpoint: 'https://www.didspaces.com/app/api/space/...',
wallet,
});
async function fetchNonExistentFile() {
try {
const command = new GetObjectCommand({ key: 'non-existent-file.txt' });
await client.send(command);
} catch (error) {
const message = getErrorMessage(error);
const statusCode = getErrorStatusCode(error);
console.error(`Operation failed with status ${statusCode}: ${message}`);
// Expected output might be: "Operation failed with status 404: Not Found"
}
}
fetchNonExistentFile();This example shows how to use getErrorMessage and getErrorStatusCode within a try...catch block to gracefully handle an API error, such as a file not being found.
With these utilities, you can handle many of the common data transformations and error-handling scenarios required when interacting with DID Space. To see how these might be used in more complex scenarios, check out the API Reference.