Openapi javascript SDK generator client API access

I’ve been trying to setup a small “fullstack app” to try out the openapi SDK generator. I tried keeping everything as simple as possible but I’m still running in to issues.

Project structure:

enter image description here

On the server side I’m using express to setup i single /hi endpoint. like this

const express = require("express")
const cors = require("cors")

const app = express();

app.use(cors());

app.get("/hi", (req, res) => {
    res.json({ message: "hi from the server" });
})

app.listen(3000, () => {
    console.log("server running on port 3000");
})

My openAPI spec file looks as follows:

openapi: 3.0.0
info:
  title: api
  description: This serves as a base for other REST API's
  version: 1.0.0
paths:
  /hi:
    get:
      description: Say hi to the server
      responses:
        '200':
          description: Succes
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string

The file seems to work correctly as I can easily generate an SDK running the npx @openapitools/openapi-generator-cli generate -i ../api/docs/index.yaml -g javascript -o src/api from the client directory.

On the client side I just use basic HTML, CSS and JS to tryout the SDK.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <main>

    </main>

    <script type="module" src="./index.js"></script>
</body>

</html>
import { DefaultApi } from './api/src/index.js';

const api = new DefaultApi('http://localhost:3000');

const testConnection = async () => {
    console.log("testing connection...")
    const response = await api.hiGet()

    const data = await response.json()

    console.log(data)
}

testConnection()

But when I startup a live server from my HTML page I Get the following errors:

enter image description here

Dynamically bind floating UI (popper.js) tooltip to arbitrary DOM element with Vue.js 3 composition API

I am trying to build a TooltipHint component, that takes an anchorAt prop holding the id of another element. Then a tooltip is supposed to show up next to the element defined by anchorAt. I am using @floating-ui/vue for this. The documented usage is quite simple and works:

...
const anchor = ref(null);
const floating = ref(null);
const {floatingStyles} = useFloating(anchor, floating, {
    whileElementsMounted: autoUpdate
  });
</script>
 
<template>
  <button ref="anchor">Button</button>
  <div ref="floating" :style="floatingStyles">Tooltip</div>
</template>

In my use case however, I can’t bind the anchor element with the ref attribute in the template, since it might be defined in some other component. I only have its id and can then construct my own anchor reference like this:

...
const anchor = ref(null)
// ... after the anchor element is mounted
anchor.value = docment.getElementById(props.anchorAt)

And here begin the problems. How do I wait for a random element to be mounted? Currently I am checking for null and use nextTick to retry. It takes usually only two iterations.

...
const anchor = ref(null)
const floating = ref(null)
let floatingStyles = ref(null)
let count = 0


init()

function init() {
  const anchorDom = document.getElementById(props.anchorAt)

  if (!anchorDom) {
    if (count++ > 5) throw 'Could not find anchor'
    nextTick(init)
    return
  }
  anchor.value = anchorDom

  floatingStyles.value = useFloating(anchor, floating, {
    whileElementsMounted: autoUpdate,
  }).floatingStyles.value
}
<template>
  <div :style="floatingStyles" ref="floating">
    Debug: {{ floatingStyles }}
    <slot></slot>
  </div>
</template>

The displayed result for floatingStyles is always { "position": "absolute", "left": "0", "top": "0", "transform": "translate(0px, 0px)" }. I can think of a few reasons where it might go wrong, but don’t know how to test for those:

  • Building a ref for an element by hand might be fundamentally different compared to using the built-in ones.
  • I broke reactivity by setting floatingStyles incorrectly. Is it even a ref?

Prisma – Next.js API – Postgres – unable to update an array

  • I have Room and Video models, each room has an array of Videos .
  • I’m building a PUT route: it takes a Video as a param, the PUT route will move that video to the first position in the videos array, then perform update to the database with Prisma. At the end, the videos array did not get updated at all.

Here are my Prisma models:

model Room {
  id       String  @id @default(cuid())
  roomName String? @unique
  videos   Video[]
  user     User    @relation(fields: [userId], references: [id], onDelete: Cascade)
  userId   String

  @@index([userId])
}

model Video {
  id             String  @id @default(cuid())
  youtubeVideoId String?
  thumbnail      String?
  url            String?
  title          String?
  room           Room?   @relation(fields: [roomName], references: [roomName], onDelete: Cascade)
  roomName       String?

  @@index([roomName])
}

Here is my PUT route (simplified error handling logics):

export async function PUT(req: NextRequest) {
  const session = await getServerSession(nextAuthOptions);
  const body: Video = await req.json();
  

  const currentRoom = await prisma.room.findUnique({
    where: {
      roomName: body.roomName,
      userId: session.id,
    },
    include: {
      videos: true,
    },
  });

  const videoIndex = currentRoom.videos.findIndex(
    (video) => video.id === body.id,
  );

  const pulledVideo = currentRoom.videos.splice(videoIndex, 1)[0];
  currentRoom.videos.unshift(pulledVideo)

  const updatedRoom = await prisma.room.update({
    where: {
      userId: session.id,
      roomName: body.roomName,
    },
    include: {
      videos: true,
    },
    data: {
      videos: {
        set: currentRoom.videos,
      },
    },
  });

  return NextResponse.json(updatedRoom.videos);
}

I’ve tested in different scenarios, still have not figured out, and really appreciate if someone can give me a direction:

  • The update does not work if I set the videos with updatedVideos
  • The prisma.room.updates works if I set the videos with currentRoom.videos (the remaining array), or even Array(pulledVideo)
  • If I console.log(updatedVideos), it shows the correct array that I want to set. But the result value of the prisma.room.update did not change from the original.

router. function doesn’t execute after auth middleware

router.get('/', auth, function(req, res){
    funcs.getBalance(req.params.user, function(err, result){
        if (err) {
            console.log(err);
            res.status(500).json({error: err.message});
        } else {
            res.status(200).json(result[0]);
        }
    })
});

Here we have a route. Notice the auth middleware. It checks if the user has an valid web token. The problem is that the router.get function doesn’t execute anything after auth has been executed

function auth(req, res, next) {
    const token = req.cookies.token;

    if (!token) {
        return res.status(401).json({message: "No token"});
    }

    jwt.verify(token, process.env.SECRET_TOKEN, (err, decoded) => {
        if (err) {
            return res.status(401).json({message: "Invalid token"});
        }

        req.user = decoded;

        return res.status(200).json({message: "Authentication ok"});
    });
}

I’ve tried small tweaks to the code but I honestly don’t know why everything stops after auth function.
I’m new to api development and javascript in general so the problem could be something small and simple that I don’t have the eyes to notice yet.

console.log is working differently than I expected in this code

This is a exercise to creat an aleatory number with conditionals and all, but the console.log doens’t show the number in the console , to help test the code , showing the number but is not working,i don’t know if it is my code fault or the navigator , i have already tried in two computers and the same happens , so i think is something with the code , maybe misssing an idex.html ?

<meta charset="UTF-8">
<script>
  let numeroSecreto = parseInt(Math.random() * 10 + 1);
  console.log(numeroSecreto);
  let tentativa = 1;
  let chute;

  while (chute != numeroSecreto) {
    chute = prompt('Qual o seu chute ?');

    if (chute == numeroSecreto) {
      break;
    } else {
      if (chute > numeroSecreto) {
        alert(`O numero secreto é menor que ${chute}`);
      } else {
        alert(`O numero secreto é maior que ${chute}`);
      }
      tentativa++;
    }

  }
  let palavraTentativa = tentativa > 1 ? 'tentativas' : 'tentativa';

  alert(`Isso aí, você descobriu o número secreto ${numeroSecreto} com ${tentativa} ${palavraTentativa}`)
</script>

String concatenation with ternary statement [closed]

I am trying to concat a string with a ternary statement but when the ternary is true, it does not concatenate the 1st string.

message={eventId+" : logId@"+logId[1]+"| "+ retry ? "retry parent : logId@"+_logId : false}

Returns retry parent : logId@49382078

I am expecting

72057594044324940 : logId@49391994 | retry parent : logId@49382078

Understanding the Relationship Between EventEmitter in Node.js and addEventListener in the Browser

I’m currently delving into Node.js and exploring its unique features compared to JavaScript in the browser environment. One concept that caught my attention is the EventEmitter, which handles events in Node.js applications. Upon initial inspection, it seems reminiscent of the familiar addEventListener method used in the DOM. However, given the differences between Node.js and browser environments, I’m seeking clarification on the nature of their relationship.

My main query revolves around whether it’s appropriate to view EventEmitter and addEventListener as analogous functionalities across different runtime environments. Essentially, I’m wondering if EventEmitter serves a similar purpose in Node.js as addEventListener it does in the browser.

While I recognize there may be distinct nuances due to the differing runtime contexts, I’m interested in understanding if there are fundamental similarities that warrant drawing parallels between these two event-handling mechanisms.

Could someone shed light on whether it’s valid to equate EventEmitter with addEventListener, and if not, what differentiates them significantly? I’m aiming to establish accurate mental connections between these concepts to deepen my comprehension of event-driven programming in both Node.js and browser environments.

Thank you for your insights and guidance.

Form field not undisabling when the field above is selected

I am trying to get the attack-damage field in my form to be undisabled if the attack has been selected above.

To attempt this I made the damage field disabled by default and then added an onchange attribute to the select element. This onchange executes a function that changes the disabled and required attributes for the attack damage.

When I use the form, the damage field is always disabled and the attack-handling function doesn’t seem to be getting called. I have added the script tag at the end of the body element.

            <!-- attack 2 -->
            <div class="form-group mb-3">
              <label for="attack2" class="form-label"
                >Attack 2 (Optional)</label
              >
              <select
                name="attack2"
                class="form-select"
                id="attack2"
                onchange="handleAttackOptions()"
              >
                <option selected value="-1">Select Attack</option>
                <% attacks.forEach((element) => { %>
                <option value="<%=element.attack_id%>">
                  <%=element.attack%>
                </option>
                <% }) %>
              </select>
            </div>

            <!-- attack2 damage -->
            <div class="form-group mb-3">
              <label for="attack2Damage" class="form-label"
                >Attack 2 Damage</label
              >
              <input
                disabled
                min="1"
                max="999"
                type="number"
                class="form-control"
                id="attack2Damage"
                placeholder="Enter damage"
                name="attack2Damage"
              />
            </div>

This is my Javascript attempt


/**
 * This method disables an attack options in form if the attack has not been selected
 * @param {int} num
 */
function handleAttackOptions() {
  console.log("Function called");

  const attackField = document.getElementById("attack2");
  const damageField = document.getElementById("attack2" + "Damage");

  if (attackField.value == "-1") {
    // an attack has not been selected - disable the options
    damageField.disabled = true;
    damageField.required = false;
  } else {
    // an attack has been selected - show the options and make them required
    damageField.disabled = false;
    damageField.required = true;
  }
}

I expected the field to be undisabled when an attack option is selected but this is not happening

Im getting this error in Next js : Export encountered errors on following paths: /Cartoon/page: /Cartoon

Whenever I try to deploy my project on firebase, I get this error in the terminal:

Export encountered errors on following paths:
/Cartoon/page: /Cartoon

Error: An unexpected error has occurred.

enter image description here

Here’s the code:

enter image description here

export default async function page({ name }) {
let response = await fetch(https://api.themoviedb.org/3/search/tv?api_key=24a1f89401be144ce02466512297e932&query=${name}&include_adult=true&language=en-US&page=1)
let cartoon = await response.json();
console.log(cartoon)
return (

<img className=’rounded-t-xl’ src={https://www.themoviedb.org/t/p/w600_and_h900_bestv2${cartoon.results[0].poster_path}} />

{cartoon.results[0].name}

)
}

I tried to use getStaticProps(), axios and use client, but none solved the problem.

Docxtemplater – using multiple filters | Country-specific format and custom decimals

Is there a way to apply multiple filters in docxtemplater?

I would like to apply a “toLocaleNumber” filter as well as a “toFixed” filter.

Example:
Input for variable ‘Price’: 500.50

In the document it says “EUR {price | toLocaleNumber: ‘de-de’}”
and the output would be “EUR 500,5”.

It’s obviously missing the last 0. If the input was 500, I would also like to show two decimals to have 500,00. I found the toFixed function that would take care of it, but I’m not sure how to combine two filters on the same variable.

Any ideas?

Many thanks,
Jenny

connecting to a pancakeSwap smart contrac, AbiError: Parameter decoding error: Returned values aren’t valid, did it run Out of Gas?

i’m trying to connect to a smart contract on pancakeSwap, using web3.js; from the official documentation i know what methods i should use to connect to the contract. first i connect to my provider which is quickNode, and then with the addresses taken from bscscan.com i connect to the pancakeSwap routerV2 address.
I use metamask wallet and I think I am connected to default BNB SmartChain.

below is the JavaScritp code i used.

const { Web3 } = require('web3');

const web3 = new Web3("https://ultra-frequent-needle.quiknode.pro/162ggHIDDEN123/");
//ABI
const pancakeRouterV2ABI = require("../scripts/pancakeABI.json");
//tokens pancakeSwap
const pancakeSwapRouterAddress="0x10ED43C718714eb63d5aA57B78B54704E256024E";
//CONTRACTS
const pancakeContract=new web3.eth.Contract(pancakeRouterV2ABI,pancakeSwapRouterAddress);


async function tryRunMethod(){
  const amounts = await pancakeContract.methods.getAmountsOut(
    web3.utils.toWei("1", "ether"), 
  [ethPancakeSwapAddress,usdPancakeSwapAddress]).call();


  console.log("amount=",amounts);
}

tryRunMethod();

no matter what method I try to run, the error will always be the same:

AbiError: Parameter decoding error: Returned values aren’t valid, did it run Out of Gas? You might also see this error if you are not using the correct ABI for the contract you are retrieving data from, requesting data from a block number that does not exist, or querying a node which is not fully synced.

Instead I can easily connect to a contract on uniswap with etherscan addresses, and I can call any method I want to

sorting list of hotels with javascript [closed]

i have hotels list in wordpress
i wanna order by prices hotel with 2 bed price
for example visit this page
https://metaflytour.com/tours/%D8%AA%D9%88%D8%B1-%D8%A2%D9%86%D8%AA%D8%A7%D9%84%DB%8C%D8%A7-%D8%AF%DB%8C-%D9%88-%D8%A8%D9%87%D9%85%D9%86-1402-2/

document.addEventListener("DOMContentLoaded", function() {

    let divs = Array.from(document.querySelectorAll('.hadibold'));


    let divValues = divs.map(div => ({
        value: parseInt(div.textContent, 10),
        element: div
    }));

    divValues.sort((a, b) => a.value - b.value);

    const parent = divs[0].parentNode;
    divValues.forEach(div => parent.appendChild(div.element));
});

Map is Still Grey After Loading

We are developing a website integrated with Google Maps, and when we open the website on mobile, we encounter an issue with the Google Maps display. Upon loading the website, the map is not visible and appears as a grey color. We can see a cluster of markers clearly, but the map itself is not visible as shown in the screenshot below. However, when we zoom in or out on the map, we can see the map clearly.enter image description here

Please suggest possible reasons why this is happening and solutions that might work. Note:

We have already tried the map resize event.enter image description here
We have already tried giving proper height and width in pixels for the map element.enter image description here

PassportJS login problem – please help. :)

I have a project where i am making a login system with passport.
I use nodejs and mysql. What happens is when i enter info and press login, it just failureRedirect: ‘/auth/login’ without any logs.

Route file

const LocalStrategy = require('passport-local').Strategy;
const passport = require('passport');
const bcrypt = require('bcrypt');
const db = require('../models');
const User = require('../models').User; // Import the User model

passport.serializeUser((user, done) => {
  done(null, user.email);
});

passport.deserializeUser(async (email, done) => {
  try {
      const user = await User.findOne({ where: { email: email } });
      if (user) {
          done(null, user);
      } else {
          done(null, false);
      }
  } catch (err) {
      done(err, null);
  }
});


passport.use(new LocalStrategy(
  async (email, password, done) => {
    try {
      const user = await User.findOne({ where: { email: email } });
      console.log('User:', user); // Log retrieved user object

      if (!user) {
        return done(null, false);
      }

      const passwordMatch = await bcrypt.compare(password, user.EncryptedPassword);
      console.log('Password Match:', passwordMatch); // Log comparison result

      if (passwordMatch) {
        return done(null, user);
      } else {
        return done(null, false);
      }
    } catch (err) {
      return done(err, false);
    }
  }
));

router.get('/login', function (req, res, next) {
    res.render('login', { title: 'SY&FK', user: req.user });
  });

  router.post('/login/password',
  passport.authenticate('local', { failureRedirect: '/auth/login', failureMessage: true }),
  function(req, res) {
    console.log("authenticate");
    console.log(err);
    console.log(user);
    console.log(info);
    res.redirect('/');
  });


router.get('/signup', function (req, res, next) {
  res.render('signup', { title: 'SY&FK', user: req.user });
});

router.post('/signup', async (req, res) => {
  try {
    const { firstname, lastname, phone, address, zip, city, email, password } = req.body;

    // Check for missing fields
    const missingFields = ['firstname', 'lastname', 'phone', 'address', 'zip', 'city', 'email', 'password']
      .filter(field => !req.body[field]);

    if (missingFields.length > 0) {
      return res.status(400).json({ message: 'Missing required fields', missingFields });
    }

    // Generate a random salt
    const salt = await bcrypt.genSalt(10); // Use bcrypt.genSalt for secure random salt

    // Hash the password using bcrypt with the generated salt
    const hashedPassword = await bcrypt.hash(password, salt);

    const newUser = await db.User.create({
      firstname,
      lastname,
      phone,
      address,
      zip,
      city,
      email,
      EncryptedPassword: hashedPassword,
      // Do not store plain text salt in the database
      Salt: salt,
      RoleID: 1,
    });

    res.redirect('/auth/login'); // Or your desired redirection
  } catch (error) {
    console.error('Error in signup route:', error);
    res.status(500).json({ message: 'Internal server error' });
  }
});

App.js relevant

const { Sequelize, Model, DataTypes } = require('sequelize');
var db = require("./models");
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
var session = require('express-session');
const flash = require('express-flash');
const bcrypt = require('bcrypt');

app.use(session({
  secret: 'xxxxxxxxxx',
  resave: false,
  saveUninitialized: false,
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(passport.authenticate('session'));
app.use(flash());

app.use('/auth', authRouter);

Login.ejs relevant text

<form action="/auth/login/password" method="POST">
                <div class="row gy-3 gy-md-4 overflow-hidden">
                  <div class="col-12">
                    <input type="email" class="form-control" name="email" id="email" placeholder="[email protected]" required>
                    <label for="email" class="form-label">Epost</label>
                  </div>
                  <div class="col-12">
                    <input type="password" class="form-control" name="password" id="password" value="" placeholder="Passord" required>
                    <label for="password" class="form-label">Passord</label>
                  </div>
                  <div class="col-12">
                    <div class="form-check">
                      <input class="form-check-input" type="checkbox" value="" name="remember_me" id="remember_me">
                      <label class="form-check-label text-secondary" for="remember_me">
                        Hold meg innlogget
                      </label>
                    </div>
                  </div>
                  <div class="col-12">
                    <div class="d-grid">
                      <button class="btn bsb-btn-xl btn-primary" type="submit">Logg inn</button>
                    </div>
                  </div>
                </div>
              </form>

Thanks in advance

Tried many different versions of the passport implementation.

Crypto.js Uncaught RangeError:Invalid array length

I need to do uploadFile, I using Crypto.js encrypt the file with MD5.
But when the file size over than 200Mb. I got this error message.

Uncaught RangeError: Invalid array length

I wondering to know how should I resolve the question? And Why do I get this error message?

This is my code:

<script>
import CryptoJS from 'crypto-js'
const calculateMD5 = (file) => {
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader()
    fileReader.onload = function () {
      const hash = CryptoJS.MD5(CryptoJS.lib.WordArray.create(fileReader.result))
      resolve(hash.toString())
    }
    fileReader.onerror = reject
    fileReader.readAsArrayBuffer(file)
  })
}

const splitFile = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const CHUNK_SIZE = 10 * 1024 * 1024
  if (target.files && target.isDefaultNamespace.length > 0) {
    const file = target.files[0]
    const fileSize = file.size
    const md5hash = await calculateMD5(file)
    console.log(md5hash)

    const chunks = Math.ceil(fileSize / CHUNK_SIZE)
    const fileChunks = []
    let start = 0
    let end = CHUNK_SIZE
    console.log(end, fileSize)

    for (let i = 0; i < chunks; i++) {
      if (end > fileSize) {
        console.log('if', i)

        end = fileSize
      }
      const chunk = file.slice(start, end)
      console.log(chunk)

      fileChunks.push(chunk)
      start = end
      end = start + CHUNK_SIZE
    }
    console.log(fileChunks)
  }
}
</script>
<template>
 <input type="file" @change="splitFile">
</template>

The information I found shows Seems like a restriction.

https://stackoverflow.com/questions/55465821/getting-heap-out-of-memory-error-even-when-available-heap-memory-is-much-larger

https://stackoverflow.com/questions/54452896/maximum-number-of-entries-in-node-js-map/54466812#54466812