Quantcast
Channel: Active questions tagged rest - Stack Overflow
Viewing all articles
Browse latest Browse all 3663

Javascript-function only runs if called before another function

$
0
0

I am getting to my limits here. I don't get the way asynchronicity behaves in my code. I am using a rest API from a js. Within my code there are to functions that are somewhat similar. They read keys and addresses from a json and they are making a API call. One of the functions behaves differently, depending on where in the script it is called. It really confuses me.This is my script:

index.mts

import { authenticate } from "./apiCalls/authenticate.mjs";import { bannerInfo } from "./apiCalls/bannerInfo.mjs";import { state } from "./apiCalls/state.mjs";import { chooseAction } from "./interactions/chooseAction.js";import { pushCertainBanner } from "./apiCalls/pushCertainBanner.js";//this function changes their behaviorawait pushCertainBanner();state();await authenticate();await bannerInfo();setInterval(() => {    state();    authenticate();    bannerInfo();}, 590000);chooseAction();

Case 1:

When pushCertainBanner() is called first, it runs well. If there is a good token it executes fine and logs an empty object {} as expected. Otherwise it logs the api response with a 401 error. I want the function to be called later in the code because I always want to be able to have a good token.

Case 2:

When pushCertainBanner() is called after authenticate() , it executes. I can see the call doing its work on the server but I do not get the console logs.

Case 3:

When pushCertainBanner() is called after bannerInfo() nothing happens. The code continues to work fine otherwise but this function does nothing anymore.

bannerInfo.mts

import axios from 'axios';import { getToken } from '../fs_helpers/getToken.js';import { getAdress } from '../fs_helpers/getAdress.js';import fs from 'fs';import * as path from 'path';export async function bannerInfo() {  let token = await getToken();  let config = {  method: 'get',  maxBodyLength: Infinity,  url: 'https://'+ await getAdress() +'/api/v2/Banners',  headers: { 'Authorization': token  },  timeout: 2000  };  const filePath = './configs/banners.json';  const dir = path.dirname(filePath);  try {    const response =  await axios.request(config);    const bannerData = JSON.stringify(response.data, null, 2);    await fs.promises.mkdir(dir, { recursive: true });    await fs.promises.writeFile(filePath, bannerData, 'utf8');    console.log("🇪🇺 Banner gefunden");  } catch (error) {    if (error.response && error.response.status === 401) {console.error("❌ Unauthorized");}    let bannerData: any = {};    try {      bannerData = JSON.parse(await fs.promises.readFile(filePath, 'utf8'));    } catch (error) {      console.log("🔎 Bannerdata file not found ... ✍🏼creating");    }    await fs.promises.writeFile(filePath, JSON.stringify(bannerData, null, 2), 'utf8');    console.error("🔑❌ Banner fetching failed");  }};

authenticate.mts

import axios from 'axios';import { promises as fs } from 'fs';import * as path from 'path';import { getAdress } from '../fs_helpers/getAdress.js';async function getLoginData(){  try {    const data = await fs.readFile('./configs/loginData.json', 'utf8');    return data;  } catch (error) {    console.error("No login data found");    return null  }}export async function authenticate(){  let data = await getLoginData();  let config = {    method: 'post',    maxBodyLength: Infinity,    url: 'https://'+ await getAdress() +'/api/authenticate',    headers: { 'Content-Type': 'application/json'    },    data : data,    timeout: 2000  };  const filePath = './configs/auth.json';  const dir = path.dirname(filePath);  try {    const response =  await axios.request(config);    response.data.authentificationSuccess = true;    const authData = JSON.stringify(response.data, null, 2);    await fs.mkdir(dir, { recursive: true });    await fs.writeFile(filePath, authData, 'utf8');    console.log("🔑 Authentication successful");  } catch (error) {    if (error.response && error.response.status === 401) {console.error("❌ Unauthorized");}    let authData: any = {};    try {      authData = JSON.parse(await fs.readFile(filePath, 'utf8'));    } catch (error) {      console.log("🔎 Authentication file not found ... ✍🏼creating");    }    authData.authentificationSuccess = false;    await fs.writeFile(filePath, JSON.stringify(authData, null, 2), 'utf8');    console.error("🔑❌ Authentication failed");  } }

pushCertainBanner.mts

import axios, { get } from "axios";import { getAdress } from '../fs_helpers/getAdress.js';import { getToken } from '../fs_helpers/getToken.js';import { time } from "console";export async function pushCertainBanner() {  let token = await getToken();  let adress = await getAdress();let data = JSON.stringify({"banners": [    {"bannerName": "sample banner","useDefaultBannerMessage": false,"text": "I was started by an api call","infinite": false,"duration": 15    }  ]});let config = {  method: 'put',  maxBodyLength: Infinity,  url: 'https://'+ adress +'/api/v2/LinearTranscodeServices/secret/Banners',  headers: { 'Authorization': token,'Content-Type': 'application/json'  },  data : data,  timeout: 2000};axios.request(config).then((response) => {  console.log(JSON.stringify(response.data));}).catch((error) => {  console.log(error);});}

I thought the Problem might have to do with the filesystem being accessed by both of the functions but because of the await they shouldn't access it at the same time. To be sure it was not a timing conflict I tried a delay but it didn't help either.

function delay(ms) {    return new Promise(resolve => setTimeout(resolve, ms));  }state();await authenticate();await bannerInfo();await delay(2000);await pushCertainBanner();

Viewing all articles
Browse latest Browse all 3663

Trending Articles