Prisma Migration Issue: “Migration history doesn’t match” Error on Production Database

I’m encountering an issue with Prisma migrations in my NestJS application. My backend setup includes Prisma and PostgreSQL, and I’m using a remote database for my production environment. Every time I try to migrate any database schema changes on the production server, I get the following error:

Error: Migration history doesn't match

It suggests resetting the whole database, which unfortunately clears all the data in my production database. Here is a summary of my current workflow:

  1. Backup Production Database: I take a backup of the production database before making any schema changes.
  2. Migrate Schema Changes: I run the migration commands, which leads to the above error and ends up clearing the data.
  3. Restore Data:I manually import the data back into the production database.

Steps I’ve Taken to Resolve the Issue:

  1. Shadow Database Configuration: I’ve specified a different shadow database in my schema.prisma file:
datasource db {
  provider          = "postgresql"
  url               = env("DATABASE_URL")
  shadowDatabaseUrl = env("SHADOW_DATABASE_URL")
}
  1. Synchronize Migration History:
    I’ve tried to ensure that the migration history in my local environment matches the one in production by copying migration files from production to local.

  2. Deploying Migrations:
    I’ve attempted to use the npx prisma migrate deploy command to apply the migrations without resetting the database, but the issue persists.

how i can fix this error?! : Uncaught ReferenceError: THREE is not defined

I created a subdomain inside the host and inside this subdomain I created a folder and created an index file to call the threejs code, which is my code:

    <script>  
        // صحنه، دوربین و رندرکننده را ایجاد کنید  
        const scene = new THREE.Scene();  
        const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);  
        const renderer = new THREE.WebGLRenderer();  
        renderer.setSize(window.innerWidth, window.innerHeight);  
        document.body.appendChild(renderer.domElement);  

        // نور به صحنه اضافه کنید  
        const light = new THREE.AmbientLight(0xffffff);  
        scene.add(light);  

        // دراکو بارگذار و GLTFLoader را تنظیم کنید  
        const dracoLoader = new THREE.DRACOLoader();  
        dracoLoader.setDecoderPath('/examples/jsm/libs/draco/');  
        const loader = new THREE.GLTFLoader();  
        loader.setDRACOLoader(dracoLoader);  

        // بارگذاری مدل GLTF  
        loader.load(  
            'https://demo.arendlighting.com/arsalan/object/scene.gltf',  
            function (gltf) {  
                scene.add(gltf.scene);  
                gltf.scene.position.set(0, 0, 0); // موقعیت مدل  
            },  
            function (xhr) {  
                console.log((xhr.loaded / xhr.total * 100) + '% loaded');  
            },  
            function (error) {  
                console.log('An error happened:', error);  
            }  
        );  

        // تنظیم دوربین  
        camera.position.z = 5;  

        // حلقه رندر  
        function animate() {  
            requestAnimationFrame(animate);  
            renderer.render(scene, camera);  
        }  
        animate();  

        // تنظیم اندازه‌گیری صفحه  
        window.addEventListener('resize', function() {  
            camera.aspect = window.innerWidth / window.innerHeight;  
            camera.updateProjectionMatrix();  
            renderer.setSize(window.innerWidth, window.innerHeight);  
        });  
    </script>  
</body>  
</html>`

But when I run the browser page, I encounter a white screen and it shows me this error in the console: Uncaught ReferenceError: THREE is not defined.
What is wrong?!

i try in this link : https://demo.arendlighting.com/arsalan/
PlZz heeeeelppp me…

How to prevent from auto reloading in html page?

I am making a chatting application using spring boot 3 and i use web socket to make connection. I’ve created a web page with 2 buttons “Start Chat” and “Close Chat”. When i click the “Start Chat” button it adds html codes into an html element(id=”chat”). This html code is from “https://spring.io/guides/gs/messaging-stomp-websocket”. And when i click the “Close Chat” button it removes the html codes from the element. My issue:

When i click the Start Chat button and Connect it works well. After closing, if i open the chat again and click Connect the page is reloaded. I don’t want this reloading when i try to connect chat again.
(Note: After clearing the chat elements from page i also call disconnect() function from webSocket.js )

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@stomp/[email protected]/bundles/stomp.umd.min.js"></script>
    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <script src="/js/bootstrap.bundle.min.js"></script>
    <script src="/js/app.js"></script>
</head>
<body>
<div th:insert="components/header :: header"></div>
<div class="container-fluid">
    <div class="col-md-3">
        <div class="row">
            <button onclick="openChat()" class="btn btn-primary m-3">Start Chatting</button>
            <button onclick="closeChat()" class="btn btn-primary m-3">Close Chat</button>
        </div>
    </div>
    <div class="col-md-9">
        <div class="row m-3" id="chat"></div>
    </div>
</div>

<script>
    function closeChat() {
        const chatElement = document.getElementById("main-content");
        chatElement.remove();
        disconnect();
        const scriptElement = document.getElementById("webSocketJs");
        if (scriptElement) {
            scriptElement.remove();
        }
    }

    function openChat() {
        event.preventDefault();
        const chatElement = document.getElementById("chat");
        const content =
            `<div id="main-content" className="container">
                <div className="row">
                    <div className="col-md-6">
                        <form className="form-inline">
                            <div className="form-group">
                                <label htmlFor="connect">WebSocket connection:</label>
                                <button id="connect" className="btn btn-default" type="submit" >Connect</button>
                                <button id="disconnect" className="btn btn-default" type="submit"
                                        disabled="disabled">Disconnect
                                </button>
                            </div>
                        </form>
                    </div>
                    <div className="col-md-6">
                        <form className="form-inline">
                            <div className="form-group">
                                <label htmlFor="name">What is your name?</label>
                                <input type="text" id="name" className="form-control" placeholder="Your name here..."/>
                            </div>
                            <button id="send" className="btn btn-default" type="submit">Send</button>
                        </form>
                    </div>
                </div>
                <div className="row">
                    <div className="col-md-12">
                        <table id="conversation" className="table table-striped">
                            <thead>
                            <tr>
                                <th>Greetings</th>
                            </tr>
                            </thead>
                            <tbody id="greetings">
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>`;
        chatElement.innerHTML = content;

        const scriptElement = document.getElementById("webSocketJs");
        if (!scriptElement) {
            let webSocketScript = document.createElement('script');
            webSocketScript.setAttribute('src', '/js/webSocket.js');
            webSocketScript.setAttribute('id', 'webSocketJs');
            document.body.appendChild(webSocketScript);
        }
    }
</script>
</body>
</html>
const stompClient = new StompJs.Client({
    brokerURL: 'ws://localhost:8080/gs-guide-websocket'
});

stompClient.onConnect = (frame) => {
    setConnected(true);
    console.log('Connected: ' + frame);
    stompClient.subscribe('/topic/greetings', (greeting) => {
        showGreeting(JSON.parse(greeting.body).content);
    });
};

stompClient.onWebSocketError = (error) => {
    console.error('Error with websocket', error);
};

stompClient.onStompError = (frame) => {
    console.error('Broker reported error: ' + frame.headers['message']);
    console.error('Additional details: ' + frame.body);
};

function setConnected(connected) {
    $("#connect").prop("disabled", connected);
    $("#disconnect").prop("disabled", !connected);
    if (connected) {
        $("#conversation").show();
    }
    else {
        $("#conversation").hide();
    }
    $("#greetings").html("");
}

function connect() {
    stompClient.activate();
}

function disconnect() {
    stompClient.deactivate();
    setConnected(false);
    console.log("Disconnected");
}

function sendName() {
    stompClient.publish({
        destination: "/app/hello",
        body: JSON.stringify({'name': $("#name").val()})
    });
}

function showGreeting(message) {
    $("#greetings").append("<tr><td>" + message + "</td></tr>");
}

$(function () {
    $("form").on('submit', (e) => e.preventDefault());
    $( "#connect" ).click(() => connect());
    $( "#disconnect" ).click(() => disconnect());
    $( "#send" ).click(() => sendName());
});

First one is my html page, and second one is webSocket.js file.

Re-adjusting image (and container) to accordeon variable height (in elementor)

I am trying to “copy” the effect of the accortdeon in the following link (https://the-healer-template.squarespace.com/work-with-me). The think that I want is to enlarge the image and the container of the image to fit the height of the accordeon container due to his variable height dependint on the lengh of the text from each accordeon elements.

Since I am working with elementor, the aproach that I am woking with is a two column container one with the image and the other with the container. Also I set the elementor accordion to only one accordeon element unfolded at a time, so when te user click to one of them, automaticaly closes the one that was active or if the click is on the same element, it desactivates it.

The main issue I am having now is that I am new to javascript and programing logic and I don’t know how to make it work. Here is the code that I am using so far, It does what I need but it is not taking in consideration the click on the other element while an other one is active. I activated the “Nested elements” on elementor to be able to assign an ID to each section of the accordeon

The link to my section example: https://www.balanceyoga.beinframe.com/example

<script>

document.addEventListener("DOMContentLoaded", function() {
    
    .responsive-image01 {
    max-width: 100% !important;
    height: auto !important;

    float:right !important;
   /* object-fit: cover;*/
    

    transition: width 300ms linear; 


    }
         
    var yogaCont01 = document.querySelector('.yoga-cont01'); // contenedor 01
    
    var yogaCont02 = document.querySelector('.yoga-cont02'); // contenedor 02
    
    var responsiveImage01 = document.querySelector('.responsive-image01'); 
    
        
    var originalWidth = responsiveImage01.offsetWidth; 

    var responsiveImageWidth01 = responsiveImage01.offsetWidth; 

    var originalHeight = yogaCont02.offsetHeight; 

    var yogaCont02Height = yogaCont02.offsetHeight; 

            
    responsiveImage01.style.width= (responsiveImageWidth01*0.65)+'px'; 

        
            
    function contHeight() {
        if (originalHeight==yogaCont02Height) {
                    
            yogaCont02Height = yogaCont02.offsetHeight;
        
            yogaCont01.style.height = yogaCont02Height + 'px';
            
            responsiveImage01.style.height = yogaCont02Height + 'px';
            
            var calculatedWidth = (originalWidth * yogaCont02Height)/originalHeight;
                
            responsiveImage01.style.width = calculatedWidth + 'px';
                    
        }else {
            

            responsiveImage01.style.height = originalHeight + 'px';
                
            responsiveImage01.style.width = (originalWidth*0.65) + 'px';
            
            yogaCont01.style.height = originalHeight + 'px';
            
            yogaCont02.style.height = originalHeight + 'px';
                
            yogaCont02Height = originalHeight;
            

        }
    }
        
    document.querySelector("#yoga-included").addEventListener("click", function() {
        setTimeout(contHeight, 360);
    
        });
        
    document.querySelector("#yoga-timeline").addEventListener("click", function() {
        setTimeout(contHeight, 360);
    
        });
        
   document.querySelector("#yoga-payment").addEventListener("click", function() {
        setTimeout(contHeight, 360);
    
        });
        
                
    }
        
);

</script>

How is the scope of variables used in Event Handlers determined? (when do I have to assign variables to fetch via event.currentTarget and when not???)

Working on my card game project I noticed at some point that I needed to append values I want to use inside an addEventListener’s function, to the tag that becomes available inside the function as event.currentTarget… but that in seemingly exactly similar coding situations, just calling variables declared outside the Event Handler’s function works.

Here is some code where calling a variable declared outside works :

document.querySelectorAll('.HexKeyControl').forEach(function(Tag) {
  Tag.IdSplitAtUnderScore = Tag.id.split('_');
  Tag.addEventListener('mousedown', function() {
    PlayNote(Tag.IdSplitAtUnderScore[1], Tag.IdSplitAtUnderScore[2]);
    SlideModeOn = true;
  });
  Tag.addEventListener('mouseup', function() {
    SlideModeOn = false;
  });
  Tag.addEventListener('mouseenter', function() {
    if (SlideModeOn) {
      PlayNote(Tag.IdSplitAtUnderScore[1], Tag.IdSplitAtUnderScore[2]);
    }
  });
  Tag.addEventListener('mouseleave', function() {
    EvidenceOut(document.getElementById('HexKeyImage_' + Tag.IdSplitAtUnderScore[1] + '_' + Tag.IdSplitAtUnderScore[2]));
  });
});

Maybe because the addEventListeners are themselves part of the forEach’s function, and the Tag variable was declared into this function, the addEventListener’s functions become child functions of the forEach’s function and for some quirky design reason it results into the variable being available… Maybe because Tag contains a DOM Element’s reference instead of a common value, it is treated differently becaue of its type…

Here is some code where I had to use event.currentTarget :

function display_board_card(spot, player, figure, instant_only = false) {
  // Variables preparation
  [...some out - of -context code...]


  /* Here comse the 1st case, in which the event handler's code is put into a variable
  for later use with eval() (which is bad I know but I don't remotely care, all cases of eval being
  replacable with other code are dumb situations that never happened to me).
  That said I understand that eval may steal the scope and force me to use event.currentTarget
  (and don't worry, the drop_target variable IS appended to the currentTarget before the eval(onClick) is
  called) */
  var onClick = "if (targeting_a_credo){
  evaluate_credo_target(drag_memory, evt.currentTarget.drop_target);
}
";


[...lots of out - of -context code...]


// Event handlers
// Here is the 2nd case in which I had to append the value to the DOM element
card_bg_div.drop_target = player + '***' + figure;
card_bg_div.addEventListener('drop', function(evt) {
  check_drop(event, evt.currentTarget.drop_target);
});
card_bg_div.addEventListener('dragover', function() {
  allowDrop(event);
});

In the 2nd case, we’re still inside a main function which has for parameters player and figure, which for some reason are made unavailable inside addEventListeners functions, which as you will admit, are located inside the parent function, just like in the first snipet, but won’t trail the parent function’s parameters inside their own function…

JavaScript is a total mess compared to PHP… I could ramble for long on this.

How can i read and write to cells in the same function?

I am creating a discord bot and I have 2 issues.

Issue One:

In my script i am trying to get the users response to :

interaction.options.get('steamid').value;

and store it in the variable userInput.

Once stored i want to write the stored response to my google sheet in sheet BOTDATA!H1.

The code works when i set const userInput = interaction.options.get('steamid').value; inside the function. Only when i use the ‘/checkbl’ command. If i use any other command i receive an error.

Issue Two: Any command that i use, regardless if it is the ‘/checkbl’ command or not will write `sample value` to the sheet BOTDATA!H1.

This is my current script:

async function blackList() { 
    const sheets = google.sheets({ version: "v4", auth });
    const spreadsheetId = "1lEB9fEqZUNtR0Tq-gzHVVaQ2eQvxsuiwXSTW3VGC2xw";
  
    const sheetName = "BOTDATA";
    const cells = ["H1"];
    const valueInputOption = "USER_ENTERED";
    const userInput = "sample value";
    const result = await sheets.spreadsheets.values.update({
      spreadsheetId,
      range: `'${sheetName}'!${cells[0]}`,
      resource: { values: [[userInput]] },
      valueInputOption,
    });
    console.log(result.data);
    
  }
  
  blackList();

  (async()=>{

if (interaction.commandName === 'checkbl') {
    const userInput = interaction.options.get('steamid').value;
    const bl = new EmbedBuilder()
    .setTitle('Blacklist Checker')
    .setDescription(`${userInput} is`)
    .setColor('Red')
    .setThumbnail('https://i.imgur.com/9GKhYQf.png')
    .setFooter({text: 'DroneOS', iconURL: 'https://i.imgur.com/9GKhYQf.png'})
    .setTimestamp()

    interaction.reply({ embeds: [bl]});

}

})()

I would like to solve both my issues stated above. Along side this i would like ‘userInput’ to write to cell H1 and i want to read cell H2 in the same function. This way i can set the response to:

.setDescription(`${userInput} is ${H2}`)

on my discord bot. Thanks for any help.

Keycloak: how to log in a user through the API

I managed to log in as admin through the /protocol/openid-connect/token url.

Now I have an admin that can list users, realms + create/delete them etc.

What I would like is to check if the credentials I receive from my user are the good ones or not.

When I use the same call than for the admin /protocol/openid-connect/token I get “bad credentials” but I know they are correct.

I am using nextjs + @keycloak/keycloak-admin-client but looks like the keycloak-admin-client cannot handle user authentication

What could be causing the 404 Not Found error for PATCH and DELETE requests?

How can I ensure my mock server handles these methods correctly?

I’m building a React application that interacts with a mock API. I can successfully perform GET and POST operations, but I’m encountering issues with PATCH and DELETE requests, which return a 404 (Not Found) error. I’ve provided the relevant code below. Could anyone help identify what might be causing these errors?

here’s my code:

App.js:

`import Header from "./Header";
import Footer from "./Footer";
import ListItem from "./ListItem";
import "./index.css";
import { useState, useEffect } from "react";
import AddItem from "./AddItem";
import SearchItem from "./SearchItem";
import ApiRequest from "./ApiRequest";

function App() {
  const API_URL = "http://localhost:3500/items";
  const [items, setItems] = useState([]);
  const [newItem, setNewItem] = useState("");
  const [search, setSearch] = useState("");
  const [fetchError, setFetchError] = useState(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchItems = async () => {
      try {
        const data = await ApiRequest(API_URL, { method: "GET" });
        setItems(data.items || []);
        setFetchError(null);
      } catch (error) {
        setFetchError(error.message);
      } finally {
        setIsLoading(false);
      }
    };

    setTimeout(fetchItems, 2000);
  }, []);

  const addItem = async (item) => {
    const id = items.length ? items[items.length - 1].id + 1 : 1;
    const addNewItem = { id, checked: false, item };
    const listItems = [...items, addNewItem];
    setItems(listItems);

    const postOptions = {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(addNewItem),
    };

    try {
      await ApiRequest(API_URL, postOptions);
      setFetchError(null);
    } catch (error) {
      setFetchError(error.message);
    }
  };

  const handleCheck = async (id) => {
    const updatedItems = items.map((item) =>
      item.id === id ? { ...item, checked: !item.checked } : item
    );
    setItems(updatedItems);

    const updateOptions = {
      method: "PATCH",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ checked: updatedItems.find(item => item.id === id).checked }),
    };

    try {
      await ApiRequest(`${API_URL}/${id}`, updateOptions);
      setFetchError(null);
    } catch (error) {
      setFetchError(error.message);
    }
  };

  const handleDelete = async (id) => {
    const remainingItems = items.filter((item) => item.id !== id);
    setItems(remainingItems);

    const deleteOptions = {
      method: "DELETE",
      headers: {
        "Content-Type": "application/json",
      },
    };

    try {
      await ApiRequest(`${API_URL}/${id}`, deleteOptions);
      setFetchError(null);
    } catch (error) {
      setFetchError(error.message);
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!newItem) return;
    addItem(newItem);
    setNewItem("");
  };

  return (
    <div className="App">
      <Header name="To do List" />
      <AddItem
        newItem={newItem}
        setNewItem={setNewItem}
        handleSubmit={handleSubmit}
      />
      <SearchItem search={search} setSearch={setSearch} />

      <main>
        {isLoading && <p><b>Loading Items</b></p>}
        {fetchError && <p><b>{`Error: ${fetchError}`}</b></p>}
        {!isLoading && !fetchError && (
          <ListItem
            items={items.filter((item) =>
              item.item.toLowerCase().includes(search.toLowerCase())
            )}
            handleCheck={handleCheck}
            handleDelete={handleDelete}
          />
        )}
      </main>
      <Footer length={items.length} />
    </div>
  );
}`

export default App;

ApiRequest.js:

`const ApiRequest = async (url = "", optionsObj = {}) => {
  try {
    const response = await fetch(url, optionsObj);
    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`HTTP error! Status: ${response.status}. Details: ${errorText}`);
    }
    return response.json(); // Return parsed JSON data
  } catch (error) {
    console.error('API request error:', error.message);
    throw error; // Rethrow the error for handling in calling function
  }
};
export default ApiRequest;`

Response:
Failed to load resource: the server responded with a status of 404 (Not Found)

Ag grid react selectcelleditor handleChange method

I want to know onChange method for ag-grid-react in selectCell editor.

I am editing the cells, when I select option from name dropdown its respective designation options should come.

But this is happening when I am existing edit mode and starting edit again.

I want to happen it live, when I select name , respective designation should come in dropdown of designation, without exiting edit mode.

Any other solutions are as well welcome.

{
field:"name",
headerName:"Name"
cellEditorSelector : (params:any)=>{
          return {
            component: "agSelectCellEditor" ,
            params:{values:nameArr},

          }
        },
field:"designation",
headerName:"Designation"
cellEditorSelector : (params:any)=>{
          return {
            component: "agSelectCellEditor" ,
            params:{values:designationArr},

          }
        }

}

Contenteditable: Some problems with creating and focusing span

I’ve been trying to solve this issue for a few days now but I don’t have any idea how I can fix it. I hope you can help me or give me some tips which lead me to the point to fix the issues.

I’m developing a feature in my app where it is possible to execute specific function on each sentence. Each sentence is assigned to a span element.

The browser’s default functionality destroys the entire functionality of the feature so I’m trying to add a custom functionality what happens if the user presses enter at the end of a sentence. My goal is to add a new line break with a new span each time when the cursor is at the end of the sentence and the user presses enter. The cursor should follow automatically the line breaks (go into the next row) and should focus the created span element that the input is assigned to the span.

I’ve tried to do it with the Selection-API and some things are working but not everything.

The things that aren’t working are:

  • move the cursor automatically into the next line
  • to focus the created span that the input is assigned to it and not inserted between the span elements (such as on the picture)

enter image description here

  • to add the line break and span at the end of a sentence outside the focused span (it doesn’t work, because I append the newly created spans as a child to the contentediable container.

In the contenteditable container should only be span elements on 1 layer without any deeper structure/layers.

How can I solve these isses?

This is my code:

public addOwnBehaviorToContentEditable(event: KeyboardEvent) {
    if (event.key !== 'Enter') return;

    event.preventDefault();

    let contenteditable = event.target as HTMLElement;
    let selection = this._document.getSelection();

    if (selection.rangeCount > 0) {
      let range = selection.getRangeAt(0);
      // Get the common ancestor container of the start and end nodes of the range
      let container = range.commonAncestorContainer;
      // Is the user in the last span element and at the end of the range (sentence) a new <br> and <span> element is created

      if (range.endOffset === container.textContent.length) {
        contenteditable.appendChild(this._document.createElement('br'));
        let span = this._document.createElement('span');
        span.textContent = '';

        this.assignPropertiesToSpan(span);
        contenteditable.appendChild(span);

        span.focus();

        let newRange = this._document.createRange();
        newRange.setStart(span, 0);
        

        selection.removeAllRanges();
        selection.addRange(newRange);
      } else {
        range.insertNode(document.createElement('br'));
      }
    }
  }

Why is req.body undefined in Multer’s diskStorage destination function?

I’m using Multer to handle file uploads in my Express.js application. I’m trying to access the req.body values in the destination function of Multer’s diskStorage option, but it’s returning undefined.how do i pass name from /registerartist to req.body of multer desination

Here’s my code:

import express from 'express';
import {json} from 'express';
import dotenv from 'dotenv';
import {mongoose} from 'mongoose'; 
import UserModel from './src/Models/usermodel.js';
import TrackModel from './src/Models/trackmodel.js';
import cors from 'cors';
import multer from 'multer';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import SingerSchema from './src/Models/singermodel.js';
import Artist from './src/Models/artistmodel.js';


dotenv.config();

const PORT = process.env.PORT;
const app = express();
app.use(json());
app.use(cors())
app.use(express.urlencoded({ extended: true }));



// Define __dirname for path resolution
const __dirname = dirname(fileURLToPath(import.meta.url));

// Multer Storage Configuration
const upload = multer({
    storage: multer.diskStorage({
      destination: (req, file, cb) => {
        const { name } = req.body; 
        const folderPath = `./uploads/artists/${name}`;
        console.log(folderPath)
        if (!fs.existsSync(folderPath)) {
          fs.mkdirSync(folderPath, { recursive: true });
        }
        cb(null, folderPath);
      },
      filename: (req, file, cb) => {
        cb(null, Date.now() + '-' + file.originalname);
      }
    })
  });
//connect to Database

mongoose.connect("mongodb://localhost:27017/Anitify")
.then(()=>{
    console.log("Connected to Mongodb")
})
.catch((err)=>{
    console.log("Error connecting to mongodb",err);
})




app.post('/registerartist', upload.single('image'),  (req, res) => {
    const { name, email, password, genre } = req.body;

  
    console.log("image is",req.file.image.originalname);
   
    console.log("bodyis",req.body.name);
  
   Artist.findOne({email:email})
   .then(result=>{
        if(!result){
            Artist.create(req.body);
        }else{
            console.log("already exists");
        }
   })
   .then(user=>res.json(user))
   .catch((err)=>{
        console.log(err);
        res.json(err)
   })
  });
  


issue in promise based taskRunner

I want to create a task runner which run based on limit for eg. limit=3 i.e. run 3 task at a time, but it is not executing after given limit; below is the main code ;

what could be the issue here?

class TaskRunner {
  #limit;
  #taskQueue = [];
  #taskCount = 0;

  constructor(limit) {
    this.#limit = limit;
  }

  run(fn, id) {
    this.#taskQueue.push({ task: fn, id: id });
     this.#taskCount++;
      while(this.#taskCount <= this.#limit && this.#taskQueue.length > 0) {
        const { task, id } = this.#taskQueue.shift();
        task(id).then((p)=>{
          console.log({p});
          this.#taskCount--;
        })
      }
    console.log(this.#taskCount);
  }
}

const taskRunner = new TaskRunner(3);

const task = (arg)=>{
  return new Promise((resolve)=>{
    setTimeout(()=>{
      console.log("Task Completed!", arg);
      resolve(true);
    }
    , 2000)
  }
  )
}
;

taskRunner.run(task, 'id-1');
taskRunner.run(task, 'id-2');
taskRunner.run(task, 'id-3');
taskRunner.run(task, 'id-4');
taskRunner.run(task, 'id-5');
taskRunner.run(task, 'id-6');
taskRunner.run(task, 'id-7');

or is there any better way to handle this?

How do i solve my crashing nextjs application?

i am currently facing a problem with my nextjs application.
As soon as I reload my page i get the following error message and my application crashes.
There are no problems on the first load. As soon as the error is there i have to restart my application.

Has anyone an idea what the reason could be?

Nextjs Error Message

Thank you!

I already tried reinstalling my node_modules but it didn’t solve the problem.

How to draw an arc on a Static Google Map in Javascript?

I wanted to draw an arc (refer the image below) on a static google map image.

Arc

I have created a web application that displays the Google Map. I have a search box and next button, the user can search whichever the place they want, zoom and set the required zoom to have a good picture of what they are looking. Upon clicking next button, I capture the map as a static image and display it inside a canvas. I have a button named arc which will draw the arc on top of the image inside the canvas.

But, my problem is I am not able to get the accurate distance. Say, the arc I am drawing is 20 meters from the center point (highlighted as red dot) to the end of the arc. When, I check with google map measure scale, I am getting a deflection of 5 to 8 meter, so mine is not accurate.

How do I get the accurate distance?

At the moment, I have used HTML2CANVAS to render a canvas, get the static image of the map and paste it inside the canvas. I have pretty much done with the logic for drawing the arc and I am focusing on making it accurate.

I am aware that map is now static image and I am drawing an arc on top of an image which is quite difficult in getting the accuracy, but is there any way I can pass the latitude and longitude and play with it?

Any idea and reference would be helpful, I can derive my logic from that.

Let me know if anyone needed the code, I am happy to post.

Thanks in Advance!