I don’t know how to handle errors in Multer with Express

I am using Multer to upload a maximum of 3 images to the server and it works fine, but when I upload more than 3 images, Multer tells me the error but it is not manageable to show the user.

I’m working on the route that calls the controller but in the Multer documentation it only shows how to handle errors with the route along with the controller actions.

Route:

router.post('/', upload.array('pictures', 3), 
    newProduct
);

Documentation code for handling Multer errors:

const multer = require('multer')
const upload = multer().single('avatar')

app.post('/profile', function (req, res) {
  upload(req, res, function (err) {
    if (err instanceof multer.MulterError) {
      // A Multer error occurred when uploading.
    } else if (err) {
      // An unknown error occurred when uploading.
    }

    // Everything went fine.
  })
})

Error response shown by Multer:

error

In this case how could I do the same documentation but separately to handle Multer errors?

Thank you.

How do I get the calendar to start on Sunday for this svelte-kit component?

The version I originally started with has first day of week as Monday, but I need it to be Sunday:

<script>
    import { beforeUpdate } from 'svelte';

    import {
        startOfMonth,
        addMonths,
        format,
        subMonths,
        addDays,
        startOfWeek,
        sub,
        add,
        eachDayOfInterval,
        getDay,
        isToday
    } from 'date-fns';

    let firstDayOfWeek;
    let currentMonth;
    let nextMonth;
    let previousMonth;
    let daysOfCurrentMonth;
    let weekdayOffset;
    let weekNames;

    beforeUpdate(() => {
        firstDayOfWeek = startOfWeek(new Date(), {
            locale: navigator?.language.split('-').pop().toLowerCase() || 'us',
            weekStartsOn: 0
        });
        currentMonth = startOfMonth(new Date());
        nextMonth = startOfMonth(addMonths(new Date(currentMonth), 1));
        previousMonth = startOfMonth(subMonths(new Date(currentMonth), 1));
        daysOfCurrentMonth = eachDayOfInterval({
            start: currentMonth,
            end: sub(nextMonth, { days: 1 })
        });
        weekdayOffset = (getDay(currentMonth) + 7) % 7 || 7;
        weekNames = [...Array(7)].map((_, index) => format(addDays(firstDayOfWeek, index), 'EEEEEE'));
    });
</script>

{#if weekNames}
    <div class="week-days">
        {#each weekNames as weekName}
            <p>{weekName}</p>
        {/each}
    </div>
{/if}

{#if daysOfCurrentMonth}
    <div class="days">
        {#each daysOfCurrentMonth as day, index}
            <p
                class="day"
                style={`
                grid-column: column(${index});
                grid-column-start: ${index === 0 ? weekdayOffset : 0};
                color: ${isToday(day) ? 'red' : 'white'};
            `}
            >
                {format(day, 'dd')}
            </p>
        {/each}
    </div>
{/if}

<style>
    .days,
    .week-days {
        display: grid;
        grid-template-columns: repeat(7, 50px);
        grid-column: 7;
    }
</style>

I believe the problem resides with this line:

weekdayOffset = (getDay(currentMonth) + 7) % 7 || 7;

It has Feb 1, 2022 starting on Monday when it should be Tuesday.

Here is a fiddle: https://codesandbox.io/s/naughty-surf-bovu8?file=/Button.svelte

Issues reformatting old google map opening times to new ones

I am currently importing data from the Google api, but getting inconsistent opening hour times.

This was the original type I was receiving:

[
  { close: { day: 0, time: '1600' }, open: { day: 0, time: '1000' } },
  { close: { day: 1, time: '2000' }, open: { day: 1, time: '0830' } },
  { close: { day: 2, time: '2000' }, open: { day: 2, time: '0830' } },
  { close: { day: 3, time: '2000' }, open: { day: 3, time: '0830' } },
  { close: { day: 4, time: '2000' }, open: { day: 4, time: '0830' } },
  { close: { day: 5, time: '2000' }, open: { day: 5, time: '0830' } },
  { close: { day: 6, time: '1700' }, open: { day: 6, time: '0900' } }
]

But now and then I get this format.

{
  Monday: '9AM–5PM',
  Tuesday: '9AM–5PM',
  Wednesday: '9AM–5PM',
  Thursday: '9AM–5PM',
  Friday: '9AM–5PM',
  Saturday: 'Closed',
  Sunday: 'Closed'
}

I’ve spent ages trying to reformat the second format into the first and original format so it is all consistent, but have been very unsuccessful in doing so…

Can anyone help me? I also have Lowdash/Underscore, but again, cannot figure this one out… I thought maybe someone might have already been doing something similar too.

react-table – How to render image from API

I created a react-table from the youtube tutorial. Everything works perfectly as I wanted, but I have one problem. In the API file I have one value where I have a link. The table in the column called icon displays the link. This is understandable because there is a link in the API file. I know I should write a function that takes the value of the “icon” column (ie link) and put that function in , but I have no idea how to do it. React-table seems terribly complicated to me, and the code is from the tutorial, not mine, and I don’t know how to do this. Could someone help me with this?

API looks like this:

[{"icon":"url","other":"text"},
{"icon":"url","other":"text"}]

Table file:

import React, { useMemo } from 'react';
import '../style.css';
import { motion } from "framer-motion";
import { useTable, useGlobalFilter } from 'react-table';
import { COLUMNS } from './columns.js';
import MOCK_DATA from './MOCK_DATA.json';
import GlobalFiltering from './globalFiltering.js';

const EquipmentTable = () => {

const columns = useMemo(() => COLUMNS, [])
const data = useMemo(() => MOCK_DATA, [])

const { 
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
    state,
    setGlobalFilter} = useTable ({
        columns,
        data
    }, useGlobalFilter)

    const { globalFilter } = state

return (
    <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}>
        <div className="category-container">
            <div className="category-content">
                <div className='category-table'>
                    <p>Możesz przejrzeć cały spis lub wyszukać konkretne przedmioty wpisując ich nazwę, rangę, typ czy nazwę bossa, z którego dropią.</p>
                </div>
                <div className="category-table">
                    <GlobalFiltering filter={globalFilter} setFilter={setGlobalFilter}/>
                </div>
                <div className="category-table">
                    <table className="equipment-table" {...getTableProps()}>
                        <thead class="equipment-table-header">
                            {
                                headerGroups.map(headerGroup => (
                                    <tr className="header-columns" {...headerGroup.getHeaderGroupProps()}>
                                        {
                                            headerGroup.headers.map( column => (
                                                <th {...column.getHeaderProps()}>{column.render('Header')}</th>
                                            ))
                                        }
                                    </tr>
                                ))
                            }
                        </thead>
                        <tbody {...getTableBodyProps()}>
                            {
                                rows.map(row => {
                                    prepareRow(row)
                                    return (
                                        <tr className="body-rows" {...row.getRowProps()}>
                                            {
                                                row.cells.map( cell => {
                                                    return <td className="rows-style" {...cell.getCellProps()}>{cell.render('Cell')}</td>
                                                })
                                            }
                                        </tr>
                                    )
                                })
                            }
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </motion.div>
)
}
export default EquipmentTable

Javascript/TypeScript – Can I add class properties from an array?

Thank you for the help in advance. I am working in TypeScript, I’d assume any JS solution also works. I’d like to make something like this:

class ExcelData {
  'Id 1': items[0].id,
  'Quantity 1': items[0].quantity,
  'Id 2': items[1].id,
  'Quantity 2': items[1].quantity
  //...
  'Id 40': items[39].id,
  'Quantity 40': items[39].quantity,
}

I am trying to use it with the ‘xlsx’ module to export project data into an Excel sheet. It is necessary for this module that it is a class, rather than several arrays. I could type it out manually, but there is 7 properties for every item and this would be very ugly code. It is also possible that I am later asked to add more items.
If it were Python, I could do something like this bc classes and dictionaries are different things:

excel_data = {}
for i in range (40):
  excel_data['Id '+ str(i)] = items[i].id
  excel_data['Quantity '+ str(i)] = items[i].quantity

What is a Typescript alternative?

Thanks!

Retrive image with URL paramter and javascript

Sadly, I have not enough experience in JS to do this.

I want to call the Google chart API with my URL paramter as data.
Here I used Javascript to store the URL paramter ‘voucher’ in a variable from my Website:

mywebsite.com/core/voucher/?voucher=123

This is the code I use:

<script>
    const queryString = window.location.search;
    const urlParams = new URLSearchParams(queryString);
    const voucher= urlParams.get('voucher');
   //voucher = 123
</script>

<img id="qr" src="https://chart.apis.google.com/chart?cht=qr&chs=400x400&chl=1"/>

Now I need the ‘voucher’ variable to call the Google chart URL with my variable as the chl URL paramter. How can i archive this?

Shopify Javascript $0.00 Price Display

This is my first post on Stack, I am very new to JavaScript and need some assistance in a change I am implementing.

In my Shopify theme I am trying to change the Javascript on variant changes to show any (variant.price) that is 0.00 to be displayed as “POA”. I have done the Liquid to ensure on initial page load the this is the case however JavaScript is overwriting this as a user selects different variants. I think the change can be done in this part of code below, however if there is another section I should be looking at please let me know.

_updatePrice: function(evt) {
            var variant = evt.variant;

            var $priceContainer = $(this.selectors.priceContainer, this.$container);
            var $regularPrice = $(this.selectors.regularPrice, $priceContainer);
            var $salePrice = $(this.selectors.salePrice, $priceContainer);
            var $unitPrice = $(this.selectors.unitPrice, $priceContainer);
            var $totalPrice = $(this.selectors.totalPrice, $priceContainer);
            var $labelSale = $(this.selectors.labelSale, this.$container);
            var $unitPriceBaseUnit = $(
                this.selectors.unitPriceBaseUnit,
                $priceContainer
            );

            // Reset product price state
            $priceContainer
                .removeClass(this.classes.productUnavailable)
                .removeClass(this.classes.productOnSale)
                .removeClass(this.classes.productUnitAvailable)
                .removeAttr('aria-hidden');

            // Unavailable
            if (!variant) {
                $priceContainer
                    .addClass(this.classes.productUnavailable)
                    .attr('aria-hidden', true);
                return;
            }               

            // On sale
            var quantity = parseInt($('[data-quantity-input]').val());
            if (variant.compare_at_price > variant.price) {
                $regularPrice.html(
                    theme.Currency.formatMoney(
                        variant.compare_at_price,
                        theme.moneyFormat
                    )
                );
                $salePrice.html(
                    theme.Currency.formatMoney(variant.price, theme.moneyFormat)
                );
                $('[data-total-price]').attr('data-price-value', variant.price)
                $('[data-total-price]').html(
                    theme.Currency.formatMoney(variant.price*quantity, theme.moneyFormat)
                );
                $priceContainer.addClass(this.classes.productOnSale);
                // label Sale
                $labelSale.show();
                $labelSale.html('-' + Math.floor(((variant.compare_at_price - variant.price)/variant.compare_at_price)*100) + '%' );
            } else {
                // Regular price
                $regularPrice.html(
                    theme.Currency.formatMoney(variant.price, theme.moneyFormat)
                );
                $salePrice.html("");
                $('[data-total-price]').attr('data-price-value', variant.price)
                $('[data-total-price]').html(
                    theme.Currency.formatMoney(variant.price*quantity, theme.moneyFormat)
                );
                $labelSale.hide();
            }

            if (checkNeedToConvertCurrency()) {
                Currency.convertAll(window.shop_currency, $('#currencies .active').attr('data-currency'), 'span.money', 'money_format');
            }

            // Unit price
            // if (variant.unit_price) {
            //     $unitPrice.html(
            //         theme.Currency.formatMoney(variant.unit_price, theme.moneyFormat)
            //     );
            //     $unitPriceBaseUnit.html(this._getBaseUnit(variant));
            //     $priceContainer.addClass(this.classes.productUnitAvailable);
            // }
        },

Thank you all kindly 🙂

How to get all attr value in same class by click() jQuery

I am making a Simon game, but I need to get the “id” (attribute) value. but whenever I click on the different color it still gives me the first attr value which is in this case is green. how many times do I click on the red, blue, or yellow button but it still gives me a green value (the first one). help, please!

//Below code HTML

<div class="container">
      <button class="btn green" id="green"></button>
      <button class="btn red" id="red"></button><br />
      <button class="btn yellow" id="yellow"></button>
      <button class="btn blue" id="blue"></button>
    </div>

//Below code Jquery

$(".btn").click(function () {
    var userChosenColor =$(".btn").attr("id");
    console.log(userChosenColor);
});

How to let web-socket server and client communicate until server stops sending the data?

I am working on a group project where we have a rover which has Raspberry Pi (Python) sending the location in coordinates to a javascript webpage. I can successfully create a simple echo python server and javascript client but want to learn how We can keep the client and server running where the Server is giving out coordinates of the rover continuously to the javascript client till Rover reaches its destination and the connection closes.

firebase admin or normal firebase with next js

I am working on next js project and I use it with firebase and right now I use firebase with my components to retrieve some data and it works perfectly – as expected – and I wanted to use firebase in getServerSideProps so I thought I should use firebase admin sdk but for fun I tried to use it with the same firebase package I used on front end and – I don’t know how – it worked however the code in getServerSideProps must be a back end code so right now I don’t know why does it work and If I should keep using firebase web package or switch to firebase admin package

Pass data from JS to Python via Django

I want to send data from python to JS in Django. I successfully see the data in the response in the browser, but JS returns as empty string. What would be the reason?

trying to fetch information;

def XXX(request):
    message_id=request.POST.get('messageid')
    return render(request, 'XX.html')

sender;

    y = json.loads(response.text)
    ts = str(y["file"]["shares"]["public"]["XX"][0]["ts"])
    return render (request, 'problemduyurusucreate.html', {'ts':ts})

JS;

...
var test = "{{ ts }}";
                $.ajax({
                type: "POST",
                url: "{% url 'slack' %}",
                data: { 
                  "messageid": test,
                csrfmiddlewaretoken: '{{ csrf_token }}'
                }  
...

but I am displaying in my browser that I have successfully pulled the data
enter image description here

How would I log the hash values in this API response?

I’m new to javascript and I was wondering how I would access the hash value and return the string so I can log it? Here’s my code, I’m using axios.

Here’s my code:

client.on("messageCreate", (message) => {
        const args = message.content.slice(prefix.length).trim().split(' ')
    const command = args.shift().toLowerCase();
   
    if (command === 'search') {
        let termargs = args.join(" ");
        
        const options = {
            method: 'GET',
            url: 'https://breachdirectory.p.rapidapi.com/',
            params: { func: 'auto', term: termargs},
            headers: {
                'x-rapidapi-host': 'breachdirectory.p.rapidapi.com',
                'x-rapidapi-key': (keytouse, keys[keytouse]),
            }
        };
        message.reply("searching...")
        options.params.term = termargs
        


        axios.request(options).then(function (response) {
            
            console.log('Found:' , response.data["result"]);
        }).catch(function (error) {
           message.reply(JSON.stringify(error));
        });
    }

        
});



client.login(TOKEN);

Here’s what it returns:

Found: 

    [
      { has_password: false, sources: [ 'Pluto.tv' ] },
      {
        has_password: true,
        password: 'bleh',
        hash: 'kMUX9351bsMjbgXH9rpKKf+GIYJrJy4=',
        sources: [ 'Aptoide.com' ]
      },
      {
        has_password: true,
        password: 'blah',
        hash: 'lEiyXSecP9cIGJfyYhs8yteVEplUIRjAvaI7Jc76upI=',
        sources: [ 'Collection 1' ]
      },
      {
        has_password: true,
        password: 'blahblahblah',
        hash: 'djdrICyb/EfH6+R0g/26+d+GIYJrJy6j',
        sources: 'Unverified'
      }
    ]

I tried doing response.data.results.hash but that didn’t work. Any help would be appreciated. Thank you!

Dynamic routes not working for any routes besides ‘/’

import React from "react";
import { Home, Profile, Saved, Explore, Auth, Settings } from "./pages";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";

const App = () => {
    const routes = [
        { path: "/", component: Home },
        { path: "/profile/:id", component: Profile },
        { path: "/saved", component: Saved },
        { path: "/explore", component: Explore },
        { path: "/auth", component: Auth },
        { path: "/settings", component: Settings },
    ];
    return (
        <div className="bg-gray-200 w-full min-h-screen">
            <Router>
                <Switch>
                    {" "}
                    {routes.map((route, i) => {
                        return <Route key={i} exact path={route.path} component={route.component} />;
                    })}{" "}
                </Switch>
            </Router>
        </div>
    );
};

I can’t seem to figure this out. If I make the first path dynamic it works. But the rest of the Routes don’t work when I try and make them dynamic. Am I missing something, I checked around and looked at tutorials but couldn’t find anything I would be missing