Best way to catch an error in Models? (Node.js + Sequelize)

Is there a simple way to catch an error in an API (server) that’s using Node.js and Sequelize (Models)? Here is my code (it uses async + await):

const router = express.Router()
const { Operations } = require('../models')

router.post('/operations/add', async (req, res) => {
    const operations = req.body
    await operations.create(operations)
    res.json(operations)
    console.log('op added!')
})

router.put('/operations/update/:id', async (req, res) => {
    const operationId = req.params.id
    const operationUpdatedData = req.body
    const operationById = await Operation.findOne({ where: { id: operationId } })
    const operationUpdated = await operationById.update(operationUpdatedData)
    res.json(operationUpdated)
    console.log('op updated!')
})

router.delete('/operations/delete/:id', async (req, res) => {
    const operationId = req.params.id
    await Operations.destroy({ where: { id: operationId } })
    res.send('op deleted!')
    console.log('op deleted!')
})

module.exports = router

This is how I handle an error in the client:

axios.post(`http://localhost:9000/operations/add`, data)
            .then(res => console.log(`op added! (${res.status})`))
            .catch(err => console.log(`wrong! (${err.response.status} )`))

I don’t want anything fancy, but feel free to try whatever you want!

Remove missing Images from array React.js

I have array of images coming from external API, I want to filter images which are broken before showing them on carousel. as you can see now I map every image and showing MissingImage component as unloader if image is missing, but in my situation sometimes there are more than half images not available on API. how can I skip images if they aren’t available before passing them to Carousel component?

          {images.map((img, i) => (
        <Dot
          key={i}
          type="button"
          onClick={() => {
            setThumbsPosition(i);
            goToSlide(i);
            setActiveSlide(i);
          }}
          active={activeSlide === i}
          ref={i === 0 && slideRef}
        >
          <SliderDotImage>
            <Img
              loading="lazy"
              src={[img.url.bigger]}
              unloader={<MissingImage small />}
            />
          </SliderDotImage>
        </Dot>
      ))}

react variable not changing

in my react app i have got two files and, when value of (number) is changing in file App.js
in Form.js is still the same. What am i doing wrong?

App.js

import * as React from "react";
import { Form } from "./Components/Form";

function App() {
  
  let number = 0;
  const onInputChange = e => number = e.target.value;
    // number is changing every time i type something in
  return (
    <>
      <input onChange={onInputChange}></input>
      <Form number={number} />
    </>
  );
}

export default App;

Form.js

import React from "react";

export const Form =({number}) =>
{
    return(
        <h1>{number}</h1>
    )
}

onbeforeunload function fires on browser back button

We´re using following code to show a loading-modal if the loading of next page takes to long.

window.onbeforeunload = function () {
    window.setTimeout(showLoader, 2000);
}

function showLoader() {
    var loader = '<div id="layoutLoadingModal" class="modal fade" role="dialog">' +
        '<div class="modal-dialog">' +
            '<div class="modal-content">' +
                '<div class="modal-body">' +
                    '<h1>Loading!</h1>' +
                '</div>' +
            '</div>' +
        '</div>' +
    '</div>';
    $("body").append(loader);
    $('#layoutLoadingModal').modal('show');
}

Unfortunately it also shows the modal if the user uses the browser back button or a button with history.go(-1);
Is there any way to tweek the code to prevent this?

cancel a mocked function in Jest and getting the original behavior after a single call

class MyService{
    async f1(args) {
        let out= await this.f2(args);
        ...
    }
}
...
// my test code:
MyService.f1.mockResolvedValueOnce([]);
await OtherService.f3(); // f1 is mocked and called in f3 and returns [] (everything is fine)
MyService.f1.mockRestore(); // trying to forget mocking f1 and getting the original behavior
MyService.f2.mockResolvedValueOnce([some data]); // I want original f1 to be called and mock the inner f2 but f1 is never called and I get undefined output from it

I’m trying to mock MyService’s functions only occasionally and after using the mocked version, forget that mocking and get the original behavior of them. But when I do it for once and restore that mock, I get undefined for the output of the mocked function and it’s actually never called.

Variables from different scripts are getting overridden

I am learning javascript and made a project where I have two canvases where I draw circles on. The scripts for each canvas is in its own file in the same folder. My problem is that for both of these scripts I am using the same variable names eg. radius and they seem to be shared between the two scripts.

I declare the variables as follows in the beginning of the file and then the function right afterwards.

const radius = 23;
const motionTrailLength = 30;
var context;
var xPos, yPos, maxX, maxY;
var dx = 2;
var dy = 2;

function init(canvas) {...}

I read that let and const “declared inside a { } block cannot be accessed from outside the block” so is there some way can wrap the script in those blocks to stop them from getting overridden?

Unable to get the value of a Promise . Error “Property ‘Choices’ does not exist on type ‘Promise'” [duplicate]

I have the following type script inside my ReactJs SPFx sharepoint online web part:-

import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
  IPropertyPaneConfiguration,
  IPropertyPaneDropdownOption,
  PropertyPaneDropdown} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';

import * as strings from 'ContactListWebPartStrings';
import ContactListApp from './components/ContactListApp';
import { IContactListProps } from './components/IContactListProps';
import { sp } from "@pnp/sp/presets/all";


export interface IContactListWebPartProps {
  department: string;
}

export default class ContactListWebPart extends BaseClientSideWebPart<IContactListWebPartProps> {
  private viewModeOptions: IPropertyPaneDropdownOption[] = null;
  public render(): void {
    const element: React.ReactElement<IContactListProps> = React.createElement(
      ContactListApp,
      {
        department: this.properties.department,
        context: this.context
      }
    );

    ReactDom.render(element, this.domElement);
  }

  protected onDispose(): void {
    ReactDom.unmountComponentAtNode(this.domElement);
  }

  protected get dataVersion(): Version {
    return Version.parse('1.0');
  }
  public onInit(): Promise<void> {
    return super.onInit().then( _ => {
      sp.setup({
        spfxContext: this.context
      });
      const choice =  
      sp.web.lists.getByTitle('Contacts').fields.getByTitle('Department').get();
      this.viewModeOptions = choice.Choices.map((choice: string, idx: number) => 
      {
        return {
         key: idx,
         text: choice
        }
      })
   });
  }


  protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
    return {
      pages: [
        {
          header: {
            description: strings.PropertyPaneDescription
          },
          groups: [
            {
              groupName: strings.BasicGroupName,
              groupFields: [
                PropertyPaneDropdown('department', {
                  label: 'Department',
                  options: this.viewModeOptions,
                  selectedKey: this.viewModeOptions[0].key,
                  disabled: !this.viewModeOptions
                 }),
              ]
            }
          ]
        }
      ]
    };
  }
}

but i am getting this error on choice.Choices.map:-

Property ‘Choices’ does not exist on type ‘Promise’

here is my web part details:-

{
  "@microsoft/generator-sharepoint": {
    "isCreatingSolution": true,
    "environment": "spo",
    "version": "1.12.1",
    "libraryName": "contact-list-webpart",
    "libraryId": "aa3dbbd0-0d6b-4cae-98b0-c29c37998c6e",
    "packageManager": "npm",
    "isDomainIsolated": false,
    "componentType": "webpart"
  }
}

How to flip image in jquery if the animation is at 0% and 50%?

I am try to make a running santa in my project.

How to loop transform: scaleX(1) and transform: scaleX(-1) when the animation start in 0% an 50%?

setTimeout(function(){
  //Enter your stuff here
  $('.animation').css("transform", "scaleX(1)")
}, 7500);  
.animation img {
  max-width: 100%;
}

.animation {
  width: 50px;
  position: absolute;
  bottom: 0;
  animation: example 15s infinite; 
  padding: 5px 9px 1px 0;
  border-top-right-radius: 20px;
  border-top-left-radius: 20px;
  transform: scaleX(-1)
}

@keyframes example {
  0%,
  100% {
    left: 0;  
    /* background: white; */
  }
  40% {
    /* background: green; */
  }
  30% {
    /* background: yellow; */
  }
  20% {
    /* background: orange; */
  }
  50% {
    left: 97%;  
    /* background: blue; */
  }  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="animation">
  <img src="https://lh3.googleusercontent.com/pw/AM-JKLX6lpuXIUQzWYC8J9vlnsS9Cb9irs-2kPKBM9XaugC4iDCag2-7w-zC7BSQls0Ea51YewUFFSJquODLZ8PfaAoqelAXOlCKmh0H7Cn9G5HcwX_u2XNT_tvr8ZD5as6He3dpMrrVH_-ZCaG1xctS_Tei=s512-no" alt="run santa run">
</div>

Codepen link: demo

JSON image importing

I am trying to add 4 images on my site however the images are not loading. I can see 4 images in the inspector tool, however they are not showing up.

This is my code in JS:

function createZooland(zoolandData) {
    let content = document.getElementById("content");

let h2 = document.createElement("h2");
let h3 = document.createElement("h3");
let blockquote = document.createElement("blockquote");
let img = document.createElement("img");

h2.innerHTML = `${zoolandData[0].common_name}`;
content.appendChild(h2);

h3.innerHTML = `${zoolandData[0].scientific_name}`;
content.appendChild(h3);

blockquote.innerHTML = `${zoolandData[0].description}`; 
content.appendChild(blockquote);

for(let i = 0; i < zoolandData.length; i++){
    for(let j = 0; j < zoolandData[i].images["image"].length; j++){
        img.src = "images/" + `${zoolandData[0].images.image}`;
        

        content.appendChild(img);
    }
}

}

and this is the JSON it’s referencing:

{
            "common_name": "Koala",
            "scientific_name": "Phascolarctos cinereus",
            "description": "Koalas are well-known...",
            "images": {
                "image": [
                    "koala1.jpg",
                    "koala2.jpg",
                    "koala3.jpg",
                    "koala4.jpg"
                ]
            }
        },

Please let me know if any additional information is needed. I’m not sure how to get the images to display.

How do I paste text with Android clipboard manager in an empty input in a WebView?

We have a web page with an input element on a webview App on Android.

If the input text is not empty, has text, you can touch and the clipboard manager is launched and shows:
When clipboard is empty “select all”
When clipboard is full “paste, select all”

BUT, when the input text is empty you can not launch the clipboard manager in order to paste text.

Should I implement onLongClick on Android webview app? if yes, what is the code to simply launch the Android Clipboard Manager?

Should I add an html paste button and solve it with html code?

How to check whether a user exists in mongoose?

So, I am trying to check whether there is a user or not I have the following code:

const userExist = await User.find({ username: req.body.username });
if (userExist)
   return res.status(400).send({ message: "User already exists" });

but even if the user doesn’t exist it still gives the error User already exists and the userExists object return []

How to return an array with the step of the sum of the previous value?

How to return an array with the step of the sum of the previous value?

I have an input number that is 1000
I want to get [1000, 2000, 3000 … 10000]

I’m trying to:

  const range = (i: number, o: number) => {
    const arr = [0, 1, 2, 3, 4].reduce(
      (accumulator: any, currentValue: any, index: any, array: any) => {
        console.log((array[index] = accumulator + currentValue));
        return 1;
      },
      10000
    );
  };

  range(1000, 10000);

How Jsx is valid javascript?

I use react and jsx. my question is how jsx is a valid js syntax? only way that I think it’s maybe true, is that react compiles all the file and converts jsx(s) to valid js. like what C preprocessor does with macros. is it true? and if it is true, is it right that we consider react as js library? I think it is higher level of a library.

if No, who it is done?