How to Pass Data from Server using SSR in SvelteKit?

I’m used to using Express with a templating engine, like Handlebars. I want to start working with Svelte and SvelteKit, but I’m unsure how to start working with both. I am stuck on passing data to the frontend from the server. In Express, I’d normally connect to the database, and then pass the data to res.render, where the templating engine would then take over. So far, I think I have to run a handle function to pass the data, and then I can access it from my page. But it seems that the handle function runs for every request, and if all my pages require different data, does that mean I have to use a giant switch statement or something for every page?

Can anybody tell me if that’s the right way to pass data over, or if there’s a better way. Sorry, I’m fairly new to metaf rameworks and Svelte.

Delaying a string function?

So basically I all my code is within a while loop. Within that I have a for loop which checks for a bee in the neighboruging grids. When it detects a bee it calls a function. I need all the functions called by that to wait and only run when the while loop is just about to be finsihed (outside the for loop but inside the while loop).

Here is my code:

Cell.prototype.floodFillEach = function() {
  grid[orginalX][orginalY].floodFill();
  while(repeat<=7){
    for (var xoff = 0-x12; xoff <= 0+x12; xoff++) {
      for (var yoff = 0; yoff <= 0+x12; yoff++) {
        var i = orginalX + xoff;
        var j = orginalY + yoff;
        if (i > -1 && i < cols && j > 0 && j < rows) {
          var neighbour = grid[i][j];
          if (neighbour.marked2) {
            console.log("x:"+i+"  y:"+j);
            neighbour.floodFill(); // everytime this function is called within this while loop i need it to wait untill...       
          }
        }
      }
    }
      // ... here. I need the functions called to wait and run here and after they are done only then proceed with the rest of this while loop
    x12++
    repeat++
  }
}

how to create document using nested mongodb schema?

I’m trying to create a new document using javascript for mongoDB database, and add values to deeply nested properties in the schema. Specifically i’m trying to add values to the taskItem, highlight, and identifier properties on task. Right now my schema looks like this

const todoTaskSchema = new mongoose.Schema({
  username: String,
  password: String,
  task: [
      {
              taskItem: String,
              highlight: {type: Boolean, default: false},
              identifier: Number,
      
      }],
  subTask: [
      {
          pointer: Number,
          tasks: Array,
      },
    ]
})

My destructured properties look like this.

const { username, password, task: [ { taskItem: taskName, highlight: starred, identifier} ] } = req.body

I’m using the .create method to create the document. It’s argument looks like this:

dbModel.create({ taskName, starred, identifier })

If I do this, and make a post request from postman using something like

  {
  "username": "Bruce Lee",
  "password": "enter the dragon",
  "task": [
      {
          "taskItem": { 
              "type": "figure out error",
              "highlight": true,
              "identifier": 1
               },
          "subTask": [
              {
                  "subTaskItem": { 
                      "pointer": 1,
                      "type": "abc", 
                      "tasks": [1, 2, 3] }
              }]
        }]
    }

the output on mongoDb is:

_id: 62ba2300c854b603578af1ac
task:Array
subTask:
Array
__v:0

can anyone tell me how to access the correct properties in the schema in order to correctly fill out the document using .create()?

How to add a timeout to a PaginateModel Promise in MongoDB

Trying to add a time out to a function that grabs the model, where the type of it in the following format public async grabModel(): Promise<PaginateModel<T>> where T is the extender.

The problem is I’m trying to use a timeout such as maxTimeMS(25000) to add a 25 second time and get the issue Property 'maxTimeMS' does not exist on type Promise<PaginateModel<T>> i’d really appreciate any help.

querySelectorAll Need to select all divs

I’m in need of getting a working search bar for these cards (only one included in the code to save space), the js I’ve been using worked fine for now, but recently I had to add a new div (with class sce-all) which made it search only some of the items or actually too many from different divs and makes the other info into display:none when I search for anything from div (with class sce-e). When I try to search anything right now, it also searches from div (with class sce-e), I only need it to search from div (with class sce-tt) or it could be both, but it gives it the display:none tag currently. I tried changing up the (‘.card div:nth-child(2)’) in the js which is the cause of the problem it seems.
Thanks for any help

const searchEl = document.querySelector('.searchbox');
const x = document.querySelectorAll('.card div:nth-child(2)');

function search(e) {
  x.forEach((item, index) => {
    if (!item.innerHTML.toLowerCase().includes(e.target.value)) {
      item.parentElement.style.display = 'none';
    } else {
      item.parentElement.style.display = 'block';
    }
  })
}

searchEl.addEventListener("keyup", search);
<form class='searchbox'>
  <input class="searchbar" type="text" placeholder="Search.." name="search">
</form>

<div class="main-container">
  <div class="cards-vid">

    <div class="video anim card">
      <div class="video-wrapper">
        <div class="video-wrapper-inside">
          <a href="vid.mp4"><video preload="metadata">
            <source src="vid.mp4#t=139" type="video/mp4">
          </video></a>
        </div>
      </div>
      <div class="sce-all">
        <div class="sce-e"><a href="none">Link Title</a><span class="length-t">0ms</span></div>
        <div class="sce-tt">Title</div>
      </div>
      <div class="tags-and-info">
        <div class="tags"><a><span class="category-tag">Main</span></a><span class="language-edit"><a href="vid.mp4">ENG</a></span></div>
        <hr class="sce-hr">
        <div class="sce-inf">Info<span class="seperate video-seperate"></span>0h 46m<span class="seperate video-seperate"></span>2023</div>
      </div>
    </div>

  </div>
</div>

Returning a promise from JQuery “on ready” function

According to the JQuery docs, the “recommended” syntax for executing code when the DOM objects become safe to manipulate (a.k.a. “on ready”) is this syntax:

$(function() {
  // Handler for .ready() called.
});

The JQuery documentation makes no mention of what JQuery does with the return value, if any, provided by the function. Which brings me to my question: I want to await a promise in my function. Is there any reason why I can’t decorate the function with the required async keyword, like this:

$(async function() {
  await someFuncThatReturnsAPromise();
});

According to the excellent JavaScript.info tutorial on the subject, the await keyword causes the function to return a resolved promise object. If JQuery doesn’t care about the function result, then the fact that the function returns a promise object should (hopefully) have no effect on the underlying “call the page ready handlers” JQuery behavior.

Extract href by regex [duplicate]

could you help out , i am am receiving an email and trying to extract the link from the text so that the match would be [https://development-client.test.app/users/reset-password?email=test.test%40inbox.testmail.app&code=98f192b1-5673-45b5-b498-d55a4ba3345]

I need to ignore the brackets and stop once code= value ends

This would match all the way including the bracket https://[^s]+

Moving object in a parameter to a variable causes function to fail – what is the difference?

I’m trying to figure out what the difference is between these two pieces of code. This is code that uses the Paypal “Smart Buttons” for Javascript to create an order.

This code works.

return actions.order.create({
  purchase_units: [{
    description: orderDescription,
    amount: {
      currency_code: 'USD',
      value: priceTotal,
      breakdown: {
        item_total: {
          currency_code: 'USD',
          value: itemTotalValue,
        },
        shipping: {
          currency_code: 'USD',
          value: shipping,
        },
        tax_total: {
          currency_code: 'USD',
          value: tax,
        }
      }
    },
    items: [{
      name: selectedItemDescription,
      unit_amount: {
        currency_code: 'USD',
        value: selectedItemPrice,
      },
      quantity: quantity
    }]
  }]
});

I want to put the object that is being passed to actions.order.create() in a variable, so I can create an array of those objects to pass. But first I just want to be sure it works passing one object in before adding multiple objects.

I changed it to this:

let purchase_units = [{
    description: orderDescription,
    amount: {
      currency_code: 'USD',
      value: priceTotal,
      breakdown: {
        item_total: {
          currency_code: 'USD',
          value: itemTotalValue,
        },
        shipping: {
          currency_code: 'USD',
          value: shipping,
        },
        tax_total: {
          currency_code: 'USD',
          value: tax,
        }
      }
    },
    items: [{
      name: selectedItemDescription,
      unit_amount: {
        currency_code: 'USD',
        value: selectedItemPrice,
      },
      quantity: quantity
    }]
  }];
  return actions.order.create(purchase_units);

When this version runs, it throws the error:

TypeError: Cannot read properties of undefined (reading 'map')

These look equivalent to me – what am I missing?

jQuery prop counter with updated iterations

I’ve used the jQuery prop-method with the counter-property to create an animation that counts from 0 to the value from the .count-string through an each-loop.

This works as intended, but I would like to increase this value by 3, 2 and 1 respectively, set by the variables cowsIncrement, sheepIncrement and pigsIncrement. Each increment has to happen in 3, 2 and 1-second intervals as well (similiar to the increment value), and it has to run infinitely with the same animation. How would I go about doing this?

Any vanilla JS/jQuery solution is welcome. Thank you!

// #count1
let cowsIncrement = 3;

// #count2
let sheepIncrement = 2;

// #count3
let pigsIncrement = 1;

$('.count').each(function() {
  $(this).prop('Counter', 0).animate({
    Counter: $(this).text()
  }, {
    duration: 1500,
    easing: 'swing',
    step: function(now) {
      $(this).text(Math.ceil(now).toLocaleString('de-DE'));
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<div class="count" id="count1">3000</div><span>cows</span>
<div class="count" id="count2">2000</div><span>sheep</span>
<div class="count" id="count3">1000</div><span>pigs</span>

How to draw a single translucent line of varying width?

I’m trying to allow a user to draw on Canvas with a tablet, which provides me with a ‘pressure’ parameter. I use this parameter to pick a width for the line. This works fine for opaque lines, but if the line is translucent, the ‘ends’ of each segment overlap, creating a circle of darker tone than the line is intended to be. How can I get this to be consistent throughout? Changing the end type leaves jagged edges. I tried using a global alpha instead of applying the transparency on the color, but it yields the same result. My next thing to try is have the drawing occur into a hidden canvas with full opacity, and use that as a mask to be applied to another canvas with the appropriate translucent color, but that seems like a lot of work to do something that I’d assumed the API supports natively.

Any thoughts?

var ctx = document.getElementById('canvas1').getContext('2d');
const c = '#ff000055'
ctx.color = c
ctx.strokeStyle = c
ctx.fillColor = c
ctx.lineCap = 'round'
var points = [null, null, null, null];

for(var i=-1; i<25; i = i +1)
{
    var width = 0.5 + i*2;
    
    var m = 200;
    
    
    var x = Math.cos(i/4) * 180;
    var y = Math.sin(i/4) * 140;
    
    points[0] = points[1];
    points[1] = points[2];
    points[2] = { X:x, Y:y};
    
    if(points[0] == null)
        continue;
    
    
    var p0 = points[0];
    var p1 = points[1];
    var p2 = points[2];

    var x0 = (p0.X + p1.X) / 2;
    var y0 = (p0.Y + p1.Y) / 2;

    var x1 = (p1.X + p2.X) / 2;
    var y1 = (p1.Y + p2.Y) / 2;
    
    ctx.beginPath();
    ctx.lineWidth = width;
    
    ctx.moveTo(m+x0, m+y0);
    ctx.quadraticCurveTo(m+p1.X, m+p1.Y, m+x1, m+y1);
    ctx.stroke();
}

jsfiddle

Building a criteria in mongoDB that doesn’t return the proper values

I’m trying to builda criteria that would filter the entries in the DB ,yet i’m not getting the proper results when filtering the genre. (the text seems to work but i’m not sure if the code will support both filters).

This is my buildCriteria function, console logging returns the proper values.

function _buildCriteria(filterBy) {
  const criteria = {};
  const { text, genre } = filterBy;
  console.log('genre:', genre);

  if (text) {
    const txtCriteria = { $regex: text, $options: 'i' };
    criteria.name = txtCriteria;
  }
  if (genre) {
    criteria.genre = { $eq: genre };
  }
  return criteria;
}

This is the query function :

async function query(filterBy) {
  try {
    const criteria = _buildCriteria(filterBy);

    const collection = await dbService.getCollection('tab');
    const tabs = await collection.find(criteria).toArray();
    return tabs;
  } catch (err) {
    logger.error('Can not find tabs', err);
    throw err;
  }
}

Would appreciate your help greatly!

How can I change the background color of the element?

          //border3
          var revealThree = document.querySelectorAll('.BorderThree');

          for(var i = 0; i < revealThree.length; i++){

            var windowheight = window.innerHeight;
            var revealtop = revealThree[i].getBoundingClientRect().top;
            var revealpoint = 50;

            if(revealtop < windowheight - revealpoint){
              revealThree[i].classList.add('active');
            }
            else{
              revealThree[i].classList.remove('active');
            }
          }

 

I tried creating a border but when I added a js function, the border’s background color suddenly became grey when it should only be a border.

Here’s the code for CSS:

    .BorderThree{
      width: 300px;
      height: 450px;
      position: absolute;
      top: 900px;
      border-style: solid;
      border-color: azure;
      left: 900px;
      transform: translateY(150px);
      opacity: 0;
      transition: all 2s ease;

    }

.BorderThree.active{
  transform: translateY(0px);
  opacity: 1;
color: #000;
}

and when I tried adjusting the the opacity, the whole border is affected. I’d appreciate your help, thank you.

Disable ‘submit’ button unless box is checked

Following on from a previous question I asked
Submit button not working with JS validation

I have been really struggling with getting the checkbox being checked to be part of the form validation.

my html is

    <h1>Applicant Form</h1>
    <div class="container">
      <form action="create-lead.php" id="newLead" class="form" method="POST">
        <div class="form-field">
          <label for="firstName">First Name</label>
          <input type="text" name="firstName" id="firstName" id="firstName">
          <small></small>
        </div>
        <div class="form-field ">
          <label for="lastName">Last Name</label>
          <input type="text" name="lastName" id="lastName" id="lastName">
          <small></small>
        </div>
        <div class="form-field">
          <label for="email">Email</label>
          <input type="text" name="email" id="email">
          <small></small>
        </div>
        <div class="form-field">
          <label for="telephone">Telephone</label>
          <input type="text" name="telephone" id="telephone">
          <small></small>
        </div>
        <div class="form-field dropdown">
          <label for="buyerType" class="buyerType">Application Type</label>
          <select class="secondary" name="buyerType" id="buyerType">
            <option value="Purchase">Purchase</option>
            <option value="FirstTimeBuyer">First Time Buyer</option>
            <option value="Remortgage">Remortgage</option>
            <option value="RaiseFunds">Raise Funds</option>
          </select>
        </div>
        <div class="form-field">
          <label class="check-container" for="accept">
              <input class="check" type="checkbox" id="accept" name="accept" value="yes">
              I agree to the <a href="#">terms and conditions</a>
            </label>
          <small></small>
        </div>
        <div class="form-field buttons">
          <input class="submitButton" type="submit" name="submitButton" id="submitButton">
          <input class="clear" type="reset" name="reset" id="reset">
        </div>
      </form>
    </div>
    <script src="js/app.js"></script>
  

and the app.js is

const firstNameEl = document.querySelector('#firstName');
const lastNameEl = document.querySelector('#lastName');
const emailEl = document.querySelector('#email');
const telephoneEl = document.querySelector('#telephone');
const checkedEl = document.getElementById('#accept');
const submitButton = document.getElementById('#submitButton');

const form = document.querySelector('#newLead');

const checkFirstName = () => {
    let valid = false;

    const firstName = firstNameEl.value.trim();

    if (!isRequired(firstName)) {
        showError(firstNameEl, 'First name cannot be left blank');
    } else if (!isFirstNameValid(firstName)) {
        showError(firstNameEl, 'First name must only contain letters');
    } else {
        showSuccess(firstNameEl);
        valid = true;
    };
    return valid;
};

const checkLastName = () => {
    let valid = false;

    const lastName = lastNameEl.value.trim();

    if (!isRequired(lastName)) {
        showError(lastNameEl, 'Last name cannot be left blank');
    } else if (!isLastNameValid(lastName)) {

        showError(lastNameEl, 'Last name must only contain letters');

    } else {
        showSuccess(lastNameEl);
        valid = true;
    }
    return valid;
};

const checkEmail = () => {
    let valid = false;
    const email = emailEl.value.trim();
    if (!isRequired(email)) {
        showError(emailEl, 'Email field cannot be left blank');
    } else if (!isEmailValid(email)) {
        showError(emailEl, 'Email is not valid')
    } else {
        showSuccess(emailEl);
        valid = true;
    }
    return valid;
};
const checkTelephone = () => {
    let valid = false;
    const telephone = telephoneEl.value.trim();
    if (!isRequired(telephone)) {
        showError(telephoneEl, 'Telephone field cannot be left blank');
    } else if (!isTelephoneValid(telephone)) {
        showError(telephoneEl, 'Number is not valid')
    } else {
        showSuccess(telephoneEl);
        valid = true;
    }
    return valid;
};

// const checkedElValid = () => {
//     if (!document.querySelector('#submitButton').checked) {
//         showError(, 'You must accept the terms to continue')
//     } else {
//         showSuccess(accept);
//         valid = true;
//     }
//     return valid;
// };

const isFirstNameValid = (firstName) => {
    const re = /^[a-zA-Z]+$/;
    return re.test(firstName);
};

const isLastNameValid = (lastName) => {
    const re = /^[a-zA-Z]+$/;
    return re.test(lastName);
};


const isEmailValid = (email) => {
    const re = /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
};

const isTelephoneValid = (telephone) => {
    const re = /^[0-9]+$/;
    return re.test(telephone);
};

const isRequired = value => value === '' ? false : true;


const showError = (input, message) => {
    const formField = input.parentElement;
    formField.classList.remove('success');
    formField.classList.add('error');

    const error = formField.querySelector('small');
    error.textContent = message;
};

const showSuccess = (input) => {
    const formField = input.parentElement;

    formField.classList.remove('error');
    formField.classList.add('success');

    const error = formField.querySelector('small');
    error.textContent = '';
}


form.addEventListener('submit', function(e) {
    //validate fields
    let isFirstNameValid = checkFirstName(),
        isLastNameValid = checkLastName(),
        isEmailValid = checkEmail(),
        isTelephoneValid = checkTelephone();
        IsCheckedElValid = checkedElValid();


    let
        isFormValid = 
        isFirstNameValid &&
        isLastNameValid &&
        isEmailValid &&
        isTelephoneValid &&
        IsCheckedElValid;


    if (!isFormValid) {
        e.preventDefault();
        submitButton.disabled;
    } else {
        submitButton.disabled == false;

    };

});
// real time validation
const debounce = (fn, delay = 500) => {

    let timeoutId;

    return (...args) => {
        if (timeoutId) {
            clearTimeout(timeoutId);
        }
        timeoutId = setTimeout(() => {
            fn.apply(null, args)
        }, delay);
    };
};
//event delegation
form.addEventListener('input', debounce(function(e) {
    switch (e.target.id) {
        case 'firstName':
            checkFirstName();
            break;
        case 'lastName':
            checkLastName();
            break;
        case 'email':
            checkEmail();
            break;
        case 'telephone':
            checkTelephone();
            break;
    }
}));

I have included the commented out section because that is the function I am working on to try and include the checkbox as part of the validation.

Everything else works perfectly, but I need to ensure the user accepts the terms and conditions before the form can be sent.

It seems that e.preventDefault() and submitButton.disabled aren’t working as expected, unless I am missing something..

I am relatively new, and don’t have the experience to get this working properly!

How to create checkboxes dynamically for selected dates of a calendar

With JavaScript or with Ajax

I need to enter the start date with the start time, and the end date with end time. And create four checkboxes for each day of the selected date range, in-line with the date mentioned in front.

BUT the last checkbox of the last raw should not be clickable/selectable IF it is not a complete day with 24 hours in full. Which means if the difference between two entered times are lesser than 1 minute.

Please help. It’s complicated for me.

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script>

    <strong>Start</strong> 
    <br>Date: <input id="fromDate" type='date' />&nbsp;&nbsp;Time:
    <input type="time" id="start-time" placeholder="HH:MM">
    <br><br><br>
    <strong>End</strong>
    <br>Date: <input id="toDate" type='date' />&nbsp;&nbsp;Time:
    <input type="time" id="end-time" placeholder="HH:MM">
    <button id="btn">Submit</button><hr />
    <p id="result"></p>

    <script>

    $("#btn").on('click', function(e) {
    var fromDate = $('#fromDate').val(), 
    toDate = $('#toDate').val(), 
    from, to, druation;
  
    from = moment(fromDate, 'YYYY-MM-DD'); // format in which you have the date
    to = moment(toDate, 'YYYY-MM-DD');     // format in which you have the date
 
    /* using diff */
    duration = to.diff(from, 'days')     
    
    /* show the result */
    $('#result').text(duration + ' days');
    });

    </script>

    <br>

    <input type="text" id="total-hours" placeholder="Total Hours">
    <script>
    document.querySelector("#end-time").addEventListener("change", myFunction);

    function myFunction() {
    function split(time)
    {
    var t = time.split(":");
    return parseInt((t[0] * 60), 10) + parseInt(t[1], 10); //convert to minutes and add minutes    
    }

    //value start
    var start = split($("input#start-time").val()); //format HH:MM
  
    //value end
    var end = split($("input#end-time").val()); //format HH:MM
    
    totalHours = NaN;
    if (start < end)
    {
    totalHours = Math.floor((end-start)/60);
    }  
    $("#total-hours").val(totalHours);
    }
    </script>

Multiple Apollo Queries in one component / screen

I have these two Apollo queries in one react component.

 const { data, loading, error } = useQuery(PlaylistQuery, {
    variables: { _id: playlistId },
    fetchPolicy: "cache-and-network",
  });

  const [loadSong, { called, loading, error, data }] = useLazyQuery(SongQuery, {
    variables: {
      _id: song._id,
    },
  });

This will obviously give me the Cannot redeclare block-scoped variable error message. What’s a smart way to get around this?