How to import custom images into the Img.ly SDK in a React.js project?

I’m working on a React.js project that uses the Img.ly SDK (CreativeEditor SDK) for image editing. I want to allow users to upload their custom images and have them appear in the editor’s upload section, so they can be selected for editing.
image – 1
I’ve successfully implemented an API that uploads the user’s images to the server, but after a page refresh, the images disappear from the editor’s upload section. I would like to fetch the uploaded images and display them in the Img.ly SDK’s media library, so they persist across sessions.
image – 2
image – 3
enter image description here
I’ve gone through the SDK documentation, but I couldn’t find a detailed example addressing this specific use case. Could anyone provide guidance or code examples to:

  • Handle the upload process for custom images within the Img.ly SDK.
  • Ensure the uploaded images are displayed in the SDK’s media library for editing.
  • Persist the uploaded images across sessions, so they are available after a page refresh.

What I Tried:
I’ve implemented an API that uploads the user’s images to a server, and I can successfully upload images and see them in the Img.ly editor. However, after refreshing the page, the uploaded images disappear from the editor’s upload section.

What I Expected:
I expected the images to persist after refreshing the page, automatically fetching and displaying them in the Img.ly SDK’s media library.

What Happened:
The images do not persist, and the media library is empty after a refresh. I’m looking for a way to load the previously uploaded images into the media library whenever the editor is initialized.

How to validate only date part of ISO8601 string in ECMAScript languages?

The topic Check if a date string is in ISO and UTC format is focused on full ISO8601 strings including the time part, so as it has been clearly declared, the regular expression from this solution will fail if the string will include only the date part like 2018-10-18. This question is about ISO8601 strings only with date part.

AFAIK the date part in ISO8601 string including 10 characters, but new Date("1970-1-01") (9 characters) will work. So I suppose, the first question will be: are first 10 characters reserved for the date part in ISO8601 string? If so the /^d{4}-d{2}-d{2}$ should works. If no, I afraid , the regular expression could be too complicated. Maybe new Date(targetISO_String).toString() === "Invalid Date will be enough?

How to add Debug Run functionalities in monaco editor

We have Run Debug functionalities in our native standalone application and we are trying to develop same into Web Application. We are using monaco editor in our Web Application.

We need to debug line by line code in monaco editor to get the outcome. Anyone have idea to implement Run Debug option in monaco edior?

monaco editor implementation in our application

native standalone application with Run Debug functionalities

How to make mansory elements responsive yet take up all available space?

I am using mansory.js to layout my images and their details( all in a div class=”main-section”) , They all are contained in a div class=”main”, The problem I am facing is due to how the elements widths is being calculated, If i say columnWidth:300 It works fine, but when i resize the window only below 300, ( like i expand the window about 150px wider, ) the layout stays the same leaving 150px blank on the right hand side, I want the column width to be dynamic so that the width of the items adjusts and increases so that they all add up to 100% of the container,
I tried using a function for it, like to calculate the width but it acts weirdly, and stacks all images on top of each other,( kinda, i don’t get it it just gets messed up)

this js code, adds those white spaces on the right hand side,

`
var elem = document.getElementById('main');
var msnry = new Masonry(elem, {
    itemSelector: '.main-section',
    columnWidth: 300,
    isFitWidth:true,
    percentPosition: true,
    gutter: 16 // Spacing between items
});



document.addEventListener("DOMContentLoaded", function () {
    setTimeout(function() {
        msnry.layout();
    }, 350); 
});

window.addEventListener('resize', function() {
    setTimeout(function() {
        msnry.layout();
    }, 350); 
});`

this code does that jumbling of the items and messes up everythig

`....snry = new Masonry(elem, {
    itemSelector: '.main-section',
    columnWidth: function() {
        var elem = document.getElementById('main');
        var containerWidth = elem.offsetWidth;
        var numColumns = Math.floor(containerWidth / 300); 
        console.log( containerWidth / numColumns); 
        return 300;
    },
    isFitWidth:true,
    percent.....`

[as you can see i tried debugging using console log and just returning 300, but it doesn’t work, and displays nothing in console]

i attached the jumbled up image and the white space image with it too

white space on right
Weird image layout

also heres the css for container

`    #main-container{//this covers the main
        width: calc(100% - 160px);
        margin:0px 80px;
        margin-top: 40px;
    }
    #main{
        width: 100%;
    }
    .main-section{
        width: 300px;
        position: relative;
        transition: all 0.1s ease-out;
        background-color: white;
        box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.04);
        margin-bottom: 16px;
        border-radius: 16px;
    }
`

How to create pickup Distance Calculation miles pricing in WordPress

I am trying to pick up Distance Calculation miles pricing in WordPress but I have not succeeded yet. any help would be appreciated.

Here is my code. but I don’t know what is wrong with my code.

HTML Form
in WordPress where users can input the pickup and destination locations.

function google_maps_distance_calculator_shortcode() {
    ob_start();
    ?>
    <div class="distance-calculator-form">
        <form id="distance-calculator-form">
            <h2>Calculate Distance and Cost</h2>

            <label for="pickup">Pickup Location:</label>
            <input type="text" id="pickup" name="pickup" placeholder="Enter pickup location"><br>

            <label for="destination">Destination Location:</label>
            <input type="text" id="destination" name="destination" placeholder="Enter destination location"><br>

            <p>Distance: <span id="distance">0 km</span></p>
            <p>Total Cost: <span id="total-cost">$0.00</span></p>

            <!-- Button to calculate distance and cost -->
            <button type="button" id="calculate-button">Calculate Distance & Cost</button>
        </form>
    </div>
    <?php
    return ob_get_clean();
}
add_shortcode('google_maps_distance_calculator', 'google_maps_distance_calculator_shortcode');

JavaScript to Calculate Distance Using Google Maps API

document.addEventListener('DOMContentLoaded', function() {
    let map;
    let directionsService;
    let directionsRenderer;

    function initMap() {
        // Initialize the Google Maps objects
        directionsService = new google.maps.DirectionsService();
        directionsRenderer = new google.maps.DirectionsRenderer();
        map = new google.maps.Map(document.getElementById('map'), {
            center: { lat: -34.397, lng: 150.644 },
            zoom: 8
        });
        directionsRenderer.setMap(map);
    }

    function calculateDistance() {
        const pickup = document.getElementById('pickup').value;
        const destination = document.getElementById('destination').value;

        if (pickup && destination) {
            const request = {
                origin: pickup,
                destination: destination,
                travelMode: 'DRIVING'
            };

            directionsService.route(request, function(result, status) {
                if (status == 'OK') {
                    directionsRenderer.setDirections(result);

                    const distance = result.routes[0].legs[0].distance.value / 1000; // distance in km
                    const cost = distance * 2; // Example: $2 per km

                    document.getElementById('distance').textContent = distance.toFixed(2) + ' km';
                    document.getElementById('total-cost').textContent = '$' + cost.toFixed(2);
                } else {
                    alert('Could not calculate distance: ' + status);
                }
            });
        } else {
            alert('Please enter both pickup and destination locations.');
        }
    }

    document.getElementById('calculate-button').addEventListener('click', calculateDistance);

    // Load the map
    initMap();
});

Add Google Maps Script to Your WordPress Site

function enqueue_google_maps_script() {
    wp_enqueue_script('google-maps', 'https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_MAPS_API_KEY&libraries=places', null, null, true);
}
add_action('wp_enqueue_scripts', 'enqueue_google_maps_script');

Add Styling

.distance-calculator-form {
    max-width: 600px;
    margin: 0 auto;
    padding: 20px;
    background-color: #f9f9f9;
    border: 1px solid #ddd;
    border-radius: 8px;
}

.distance-calculator-form label {
    display: block;
    margin-bottom: 8px;
    font-weight: bold;
}

.distance-calculator-form input[type="text"] {
    width: 100%;
    padding: 8px;
    margin-bottom: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
}

#calculate-button {
    background-color: #007cba;
    color: white;
    padding: 10px 20px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

#calculate-button:hover {
    background-color: #005f8d;
}

#distance, #total-cost {
    font-weight: bold;
}

How to implement file streaming for an Excel file download in FastAPI to initiate immediate download in browser?

I am building a FastAPI application and need to implement an endpoint that allows users to download an Excel file using streaming. The goal is for the file to start downloading immediately when the user clicks a download button in their browser, similar to how files are downloaded from websites.

Here is my current implementation:


from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import openpyxl
import io
import time

app = FastAPI()

@app.get("/download_excel/")
async def get_attendance_report():
    start_time = time.time()
    
    # Create Excel file in memory
    wb = openpyxl.Workbook()
    ws = wb.active

    headers = ["id", "name", "age", "city", "is_student"]
    ws.append(headers)

    # Sample data
    data = [
        {'id': 1, 'name': 'Alice', 'age': 30, 'city': 'New York', 'is_student': True},
        {'id': 2, 'name': 'Bob', 'age': 25, 'city': 'Los Angeles', 'is_student': False}
    ]
    
    for record in data:
        ws.append([record['id'], record['name'], record['age'], record['city'], record['is_student']])

    log.info(f"File generation time: {time.time() - start_time} seconds")

    def iterfile():
        with io.BytesIO() as byte_stream:
            wb.save(byte_stream)
            byte_stream.seek(0)
            while chunk := byte_stream.read(262144):  # 256KB chunks
                yield chunk

    headers = {
        'Content-Disposition': 'attachment; filename="employee_attendance_report.xlsx"',
        'Transfer-Encoding': 'chunked'
    }
    
    return StreamingResponse(iterfile(), media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', headers=headers)



Problem:

1.When I click the download button, I receive a status code 200 immediately, but it takes more time for the download process to start.

2.I want the file to be downloaded immediately when the user clicks the download button. The file should appear in the browser’s download manager, showing its name and progress.

What I’ve Tried:
Implemented StreamingResponse to stream the file in chunks.
Set the Content-Disposition header to indicate an attachment and filename.
Questions:
Is the StreamingResponse implementation correct for streaming an Excel file?
Are there any additional headers or configurations required to ensure that the file starts downloading immediately in the browser?
How can I reduce the delay between receiving the status code and the start of the download process?

I have a shopping app component that I only want to show on a particular page. Tried useLocation but the component has dynamic ids

I want to know how I can make my “page” variable in the below code dynamic, so I can properly compare it with the location.pathname variable which will have dynamic page ids.

import { useLocation } from 'react-router-dom';

function AddToCart() {
  function IsItemPage() {
    const page = '/item_page';
    const location = useLocation();
    console.log(location);
    if (location.pathname == page) {
      return true;
    };
  }

  return IsItemPage() && ( 
    <span className='add-to-cart'>
      <button>Add Item</button>
      <button>Cart</button>
    </span>
  );
}

export default AddToCart;

Now each item I open from the home page has a unique id for example: "/item_page/2" and obviously I cannot hard code it. If I provide the absolute path to the “page” variable like "/item_page/1" or something, the component is working as expected but only for that particular item with ‘id: 1’. But I need to be able to achieve this for every item I open from the home page.

So how can I achieve this?

React Native Reanimated interpolateColor issue

I have a simple animated circular progress using react-native-svg and react-native-reanimated.

This is the AnimatedCircle

<Svg height={"90%"} width={"90%"} viewBox="0 0 100 100">
    <AnimatedCircle
        animatedProps={animatedCircleProps}
        cx="50"
        cy="50"
        r="45"
        stroke="rgb(247, 30, 43)"
        strokeWidth="10"
        strokeDasharray={`${radius * Math.PI * 2}`}
        strokeLinecap="round"
    />
</Svg>

This is the animatedCircleProps used in the animatedProps

const animatedCircleProps = useAnimatedProps(() => {
    const interpolatedColor = interpolateColor(
        percentage.value,
        [0, 50, 100],
        [
            "rgb(247, 30, 43)",
            "rgb(255, 248, 48)",
            "rgb(32, 250, 45)",
        ],
    );

    return {
        stroke: interpolatedColor,
        strokeDashoffset: (1 - percentage.value / 100) * circumference,
    };
});

Using the value provided by interpolateColor always gives this error:

 ERROR  ReanimatedError: Exception in HostFunction: java.lang.ClassCastException: java.lang.String cannot be cast to com.facebook.react.bridge.ReadableMap, js engine: reanimated

Is there something I’m missing? Isn’t the value over here also a string? stroke="rgb(247, 30, 43)"

Why doesn’t it work with the animatedCircleProps?

React Native Reanimated useSharedValue() value is unexpected inside useAnimatedGestureHandler()

Here is the code I am using to initialize my shared values:

export default function CardList({ children, players, setPlayers, playerTurnCounter }) {
  const [ready, setReady] = useState(false);

  const offsets = useSharedValue(children.map(() => ({
    order: 0,
    width: 0,
    height: 0,
    x: 0,
    y: 0,
    originalX: 0,
    originalY: 0,
  }));

  if (!ready) {
    return (
      <View style={styles.row}>
        {children.map((child, index) => {
          return (
            <View
              key={child.key}
              onLayout={({
                nativeEvent: { layout: { x, y, width, height } },
              }) => {
               offsets.value[index] = {
                   order: -1,
                   width: width / children + 10,
                   height,
                   x,
                   y,
                   originalX: x,
                   originalY: y,
                );

                runOnUI(() => {
                  'worklet';

                  if (offsets.filter((o) => o.order.value !== -1).length === 0) {
                    runOnJS(setReady)(true);
                  }
                })();
              }}>
              {child}
            </View>
          );
        })}
      </View>
    );
  }
  return (
    <View style={styles.container}>
      {children.map((child, index) => (
        <SortableCard
          key={child.key}
          offsets={offsets}
          index={index}
          players={players}
          setPlayers={setPlayers}
          containerWidth={containerWidth}
          playerTurnCounter={playerTurnCounter}>
          {child}
        </SortableCard>
      ))}
    </View>
  );
} 

And here is my useAnimatedGestureHandler():

/* eslint-disable react/prop-types */
import React, { ReactElement } from 'react';
import { StyleSheet } from 'react-native';
import { PanGestureHandler, PanGestureHandlerGestureEvent } from 'react-native-gesture-handler';
import Animated, {
  runOnJS,
  useAnimatedGestureHandler,
  useAnimatedStyle,
  useDerivedValue,
  useSharedValue,
  withSpring,
} from 'react-native-reanimated';
import { between, useVector } from 'react-native-redash';

import {
  calculateLayout,
  CARD_HEIGHT,
  lastOrder,
  MARGIN_LEFT,
  MARGIN_TOP,
  remove,
  reorder,
  SENTENCE_HEIGHT,
} from '../Layout';

function SortableCard({ offsets, index, children, players, setPlayers, containerWidth }) {
  const offset = offsets.value[index];
  const isGestureActive = useSharedValue(false);
  const isAnimating = useSharedValue(false);
  const translation = useVector();
  const isInBank = useDerivedValue(() => offset.order === -1);
  const onGestureEvent = useAnimatedGestureHandler({
    onStart: (_, ctx) => {
      if (isInBank.value) {
        translation.x.value = offset.originalX - MARGIN_LEFT;
        translation.y.value = offset.originalY + MARGIN_TOP;
      } else {
        translation.x.value = offset.x;
        translation.y.value = offset.y;
      }
      ctx.x = translation.x.value;
      ctx.y = translation.y.value;
      isGestureActive.value = true;
    },
    onActive: ({ translationX, translationY }, ctx) => {
      translation.x.value = ctx.x + translationX;
      translation.y.value = ctx.y + translationY;
     
      if (isInBank.value && translation.y.value < SENTENCE_HEIGHT) {
        offset.order = lastOrder(offsets.value);
        calculateLayout(offsets.value, containerWidth);
      } else if (!isInBank.value && translation.y.value > SENTENCE_HEIGHT) {
        offset.order = -1;
        remove(offsets.value, index);
        calculateLayout(offsets.value, containerWidth);
      }
      for (let i = 0; i < offsets.value.length; i++) {
        const o = offsets.value[i];
        if (i === index && o.order !== -1) {
          continue;
        }
      
        if (
          between(translation.x.value, o.x, o.x + o.width) &&
          between(translation.y.value, o.y - CARD_HEIGHT, o.y + CARD_HEIGHT)
        ) {
          reorder(offsets.value, offset.order, o.order);
          calculateLayout(offsets.value, containerWidth);
          break;
        }
      }
    },
    onEnd: ({ velocityX, velocityY }) => {
      isAnimating.value = true;
      translation.x.value = withSpring(offset.x, { velocity: 0.2 });
      translation.y.value = withSpring(offset.y, { velocity: 0.2 });
      isGestureActive.value = false;
      const tplayers = players;
      if (
        between(translation.x.value, offset.x / 2, offset.x / 2 + offset.width) &&
        between(translation.y.value, offset.y - CARD_HEIGHT, offset.y)
      ) {
     
        let inDeck = false;
        for (let i = 0; i < tplayers[0].subHand.length; i++) {
          if (
            tplayers[0].subHand[i].suite === children.props.item.suite &&
            tplayers[0].subHand[i].value === children.props.item.value
          ) {
            inDeck = true;
          }
        }
        if (!inDeck) {
          tplayers[0].subHand.push(children.props.item);
        }
        runOnJS(setPlayers)(tplayers);
      } else if (
        between(translation.x.value, offset.x, offset.x + offset.width) &&
        between(translation.y.value, offset.y - CARD_HEIGHT, offset.y)
      ) {
        let inDeck = false;
        for (let i = 0; i < tplayers[0].subHand.length; i++) {
          if (
            tplayers[0].subHand[i].suite === children.props.item.suite &&
            tplayers[0].subHand[i].value === children.props.item.value
          ) {
            inDeck = true;
          }
        }
        if (!inDeck) {
          tplayers[0].subHand.push(children.props.item);
        }
        runOnJS(setPlayers)(tplayers);
      } else {
        for (let i = 0; i < tplayers[0].subHand.length; i++) {
          if (
            tplayers[0].subHand[i].suite === children.props.item.suite &&
            tplayers[0].subHand[i].value === children.props.item.value
          ) {
            tplayers[0].subHand.splice(children.props.item, 1);
          }
        }
        runOnJS(setPlayers)(tplayers);
      }
    },
  });
  const translateX = useDerivedValue(() => {
    if (isGestureActive.value) {
      return translation.x.value;
    }
    return withSpring(isInBank.value ? offset.originalX - MARGIN_LEFT : offset.x);
  });
  const translateY = useDerivedValue(() => {
    if (isGestureActive.value) {
      return translation.y.value;
    }
    return withSpring(isInBank.value ? offset.originalY + MARGIN_TOP : offset.y);
  });
  const style = useAnimatedStyle(() => {
    return {
      position: 'absolute',
      top: 0,
      left: 0,
      width: offset.width.value,
      height: CARD_HEIGHT,
      transform: [{ translateX: translateX.value }, { translateY: translateY.value }],
    };
  });
  return (
    <>
      <Animated.View style={style}>
        <PanGestureHandler onGestureEvent={onGestureEvent}>
          <Animated.View style={StyleSheet.absoluteFill}>{children}</Animated.View>
        </PanGestureHandler>
      </Animated.View>
    </>
  );
}

export default SortableCard;

My issue is when I try to access offsets, which is one shared value that stores an array, while inside of useAnimatedGestureHandler, the values are not as expected.

When I put print statements outside of useAnimatedGestureHandler (for example, on the line below ‘offset = offsets.value[index]’) the expected values are printed. Similarly if I console log offsets in the return statement I also see the expected values. But if I try to access offsets inside the gesture handler or if I try to print them, all values are reinitialized to their original values but the initializer doesn’t seem to get called again.

Any help to assist me in understanding what is going on here is greatly appreciated. Thank you!

Having trouble getting autocomplete.js to display results after starting a third word in the search

I have been trying to use an autocomplete library from https://tarekraafat.github.io/autoComplete.js/#/ called autocomplete.js. It is working fine all the way up until I start to add a third word to the query. When I get to the third word, even after one or two characters, I get get “no results found”, but otherwise I get no errors in the console.

If you run the code below, you will see what happens.

Somehow, typing a third word into the search box is causing it to lose the data somewhere between returning the results from the API, and when it gets to resultsList.element. I see no problems with data.src. Can anyone else see any problems with this code?

Here is the code I’m using:

    const autoCompleteJS = new autoComplete({
        selector: "#autoComplete",
        data: {
            src: [
                "Don't Rock The Jukebox - Alan Jackson [CB Karaoke]",
                "Don't Rock The Jukebox - Alan Jackson [NU Karaoke]",
                "Don't Rock The Jukebox - Alan Jackson [DK Karaoke]",
                "Don't Rock The Jukebox - Alan Jackson [SC Karaoke]",
                "Don't Rock The Jukebox - Alan Jackson [P Karaoke]"
            ],
            cache: false // Disable caching for dynamic data
        },
        threshold: 3, // Minimum number of characters before the autocomplete starts
        debounce: 300, // Wait 300ms before fetching the data
        resultsList: {
            element: (list, data) => {
                // Display "No Results" message when no results are found
                if (!data.results.length) {
                    console.log("no results");
                    const message = document.createElement("div");
                    message.setAttribute("class", "no_results");
                    message.innerHTML = `<span>No results found</span>`;
                    list.appendChild(message);
                }
            },
            maxResults: 10, // Maximum number of results to show
            noResults: true
        },
        resultItem: {
            highlight: true,
            element: (item, data) => {
                console.log("data: " + data)
                // Display the result item
                item.innerHTML = `<span>${data.value}</span>`;
            }
        },
        onSelection: (feedback) => {
            const selection = feedback.selection.value;
            document.querySelector("#autoComplete").value = selection;
            console.log("Selected item:", selection);
        }
    });
<link href="https://cdn.jsdelivr.net/npm/@tarekraafat/[email protected]/dist/css/autoComplete.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/@tarekraafat/[email protected]/dist/autoComplete.min.js"></script>
<div class="container mt-5 pt-5 col-md-5">
    <h4>Search Songs</h4>
    <div id="autocomplete" class="autocomplete">
        <input id="autoComplete" type="text" placeholder="Search Karaoke">
        <ul class="autocomplete-result-list"></ul>
    </div>
</div>

EDIT:
I think I figured something out. This library seems to want to search through the results on its own. It doesn’t respect the search results I feed it. As long as the words I type are together in the results, it displays them. Is there a way to keep it from doing its own sorting?

Hiding a parent div based on all child inputs being disabled

I am trying to {display:none} on class=”filter-form__group” only if ALL child Input’s are ‘disabled’.

<div class="filter-form__group">
  <div class="filter-form__group-filter-wrapper" data-filter-type="list">
    <div class="filter-form__list-wrapper">
      <ul class="filter-form__list">
        <li class="filter-item">
          <label data-filter-item="" class="filter-item__content">
            <input type="checkbox" value="Luggage" disabled>
          </label>
        </li>
        <li class="filter-item">
          <label data-filter-item="" class="filter-item__content">
            <input type="checkbox" value="Motorcycle" disabled>
          </label>
        </li>
      </ul>
    </div>
  </div>
</div>

Thanks!

I tried some CSS but they do not seem to work and I believe this may have to be done in JS.

How do i mock MongoDb Connection and Test it

My DB Class to test
I have a DB class where i encapsulate Mongodb methods to test

import mongodb from 'mongodb';
import dotenv from 'dotenv';

// Comfigure dotenv
dotenv.config();

// eslint-disable-next-line no-unused-vars
class DBClient {
  /** 
  * Creates a new DBclient instance.
  */
  constructor() {
    const host = process.env.DB_HOST || 'localhost';
    const port = process.env.DB_PORT || 27017;
    const database = process.env.DB_DATABASE || 'files_manager';

    const dbUri = `mongodb://${host}:${port}/${database}`;
    this.client = new mongodb.MongoClient(dbUri, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    }); 

    this.isClientConnected = false;
    this.client.connect((err) => {
      if (err) {
        console.error('Error encounted while connecting to MongoDB', err);
      } else {
        this.isClientConnected = true;
        console.log('Connected to MongoDB');
      }   
    }); 
  }

  /** 
  * check the status of the connection to MongoDB
  * @returns {boolean}
  */
  isAlive() {
    return this.isClientConnected;
  }
}

const dbClient = new DBClient();
module.exports = dbClient;

My Test File
My intention is to mock the connection to db then test

const { expect } = require('chai');
const sinon = require('sinon');
const mongodb = require('mongodb');
const dbClient = require('../utils/db');

describe('DBClient', function() {
  afterEach(function() {
    // Automatically restore all stubs after each test
    sinon.restore();
  }); 

  it('should initialize and connect successfully', function(done) {
    const connectStub = sinon.stub(mongodb.MongoClient.prototype, 'connect').callsFake(function(cb) {
      cb(null); // No Error
    });  
    // Wait for the next tick to allow the callback to execute
    process.nextTick(() => {
      expect(dbClient.isAlive()).to.be.true;
      expect(connectStub.calledOnce).to.be.true;
      done();
    }); 
  }); 
  
  it('should fail to connect and isAlive returns false', function(done) {
    // Stub the connect method to simulate a connection failure
    const connectStub = sinon.stub(mongodb.MongoClient.prototype, 'connect').callsFake(function(cb) {
      cb(new Error('Failed to connect')); 
    }); 

    process.nextTick(() => {
      expect(dbClient.isAlive()).to.be.false;
      expect(connectStub.calledOnce).to.be.true();
      done();
    }); 
  }); 
});

When i run the test
The two test cases are falling with the following error.

  DBClient
    1) should initialize and connect successfully
    2) should fail to connect and isAlive returns false


  0 passing (20ms)
  2 failing

  1) DBClient
       should initialize and connect successfully:

      Uncaught AssertionError: expected false to be true
      + expected - actual

      -false
      +true
      
      at /root/alx-files_manager/test/connectToMongoDb.test.js:18:39
      at processTicksAndRejections (node:internal/process/task_queues:77:11)

  2) DBClient
       should fail to connect and isAlive returns false:

      Uncaught AssertionError: expected false to be true
      + expected - actual

      -false
      +true
      
      at /root/alx-files_manager/test/connectToMongoDb.test.js:32:43
      at processTicksAndRejections (node:internal/process/task_queues:77:11)

I suspect my issue is starting when I stub the connection to the DB. Please assist

JavaScript Discord Error, TypeError: client.handleCommands is not a function

Hello guys so I’m experiencing this problem with Discord bot making in JavaScript.
I’m following a tutorial from Fusion Terror.
The error I’m experiencing is that it’s saying handleCommands.js is not a function, it works for him but not for me.

Full error:

~@~: workspace/project_name$ node .
/home/username/workspace/project_name/src/bot.js:26
client.handleCommands();
       ^

TypeError: client.handleCommands is not a function
    at Object <anonymous> (/home/username/workspace/project_name/src/bot.js:6:8)
    at Module._compile (node:internal/modules/cjs/loader:1469:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1548:10)
    at Module.load (node:internal/modules/cjs/loader:1288:32)
    at Module._load (node:internal/modules/cjs/loader:1104:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:174:12)
    at node:internal/main/run_main_module:28:49

Node.js v20.17.0

All the files and folders:
file and folder organization

bot.js code:

require("dotenv").config();

const { Client, Collection, GatewayIntentBits } = require("discord.js");
const client = new Client({
  intents:
    (GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent),
});
const { token } = process.env;
const fs = require("fs");

client.commands = new Collection();
client.commandArary = [];

const functionFolders = fs.readdirSync(`./src/functions`);
for (const folder of functionFolders) {
  const functionFiles = fs
    .readdirSync(`./src/functions/${folder}`)
    .filter((file) => file.endsWith(`.js`));
  for (const file of functionFiles)
    require(`./functions/${folder}/${file}`)(client);
}

client.handleEvents();
client.handleCommands();

client.login(token);

handleCommand.js code:

const fs = require("fs");

module.exports = (client) => {
  client.commandHandler = async () => {
    const commandsFolder = fs.readdirSync(`./src/commands`);
    for (const folder of commandsFolder) {
      const commandFiles = fs
        .readdirSync(`./src/commands/${folder}`)
        .filter((file) => file.endsWith(`.js`));

      const { commands, commandsArray } = client;
      for (const file of commandFiles) {
        const command = require(`../commands/${folder}/${file}`);
        commands.set(command.data.name, command);
        commandsArray.push(command.data.toJSON());
        console.log(
          `Command ${command.data.name} has been regtistered through the command handler succesfully.`
        );
      }
    }
  };
};

Thanks in advance!

Well I tried re-writing the code which at the moment I thought would help, whilst it didn’t and the same error occured

useQueries dependent on another Query, whose data is with 3 levels depth

I am facing a situation where I will first use a useQuery to fetch an object, which contains multiple URLs three levels deep. And then, I’ll use a useQueries to fetch all those URLs. And example given Dependent Queries cannot handle this situation.

For example:

// Get the users ids
const { data: userIds } = useQuery({
  queryKey: ['users'],
  queryFn: getUsersData
})

const usersMessages = useQueries({
  queries: userIds ?
     userIds.map(id => {
        return {
          queryKey: ['messages', id],
          queryFn: () => getMessagesByUsers(id),
        };
      })
  : [],
})

The above code works if userIds is like:
[ url1, url2, url3, url4 ] .
However, in my case, the userIds has the following structure:

[
  {'name':'A', 'id': [url1, url2]}, 
  {'name':'B', 'id': [url3, url4]}
]

and my objective is to fetch from all URLs.

I can’t change the first query using “select” to change the format of the returned data because I am collaborating with others, and changing that would incur many other refactors.

I tried to first get userIds, and then decompose it to form a new array that only contains all the URLs, give this new array to the second useQueries and meanwhile set dependency on !isLoading of the first query, which does not work. The code enters in to a loop and throw an error “Rendered more hooks than during the previous render”.