Path: blob/master/cloud/ai-service-apps/nextjs-carbon-react-ui/src/app/lib/util.js
6408 views
import { SPACE_ID, API_KEY, BASE_DEPLOYMENT_URL } from "./variables";12// These values will be computed3const VERSION = "2025-01-01";4const IAM_STAGE = BASE_DEPLOYMENT_URL.includes("wml-fvt") ? "staging" : "production";56export const URLS = {7deploymentUrl: `${BASE_DEPLOYMENT_URL}?space_id=${SPACE_ID}&version=${VERSION}`,8aiServiceUrl: `${BASE_DEPLOYMENT_URL}/ai_service?version=${VERSION}`,9aiServiceStreamUrl: `${BASE_DEPLOYMENT_URL}/ai_service_stream?version=${VERSION}`,10};1112let token = null;13let tokenExpiresAt = null;1415export async function getToken() {16if (!_isTokenValid()) {17await generateToken();18}19return token;20}2122function _isTokenValid() {23if (!token) return false;24if (tokenExpiresAt <= Date.now()) {25return false;26}27return true;28}2930export async function generateToken() {31const stateSegment = IAM_STAGE === "staging" ? "test." : "";32const tokenUrl = `https://iam.${stateSegment}cloud.ibm.com/identity/token`;33const urlTokenParams = new URLSearchParams();3435urlTokenParams.append("grant_type", "urn:ibm:params:oauth:grant-type:apikey");36urlTokenParams.append("apikey", API_KEY);3738const data = await fetch(tokenUrl, {39method: "POST",40headers: {41"Content-Type": "application/x-www-form-urlencoded",42},43body: urlTokenParams,44}).then((res) => res.json());4546tokenExpiresAt = data.expiration * 1000;47token = data.access_token;48}495051