import Resolver from '@forge/resolver';
import api, { fetch, route } from '@forge/api';
let _tokens = [];
const apiKey = "********************";
const backend = "WEAVY_URL";
resolver.define("token", async (req, res) => {
// get jira user's account id
const accountId = req.context.accountId;
// check if we already have a token stored for the user or if we need to refresh the token
if ((!req.payload.refresh || req.payload.refresh === "false") && _tokens.find((t) => t.accountId === accountId)) {
res.json({ access_token: _tokens.find((t) => t.accountId === accountId).access_token });
} else {
// get an access token from weavy backend
let response = await fetch(`${backend}/api/users/${accountId}/tokens`, {
method: 'POST',
headers: {
'content-type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({ expires_in: 3600 })
});
if (response.ok) {
let data = await response.json();
// store the access token so we don't need to call the api every time (unless we need to refresh the token)
_tokens = [..._tokens.filter((t) => t.accountId !== accountId), { accountId: accountId, access_token: data.access_token }];
return data.access_token;
} else {
return ({ message: "Could not get access token from server!", accountId: accountId, error: response })
}
}
});
export const handler = resolver.getDefinitions();