import { network, user, vault } from '@oliveai/ldk';
const tokenKey = 'myloop_token';
const expirationKey = 'myloop_expiration';
const oneDayMs = 24 * 60 * 60 * 1000;
const tokenUrl = 'http://127.0.0.1:8080/token';
const apiUrl = 'http://127.0.0.1:8080/myTestApi';
async function refreshToken() {
// We'll use the jwt provided by the user aptitude to act as our authorization
// to hit the token endpoint
const jwt = await user.jwt();
const response = await network.httpRequest({
Authorization: `Bearer ${jwt}`,
if (response.statusCode != 200) {
const token = await network.decode(response.body);
const expirationTime = Date.now() + oneDayMs;
// Once we've retrieved the new token, we can store it securely in the vault
await vault.write(tokenKey, token);
await vault.write(expirationKey, expirationTime);
// This will be the main entrypoint into our example
let exists = await vault.exists(expirationKey);
// If the key exists in vault, we need to make sure it hasn't expired
let expirationTimeStr = await vault.read(expirationKey);
let expirationTime = parseInt(expirationTimeStr);
if (expirationTime < Date.now()) {
// Check to make sure the user token exists before retrieving it
// Something could have gone wrong with refreshToken();
const userTokenExists = await vault.exists(tokenKey);
// Read the key and make an API request to get our data
const userToken = await vault.read(tokenKey);
const someData = await network.httpRequest({
Authorization: `Bearer ${userToken}`,
// Do something with someData