UNPKG

@rocketflag/node-sdk

Version:

The Node SDK for the RocketFlag service.

58 lines (57 loc) 2.56 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const errors_1 = require("./errors"); const validateFlag_1 = require("./validateFlag"); const GET_METHOD = "GET"; const DEFAULT_API_URL = "https://api.rocketflag.app"; const DEFAULT_VERSION = "v1"; const ALPHANUMERIC_REGEX = /^[a-zA-Z0-9]+$/; const createRocketflagClient = (version = DEFAULT_VERSION, apiUrl = DEFAULT_API_URL) => { const getFlag = async (flagId, userContext = {}) => { if (!flagId) { throw new Error("flagId is required"); } if (typeof flagId !== "string") { throw new Error("flagId must be a string"); } if (typeof userContext !== "object" || userContext === null) { throw new Error("userContext must be an object"); } for (const key in userContext) { const value = userContext[key]; if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") { throw new Error(`userContext values must be of type string, number, or boolean. Invalid value for key: ${key}`); } if (key === "env" && (typeof value !== "string" || !ALPHANUMERIC_REGEX.test(value))) { throw new Error(`env values must be alphanumeric. Invalid value for env: ${[key]}`); } } const url = new URL(`${apiUrl}/${version}/flags/${flagId}`); Object.entries(userContext).forEach(([key, value]) => { url.searchParams.append(key, value.toString()); }); let raw; try { raw = await fetch(url, { method: GET_METHOD }); } catch (error) { throw new errors_1.NetworkError(`Network error: ${error instanceof Error ? error.message : "Unknown error"}`); } if (!raw.ok) throw new errors_1.APIError(`API request failed with status ${raw.status}`, raw.status, raw.statusText); let response; try { response = await raw.json(); } catch { throw new errors_1.InvalidResponseError("Failed to parse JSON response"); } if (!response || typeof response !== "object") throw new errors_1.InvalidResponseError("Invalid response format: response is not an object"); if (!(0, validateFlag_1.validateFlag)(response)) throw new errors_1.InvalidResponseError("Invalid response from server"); return response; }; return { getFlag }; }; exports.default = createRocketflagClient;