跳到正文
DEV Community· BlockVectra·· 3 小時前AI 評分35

BlockVectra Data API TypeScript 客戶端 v0.1.3 在建立客戶端時檢查 API 金鑰

Check the key before the first Data API request

AI 導讀

BlockVectra Data API TypeScript 客戶端 v0.1.3 在建立客戶端時,會拒絕缺失、空白或只含空格的 API 金鑰,並保留非空金鑰原樣;金鑰是否有效仍由 API 檢查。

正文

BlockVectra

An unset environment variable is still undefined at runtime, even when TypeScript code uses a non-null assertion. Catching that configuration error before a request makes the first call easier to debug.

The BlockVectra Data API TypeScript client now rejects a missing, empty or whitespace-only key when you create the client. It leaves non-empty keys unchanged; the API checks whether they are active and valid.

Version 0.1.3 is available as a prebuilt GitHub package:

npm install https://github.com/blockvectra/data-api-js/releases/download/v0.1.3/blockvectra-data-api-0.1.3.tgz

The package includes JavaScript and TypeScript declarations. It is not yet available through npm install @blockvectra/data-api.

Here is a Node.js TypeScript example. Keep the key in server configuration:

import { createDataClient, isDataApiError } from "@blockvectra/data-api";

const apiKey = process.env.BLOCKVECTRA_API_KEY;
if (apiKey === undefined) {
  throw new Error("Set BLOCKVECTRA_API_KEY on the server.");
}

const client = createDataClient({ apiKey });
const { data, error, response } = await client.GET(
  "/{chain}/status/freshness",
  { params: { path: { chain: "robinhood_mainnet" } } },
);

if (!response.ok) {
  const code = isDataApiError(error)
    ? error.error.code
    : "unstructured_error";
  throw new Error(`Data API ${response.status}: ${code}`);
}

if (data) {
  console.log({
    as_of_block: data.meta.as_of_block,
    refreshed_at: data.meta.refreshed_at,
  });
}

isDataApiError matters because an HTTP error body can be JSON, plain text, HTML or empty. The guard checks the Data API JSON envelope before the example reads error.error.code. It does not parse strings, rewrite the response or decide whether the key is valid. The original HTTP status remains available in every response.

The same pattern is useful for a backend service or an agent making the request. Keep the response metadata with the result, then check the dataset's coverage and refresh state against the task you are doing. An empty result or a successful status alone does not establish that the expected data is complete and current.

The release passed 37 unit tests, type checking and all nine README TypeScript examples. The prebuilt package was also installed and checked in a separate project with mock responses. The credentialed live test was skipped; this example is not a report of a new live API run.

Get a key through the normal key setup, and use the SDK README for pagination and other endpoints. The v0.1.3 release includes the archive and its SHA-256 checksums.

來源:DEV Community · dev.to