Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ibm
GitHub Repository: ibm/watson-machine-learning-samples
Path: blob/master/cloud/ai-service-apps/nextjs-carbon-react-ui/src/app/lib/util.js
6408 views
1
import { SPACE_ID, API_KEY, BASE_DEPLOYMENT_URL } from "./variables";
2
3
// These values will be computed
4
const VERSION = "2025-01-01";
5
const IAM_STAGE = BASE_DEPLOYMENT_URL.includes("wml-fvt") ? "staging" : "production";
6
7
export const URLS = {
8
deploymentUrl: `${BASE_DEPLOYMENT_URL}?space_id=${SPACE_ID}&version=${VERSION}`,
9
aiServiceUrl: `${BASE_DEPLOYMENT_URL}/ai_service?version=${VERSION}`,
10
aiServiceStreamUrl: `${BASE_DEPLOYMENT_URL}/ai_service_stream?version=${VERSION}`,
11
};
12
13
let token = null;
14
let tokenExpiresAt = null;
15
16
export async function getToken() {
17
if (!_isTokenValid()) {
18
await generateToken();
19
}
20
return token;
21
}
22
23
function _isTokenValid() {
24
if (!token) return false;
25
if (tokenExpiresAt <= Date.now()) {
26
return false;
27
}
28
return true;
29
}
30
31
export async function generateToken() {
32
const stateSegment = IAM_STAGE === "staging" ? "test." : "";
33
const tokenUrl = `https://iam.${stateSegment}cloud.ibm.com/identity/token`;
34
const urlTokenParams = new URLSearchParams();
35
36
urlTokenParams.append("grant_type", "urn:ibm:params:oauth:grant-type:apikey");
37
urlTokenParams.append("apikey", API_KEY);
38
39
const data = await fetch(tokenUrl, {
40
method: "POST",
41
headers: {
42
"Content-Type": "application/x-www-form-urlencoded",
43
},
44
body: urlTokenParams,
45
}).then((res) => res.json());
46
47
tokenExpiresAt = data.expiration * 1000;
48
token = data.access_token;
49
}
50
51