Sequelize beforeSave hook not firing when syntax is correct

I’m trying to use beforeSave hook when creating an order for my database. This hook is supposed to set the location of the order however the hook is never fired so the order never has a location. This is my hook that I have created:

{
    hooks: {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      beforeSave: async (order: any) => {

        console.log('Test')

        // ------------- Set location -------------

        const storeId = order.store;

        const storeInstance = await Store.findByPk(storeId);

        if (!storeInstance) {
          throw new Error('Store not found');
        }

        const locationId = storeInstance.location;

        order.location = locationId;

        console.log(order.location)

        // ------------- Create customer if not exist -------------

        const customer = {
          shipping_firstname: order.shipping_firstname,
          shipping_lastname: order.shipping_lastname,
          shipping_country: order.shipping_country,
          shipping_region: order.shipping_region,
          shipping_city: order.shipping_city,
          shipping_postcode: order.shipping_postcode,
          shipping_address1: order.shipping_address1,
          shipping_address2: order.shipping_address2 || null,
          shipping_phone: order.shipping_phone || null,
          shipping_email: order.shipping_email || null,

          billing_firstname: order.billing_firstname,
          billing_lastname: order.billing_lastname,
          billing_country: order.billing_country,
          billing_region: order.billing_region,
          billing_city: order.billing_city,
          billing_postcode: order.billing_postcode,
          billing_address1: order.billing_address1,
          billing_address2: order.billing_address2 || null,
          billing_phone: order.billing_phone || null,
          billing_email: order.billing_email || null
        }

        const fcustomer = await Customer.findOne({
          where: {
            billing_firstname: Seq.where(Seq.fn('lower', Seq.col('billing_firstname')), Seq.fn('lower', customer.billing_firstname)),
            billing_lastname: Seq.where(Seq.fn('lower', Seq.col('billing_lastname')), Seq.fn('lower', customer.billing_lastname)),
            billing_country: Seq.where(Seq.fn('lower', Seq.col('billing_country')), Seq.fn('lower', customer.billing_country)),
            billing_region: Seq.where(Seq.fn('lower', Seq.col('billing_region')), Seq.fn('lower', customer.billing_region)),
            billing_postcode: Seq.where(Seq.fn('lower', Seq.col('billing_postcode')), Seq.fn('lower', customer.billing_postcode)),
            billing_address1: Seq.where(Seq.fn('lower', Seq.col('billing_address1')), Seq.fn('lower', customer.billing_address1)),
          }
        })

        if (fcustomer) {
          fcustomer.update(customer);
        } else {
          Customer.create(customer)
            .catch((err: Error) => {
              console.error(err)
            });
        }

        /*         const products = order.products;
        
                for (let i = 0; i < products.length; i++) {
                    const product = products[i];
                    const foundProduct = await Inventory.findByPk(product.id);
                    foundProduct.stockOnHold = foundProduct.stockOnHold + product.qty;
                    foundProduct.save();
                } */
      },
    },

    sequelize,
    modelName: 'Order',
  });

And then this is my fetch request for creating an order:

fetch('/orders/api', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(data)
                }).then((res) => res.json()).then((data) => {
                    if (data.code === 200) {
                        ordersCreateKit.close();
                        orders.fetchOrders();
                        orders.fetchOrderStats();
                    }
                }).catch((err) => {
                    console.log(err);
                })

This is supposed to be the code that adds the location to the order. It used to fire but when I restarted the server it stopped and nothing was changed.

How can we relate two function parameters in TypeScript, in a generic function?

I am struggling adding the right types for function parameters, where the function should be generic and the parameters should relate to each other.

It is best explained with code, here is a minimal reproducible example:

interface Foo {
  union: 'one' | 'two' | 'three';
  object: {
    One: {'oneRelatedKey': 'oneRelatedValue'};
    Two: {'twoRelatedKey': 'twoRelatedValue'};
    Three: {'threeRelatedKey': 'threeRelatedValue'};
  };
};

const objectOne = {
  one: {
    func: (obj: Foo['object']['One']) => {console.log(obj)}
  },
  two: {
    func: (obj: Foo['object']['Two']) => {console.log(obj)}
  },
  three: {
    func: (obj: Foo['object']['Three']) => {console.log(obj)}
  },
};

const func = <T extends Foo['union']>(one: T, two: Foo['object'][Capitalize<T>]) => {
  objectOne[one].func(two);
}

I am getting an error on two:

Property ”twoRelatedKey” is missing in type ‘{ oneRelatedKey:
“oneRelatedValue”; }’ but required in type ‘{ twoRelatedKey:
“twoRelatedValue”; }’

I want to ensure that func is called with a string from Foo['union'] and the corresponding object from Foo['object'], indexed on the capitalized version of the passed in Foo['union'] argument.

If should then work to call func as follows:

func('one', { 'oneRelatedKey': 'foo' })

Note:
The example is an MRE. In the actual code, the type (Foo) and the object (objectOne) comes from a library that I cannot change, and the function func is one I am trying to create myself.

video conference tile view resize listener

I work on a video conferencing app, and want to re-write the logic for the tile / gallery view in our call room.

Basically, we want to make the video call participant’s divs as big as possible (either stacked or side-to-side), to fill a given parent div. They will always be a particular ratio (4:3).

how are people doing this?
are there any libraries or open-source projects for this?

I hope this question makes sense!

I really like how google meet are doing it, I think they are using translate3d.
Animations would also be great.

Thanks

We have a solution at the moment, a mutation observer wrapped in a directive in our angular app. However we are experiencing some jankiness and strange behaviour when users enter and exit the room, and other elements come on screen, changing the layout.

Generated library does not work when integrating with other applications

I just developed a library with React.
The goal of this library is that it will be functional on all types of React and no-React applications.

Currently, I encountered a problem while testing my lib on other applications.

The problem that the generated code does not find React knowing that I have indicated that React and React-dom are external libs in my vite.config.ts file

Thank you for guiding me to resolve this problem. the objective is for the generated code to be completely autonomous and independent

Below you will find the contents of my files:

  • vite.config.ts file
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    react()
  ],
  build: {
    lib: {
      entry: path.resolve(__dirname, './src/main.tsx'),
      name: 'accessibility-turnkey',
      formats: ['es', 'umd'],
      fileName: (format) => `accessibility-turnkey.${format}.js`,
    }, 
    rollupOptions: {
      external: ['react', 'react-dom']
    },
    emptyOutDir: true,
  }
})
  • and package.json file
{
  "name": "accessibility-turnkey",
  "private": true,
  "version": "1.0.0",
  "type": "module",
  "files": [
    "dist"
  ],
  "main": "./dist/accessibility-turnkey.umd.js",
  "module": "./dist/accessibility-turnkey.es.js",
  "exports": {
    ".": {
      "import": "./dist/accessibility-turnkey.es.js",
      "require": "./dist/accessibility-turnkey.umd.js"
    },
    "./style.css": "./dist/style.css"
  },
  "typesVersions": {
    "*": {
      "*": [
        "./dist/*"
      ]
    }
  },
  "publishConfig": {
    "access": "public"
  },
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview"
  },
  "dependencies": { ... },
  "devDependencies": { ... }
}

This is the error encountered with .es.js version
Uncaught TypeError: Failed to resolve module specifier "react". Relative references must start with either "/", "./", or "../".

enter image description here

with .umd.js version
Uncaught TypeError: Cannot read properties of undefined (reading '__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED')

enter image description here

how do I get postmessage from webview in flutter web and android

I am making an app where which shows an iframe content, so I am using an IFrameElement and HtmlElementView for the web which works, but the android part using webview_flutter not working

Working web part

import 'dart:html';
import 'dart:ui_web' as ui;
import 'package:flutter/material.dart';

class ShowView extends StatefulWidget {
  const ShowView({super.key});

  @override
  State<ShowView> createState() => _ShowViewState();
}

class _ShowViewState extends State<ShowView> {
  @override
  void initState() {
    //setup listener ---------------------------------
    window.addEventListener("message", (Event event) {
      String? data = (event as MessageEvent).data.toString();
      print('message: $data');
    });
    // ignore: undefined_prefixed_name
    ui.platformViewRegistry.registerViewFactory(
      'test-view-type',
      (int viewId) => IFrameElement()
        ..height = '500'
        ..width = '500'
        ..src = '<URL>'
        ..style.border = 'none',
    );

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return const HtmlElementView(
      viewType: 'test-view-type',
    );
  }
}

Not working android part

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class ShowView extends StatefulWidget {
  const ShowView({super.key});

  @override
  State<ShowView> createState() => _ShowViewState();
}

class _ShowViewState extends State<ShowView> {
  late WebViewController controller;

  @override
  void initState() {
    controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..addJavaScriptChannel(
        'message',
        onMessageReceived: (JavaScriptMessage message) {
          print('channel Message: $message');
        },
      )
      ..loadRequest(
        Uri.parse(
          '<URL>',
        ),
      );
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return WebViewWidget(controller: controller);
  }
}

The Iframe is giving the data like this

window.parent.postMessage(data,'*');

For web I am window.addEventListener which works, for android I am trying addJavaScriptChannel which is not working

How can I fix the vuetify menu position shifting upon the first click after page render?

I have a text field with a GIF icon menu. Upon clicking the menu icon, a GIF dialog (GifDialog.vue) pops up displaying GIF content. I’m encountering an issue where upon the initial click after the page renders, the menu position shifts unexpectedly (See Picture No.1). However, upon closing the menu and clicking the icon again, it returns to its normal position (See Picture No.2). This issue occurs consistently upon page refresh. I suspect the problem may be related to the image, but after checking the documentation, I couldn’t find any API to address it. How can I resolve this?

Index.vue

<v-text-field>
  <template #append>
    <v-menu
      top
      right
      :max-width="$vuetify.breakpoint.smAndUp ? 500 : 250"
      max-height="500"
      :close-on-content-click="false"
      offset-y
    >
      <template v-slot:activator="{ on, attrs }">
        <v-btn
          icon
          large
          v-bind="attrs"
          v-on="on"
        >
          <v-icon>
            mdi-file-gif-box
          </v-icon>
        </v-btn>
      </template>
      <gif-dialog/>
    </v-menu>
  </template>
</v-text-field>

GifDialog.vue

<template>
  <v-card>
    <div>
      ....
    </div>
    <v-row no-gutters>
      <v-col
        v-for="(item, index) in categories"
        :key="index"
        cols="12"
        sm="4"
      >
        <v-img
          height="110"
          :src="item.image"
          class="ma-2 rounded"
          style="cursor: pointer;"
        >
          <div
            class="d-flex fill-height justify-center align-center"
            style="color:white;"
          >
            {{ item.searchterm }}
          </div>
        </v-img>
      </v-col>
    </v-row>
  </v-card>
</template>

Picture No.1
enter image description here
Picture No.2
enter image description here

Adding ‘dictionary’ into my local storage doesn’t work

AnyFunction() {
    var data = JSON.parse(localStorage.getItem("data"));

    var x = randomID();

    var user = {[x]: {
      username: "anything",
      email: "anything",
      password: "anything",
      wallet: 0,
      cart: {},
      }
    };

    data["users"] += user;

    localStorage.setItem("data", JSON.stringify(data));

Local Storage:

{users: {}, products: {}}

It works with data["users"] = user, but I’m trying to make it to be able to add users instead of changing it but data["users"] += user returns “[object Object][object Object]”.

Blessed npm styling list item rows conditionally

I am using the Blessed npm package to render markdown in the terminal and I want to render tags different colours.

For example:

h1 = yellow
p = green

I have tried a few different methods but have had no luck. For example:

list.on("element", function (item) {
  item.style.fg = "red";
});

Can anyone out there point me in the right direction?

Full function:

function createList(markdown) {
  const list = blessed.list({
    items: markdown.split("n"),
    height: "75%",
    width: "75%",
    scrollable: true,
    style: {
      selected: {
        fg: "black",
        bg: "yellow",
      },
    },
    border: {
      type: "line",
    },
    mouse: true,
    keys: true,
    vi: true,
    alwaysScroll: true,
    scrollbar: {
      ch: " ",
      inverse: true,
    },
    left: "center",
    top: "center",
  });
  list.on("element", function (item) {
      item.style.fg = "red"; // Change the foreground color to red
  });
  return list;
}

Center a span element around highlighted text and break-word overflow on both sides

I have a span element that can have a long text which is truncated using css at the end if it overflows. The text also contains some highlighted text, but if this part is towards the end of the long text, the highlighted part is not visible. I need the highlighted part to be around the center of the text that is visible, and overflow should work on both sides. How can I achieve this?


<html>
    <head>
        <style>
            .dont-break-out {
              overflow-wrap: break-word;
              word-wrap: break-word;
            }
        </style>
    </head>
    <body>
        <div style="max-width: 200px;">
            <span class="dont-break-out">
                <span style="max-width: 100%;overflow: hidden;text-overflow: ellipsis;display: -webkit-box;-webkit-line-clamp: 1;-webkit-box-orient: vertical;">
                    This is a very long text and at the end of this very long text, I have a <em style="font-size: larger;">highlighted</em> part that should be visible.
                </span>
            </span>
        </div>
    </body>
</html>

Can’t Find Installed React Native Android App On Phone and Emulator?

So something strange happened, when developing I noticed that my react-native app compiled but wasn’t visible (not found on the apps list/tray) on my emulator although the react-native run-android launches it (both debug and release) but when I go to Settings > Apps I can see the app listed there, I thought this was some new thing to react for dev environments, but I noticed that after compiling my app as release I can’t find it on the phone until I go to Settings > Apps and even from there I can’t launch.

Another thing I first noticed was, that the first time I compile the release, while trying to install a notice appeared on my screen saying, Google play connect rejected my app, and at first I couldn’t install the app, but after rerunning the compilation I was able to, but now the app can’t be launched.

I tried to re-build , did ./gradelw clean and also update the build version nothing works for me .

How do I send app data to the storefront?

I’m new to building an Shopify app (Remix and JavaScript) for my Shopify store, where I’m adding a phone number that will be used as a WhatsApp redirection on the storefront.

I know there are other similar apps that exist, but I’m creating this for learning purposes.

Currently, the app is installed but how do I fetch the data to the Storefront, so the WhatsApp icon will be appear as a redirection?

I’ve made some code by using Polaris below is my code of  app._index.jsx.

import { useEffect } from "react";
import { json } from "@remix-run/node";
import { useActionData, useNavigation, useSubmit } from "@remix-run/react";
import { LegacyStack, RadioButton, Text, TextField, Page, Card, Button, Image, Box, BlockStack } from "@shopify/polaris";
import { useState, useCallback } from 'react';

import { authenticate } from "../shopify.server";
import db from "../db.server";

export async function loader() {
  return null;
}

export const action = async ({ request }) => {
  const { admin } = await authenticate.admin(request);
  const color = ["Red", "Orange", "Yellow", "Green"][
    Math.floor(Math.random() * 4)
  ];
  const response = await admin.graphql(
    `#graphql
      mutation populateProduct($input: ProductInput!) {
        productCreate(input: $input) {
          product {
            id
            title
            handle
            status
            variants(first: 10) {
              edges {
                node {
                  id
                  price
                  barcode
                  createdAt
                }
              }
            }
          }
        }
      }`,
    {
      variables: {
        input: {
          title: `${color} Snowboard`,
        },
      },
    },
  );
  const responseJson = await response.json();
  const variantId =
    responseJson.data.productCreate.product.variants.edges[0].node.id;
  const variantResponse = await admin.graphql(
    `#graphql
      mutation updateVariant($input: ProductVariantInput!) {
        productVariantUpdate(input: $input) {
          productVariant {
            id
            price
            barcode
            createdAt
          }
        }
      }`,
    {
      variables: {
        input: {
          id: variantId,
          price: Math.random() * 100,
        },
      },
    },
  );
  const variantResponseJson = await variantResponse.json();

  return json({
    product: responseJson.data.productCreate.product,
    variant: variantResponseJson.data.productVariantUpdate.productVariant,
  });
};

export default function Index() {
  const nav = useNavigation();
  const actionData = useActionData();
  const submit = useSubmit();
  const [showStep1, setShowStep1] = useState(true);

  const toggleSteps = useCallback(() => {
    setShowStep1(!showStep1);
  }, [showStep1]);

  const goBack = useCallback(() => {
    setShowStep1(true);
  }, []);

  const [whatsappNumber, setWhatsappNumber] = useState("");

  useEffect(() => {
    if (actionData?.product?.id) {
      // Product created, you may show a notification
    }
  }, [actionData]);

  const handleSave = () => {
    // Save WhatsApp number to localStorage
    localStorage.setItem("whatsappNumber", whatsappNumber);
  };
  

  //Radio Button jQuery
   const [value, setValue] = useState('disabled');

  const handleChange = useCallback(
    // (_: boolean, newValue: string) => setValue(newValue),
    [],
  );

  return (
    <Page 
    title="WhatsApp Redirection" primaryAction={{content: 'Save', disabled: true}}
>
       {whatsappNumber && (
      <a href={`https://wa.me/${whatsappNumber}`} target="_blank" className="whatsapp-icon">
        <Image
          source="https://cdn.shopify.com/s/files/1/0592/3880/9793/files/whatsapp-svgrepo-com.png?v=1713350385"
          alt="WhatsApp Icon"
          width="75px"
        />
      </a>
    )}
    
        <Card sectioned >
          <Text as="h2" variant="headingSm">
            Add WhatsApp Number
          </Text>
            <BlockStack gap="200">
              {/* <Image
                source="https://cdn.shopify.com/s/files/1/0592/3880/9793/files/whatsapp-svgrepo-com.png?v=1713350385"
                alt="WhatsApp Icon"
                width="75px"
              /> */}
              <TextField
                value={whatsappNumber}
                onChange={(value) => setWhatsappNumber(value)}
                type="tel"
                placeholder="(123) 456 -7890"
                autoComplete="on"
                maxLength={10} gap="400"
              />
              
            </BlockStack>
            <BlockStack gap="200">
                  <LegacyStack >
      <RadioButton
        label="Bottom Left"
        checked={value === 'disabled'}
        id="disabled"
        name="bottom"
        onChange={handleChange}
      />
      <RadioButton
        label="Bottom Right"
        id="optional"
        name="bottom"
        checked={value === 'optional'}
        onChange={handleChange}
      />
    </LegacyStack>
            </BlockStack>
        </Card>
      
    </Page>
  );
}

Could not load content for webpack://SwaggerUIBundle/src/core/system.js” error in Swagger UI

While attempting to use Swagger UI to document a Laravel project with the URL http://localhost:8014/api/documentation, I encounter the following error in the browser console:

TypeError: Cannot destructure property 'type' of 'u' as it is undefined.
    at build-request.js:115:9
    at Array.forEach (<anonymous>)
    at build-request.js:107:30
    at Array.forEach (<anonymous>)
    at applySecurities (build-request.js:106:12)
    at buildRequest (build-request.js:16:9)
    at Object.execute_buildRequest [as buildRequest] (index.js:249:11)
    at actions.js:453:24
    at index.js:174:16
    at redux.mjs:331:12

Of course, with further investigation, I realized that the main error was:

Could not load content for webpack://SwaggerUIBundle/src/core/system.js (Fetch through target failed: Unsupported URL scheme; Fallback: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME)

This error only occurs for specific API endpoints, not all of them.

Additional Information:

  • I am using Laravel and Swagger UI in my project.
  • I can access the API documentation at http://localhost:8014/api/documentation.
  • I have carefully reviewed the API data structure, and it matches the Swagger documentation.
  • I am using compatible versions of Laravel and Swagger UI.
  • I have cleared the Swagger cache and regenerated the
    documentation.

What could be causing this error, and how can I resolve it?

Prime React Menubar not behaving correctly on small screen

Im trying to use MenuBar component from Prime React library, but for some reason, the menubar button that triggers menu bar on small screen does not show, and menubar is showing automatically. this how it looks on my app:
enter image description here

and this is how it should look:
enter image description here

this is my layout/app.tsx:

import { MegaMenu } from "primereact/megamenu";
import MenuStart from "./components/menu-start";
import { useNavigate, useNavigation } from "react-router-dom";
import { useHasAccess } from "../hooks/role";
import { useEffect } from "react";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { Menubar } from "primereact/menubar";
interface iProps {
  children: JSX.Element | JSX.Element[];
}
export default function Layout({ children }: iProps) {
  const navigate = useNavigate();
  const { hasAccess } = useHasAccess(["ROLE_CHEF"]);
  const items = [];
  NProgress.start();
  if (hasAccess)
    items.push(
      {
        label: "Demandes",
        icon: "pi pi-folder",

        command: () => {
          navigate("/demandes");
        },
      },
      {
        label: "Organizations",
        icon: "pi pi-building",
        command: () => {
          navigate("/organizations");
        },
      }
    );
  useEffect(() => {
    NProgress.done();
  });
  return (
    <div className="p-4">
      <Menubar start={MenuStart} model={items}/>
      {children}
    </div>
  );
}

Btw im using tailwind with prime react,It might be related with the problem so this is my index.css:

@layer tailwind-base, primereact, tailwind-utilities;

/* IMPORTANT: In "styled" mode you must add the PrimeReact Theme here. Do NOT include in "unstyled" mode */
@import "primereact/resources/themes/lara-light-blue/theme.css"
  layer(primereact);

@layer tailwind-base {
  @tailwind base;
}

@layer tailwind-utilities {
  @tailwind components;
  @tailwind utilities;
}

I want to mention that I tried MegaMenu component and it works perfectly fine, the secend screenshot is from it.