Promise {} of bcrypt inside promise

I have a lambda function that is connected to Mongo via mongoose. The user inputs a name and password on the frontend and the lambda function searches whether the user exists and afterwards the crypted password is compared via bcrypt.

Right now bcrypt gives me {<promise pending>}, when I console.log(match).

However, I can’t simply add an await as the check is inside a promise.

require("dotenv").config();
const mongoose = require("mongoose");
const User = require('../server/models/user');
const bcrypt = require('bcryptjs')

exports.handler = async (event, context) => {
  context.callbackWaitsForEmptyEventLoop = false;
  
  mongoose.connect(`${process.env.MONGO_URI}`,{
    useNewUrlParser: true,
    useUnifiedTopology: true,
  }
  );
  
  let {name, password} = JSON.parse(event.body);

 let fd = await new Promise((res,rej)=>User.findOne(
    {
      name:name,
    },
    (err, user) => {
      if (err) {
        rej({
          statusCode: 500,
          body: JSON.stringify({ msg: err.message }),
        });
      } else {
    //==>    const match = await bcrypt.compare(password, JSON.stringify(user.password)); 

 
        if (match) {
        let statusCode = user && match? 200:405
        res({
          statusCode,
          headers: {
            "Access-Control-Allow-Origin": "*", 
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ user}),
        });
      }
      }
    }
  ));
  return fd
};

So basically how can I ‘await’ bcrypt in that case or how could I write this function in another way? Thanks for reading!

Supabase and Axios(patch): index row size 3040 exceeds btree version 4

I’m having this trouble while sending a patch request from axios to supabase (nextjs application):

{
    "message": "index row size 3040 exceeds btree version 4 maximum 2704 for index "guests_list_qr_code_url_key"",
    "code": "54000",
    "details": "Index row references tuple (1130,6) in relation "guests_lists".",
    "hint": "Values larger than 1/3 of a buffer page cannot be indexed.nConsider a function index of an MD5 hash of the value, or use full text indexing."
}

I’m just updating a qr_code field sending a very short data:image in the body, and is throwing me that error.

body object

{
    "qr_code": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJQAAACUCAYAAAB1PADUAAAAAXNSR0IArs4c6QAACINJREFUeF7tndGS4kgMBIf//+jZuHs6mzgykpIwsDWvaqvVpZS6bTNw+/39/f3pXxUYUuBWoIaUrJt/FShQBWFUgQI1KmedFagyMKpAg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/knvQgo6mg2Xozn1e/yKKAC5T5RWaAkUVTB1k7T24qm+Wm+6etpi0vnw/W0Qx0lKlCEzGP7+GMDSgiFS9eTnSrUbql2fLoFkT5kJ32mz0zrd3m0oGlBbAItIHa8jYfGk15UQNtbXIE6KWAFp/EESFpwBBj5b4da/u4EAqQdihA+2r/+DEVyUEVPbykWYIrf2m0H1f637/JoAWnCrH87nx1PW0qBAkRJIJtw6hhktxVl/dH4AkUKFKiDAgXqL38ORR3L1hN1ZJqP7Laj2y2ZxlN8ZO+hPPwWYAskJmT4uxAI0PH4eyjPXsaOJ6RA3dQZgyrUnlGoAu18NL5b3sVnKEoQ2bcTaB9cUrzWTgVBBWbPRNt6rp+hrMDvluDpLY3WR4BYAGm+6fUVqJPi2xVMCS5Q8ut8bMe6OsHTFVyg5INNC4wdT2cKCwABS1uMjZ86EPmjeAlYqw/Fczff9GMDG4AdX6Ae31UXKElUgSpQEpnHwwvUlwM1SkudfbwC8WODj1egCxhVoECNyllnBaoMjCpQoEblrLMCVQZGFShQo3LWWYEqA6MKFKhROeusQJWBUQUK1KicdVagysCoAgVqVM46K1BlYFSBAjUqZ50VqDIwqsAfHleq+XgI30IAAAAASUVORK5CYII="
}

I did the same process using the supabase-js library in another project (website), and it works good.

Need some clues.

Toggle Button Pixi JS

i’m new in JS and learning Pixi JS
i have no idea about toggle button in my little project. got dead end
i want to do some click button ‘Mute’ and the function is mute also change to icon mute, when i click this mute button, the icon will change back to unmute icon

here my some script

let’s call this “ButtonView”

import { GlowFilter } from "pixi-filters";
import { Timeline } from "gsap/gsap-core";

export default class ButtonView extends PIXI.Container {
    constructor(options) {
        super()
        this.name = options.name || 'button'
        this.text = options.text || 'button'
        this.action = options.action || this.noAction

        this.timeLine = new Timeline()
        this.outlineFilter = new GlowFilter({ outerStrength: 0, color: 0xffffff, distance: 20 })
        this.filters = [this.outlineFilter]

        this.setInteractive(true)
        this.on('click', this.action)
        this.on('tap', this.action)
        this.on('pointerup', this.pointerUp)
        this.on('pointerdown', this.pointerDown)
        this.on('pointerover', this.pointerOver)
        this.on('pointerout', this.pointerOut)
    }

    setInteractive(bool) {
        this.interactive = bool
        this.buttonMode = bool
    }

    pointerUp() {
        this.scale.set(1)
    }

    pointerDown() {
        this.scale.set(0.95)
    }

    pointerOver() {
        this.timeLine.clear()
        this.timeLine.to(this.outlineFilter, .3, { outerStrength: 2 })
    }

    pointerOut() {
        this.timeLine.clear()
        this.timeLine.to(this.outlineFilter, .3, { outerStrength: 0 })
    }

    enable() {
        this.setInteractive(true)
    }

    disable() {
        this.setInteractive(false)
    }

    noAction() {
        console.log('ButtonView no action')
    }
}

and this “MuteView”

import ButtonView from "./ButtonView"

export default class MuteView extends ButtonView {
    constructor(options) {
        super(options)
        this.header = new PIXI.Text('mute', { fill: 0xeeeeee, fontSize: 20 })
        this.muted = new PIXI.Text(options.muted, { fill: 0xffffff, fontSize: 40, fontWeight: 'bold' })
        this.addChild(this.header, this.muted)
        this.create()
    }

    create() {
        const btnMute = new PIXI.Sprite('./images/mute_box.png')
        btnMute.anchor.set(0.5)

        this.btnSprite = new PIXI.Sprite('./images/unmute_icon.png')
        this.btnSprite.position.set(
            btnMute.width / 2 - this.btnSprite.width / 2,
            btnMute.height / 2 - this.btnSprite.height / 2
        )
        this.btnSprite.anchor.set(0.5)

        const back = new PIXI.Graphics()
        back.drawRect(0, 0, btnMute.width, btnMute.height)
        back.pivot.set(mute.width / 2)

        this.btn = new PIXI.Container()
        this.btn.addChild(btnMute, this.btnSprite)
        this.addChild(back, this.btn)
    }

    pointerUp() {
        this.btn.scale.set(1)
    }

    pointerDown() {
        this.btn.scale.set(0.95)
    }

    enable() {
        super.enable()
        this.spriteChange('./images/unmute_icon.png')
    }

    disable() {
        super.disable()
        this.spriteChange('./images/mute_icon.png')
    }

    spriteChange(texture) {
        this.btnSprite.texture = texture
    }
}

Echarts Apache – draggable div

I need to implement the drag function for the echarts.

HTML CODE:

<div class="maindash">
    <div class="cardchart" id="barchart" ></div>
    <div class="cardchart"  id="piechart" ></div>
    <div class="cardchart"  id="areachart" ></div>
    <div class="cardchart"  id="baranimchart" ></div>
</div>

<style>
    .maindash {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-evenly;
        flex-grow: 0;
        margin: 10px;
        gap: 5px;
        overflow: auto;
        height: 100%;
    }

    .cardchart {
        box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
        margin:13px;
        width: 400px; 
        height: 300px;
        background-color: #fff;
    }
</style>

JS CODE:

function dragndrop() {
                    $( ".cardchart" ).sortable({
                        revert: true
                      });

            }

For some reason I can drag only the chart and not the div. I have selected (.cardchart) but it continues to drag only the chart. Me I want to drag the complete div.

enter image description here

Find an alternative to split when processing a lot of data

I am mapping through the object in order to return an array of object. However I want to modify the “model-1111” from a string to an integer. This method works with a split, however I would like to find an alternative to split, because split will return an array, which is not the best when processing a lot of data.

  const data = {"model-10389": 164703,  "model-10388": 164704,  "model-10387": 164705};

  const output = Object.entries(data).map(([key, id]) => ({
  modelId: +key.split("-").pop(),
  id
  }));

 console.log(output);

Call javascriptfunction on the server from the locationManager function

I am in the process of creating a web application. The application is a kind of map and therefore I need to retrieve the location of the user. On the Bottom of this code there is the function LocationManeger. This function determines the coordinates of the user. These coordinates should be passed on to the javascript function, but I don’t know how to do that. Does anyone know how to fix this?

Webview

//  WebView.swift
//  ferocity
//
//  Created by Jens Buwalda on 2022-06-17.
//

import Foundation
import SwiftUI
import WebKit
import CoreLocation

struct WebView : UIViewRepresentable {

    let url: URL
    var webView = WKWebView()
    var manager = LocationManagerService()
   
    func makeUIView(context: Context) -> WKWebView  {
        let request = URLRequest(url: url)
        webView.load(request)
        return webView
    }
    
    // AND IT HAS TO CALL THIS (OR UPDATE THE WEBVIEW)
    func updateLocation(lat:String, lon:String){
        webView.evaluateJavaScript("deviceLocation(" + lat + ", " + lon + ");")
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
        uiView.navigationDelegate = context.coordinator
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    //Conform to WKNavigationDelegate protocol here and declare its delegate
    class Coordinator: NSObject, WKNavigationDelegate {
        var parent: WebView

        init(_ parent: WebView) {
            self.parent = parent
        }

        func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
            // Check if there is a token in the url
            let token = getQueryStringParameter(url: navigationAction.request.url!.absoluteString, param: "token")
            // Save token if available
            let defaults = UserDefaults.standard
            if token != nil{
                defaults.set(token, forKey: "token")
            }
            
            // Check if a token is present in storage
            if let memoryToken = defaults.string(forKey: "token") {
                print("Memory token: " + memoryToken)
                // Add token to new url
                let reloadUrl = insertQueryItems(url: navigationAction.request.url!.absoluteString, key: "token", value: memoryToken)!
                print("Reload url: " + reloadUrl.absoluteString)
                // Check if the url id different from the current url
                if navigationAction.request.url?.absoluteString != reloadUrl.absoluteString{
                    print("Reload")
                    webView.load(URLRequest(url: reloadUrl))
                }
            } else {
                print("No token in memory")
            }

            
            //Change padding on login page
            if ((navigationAction.request.url?.absoluteString.contains("sso")) != false){
                // TODO: add padding to top
                // self.parent.padding(      )
            } else {
                // Remove the padding
            }
            decisionHandler(.allow)
        }
        
        func getQueryStringParameter(url: String, param: String) -> String? {
          guard let url = URLComponents(string: url) else { return nil }
          return url.queryItems?.first(where: { $0.name == param })?.value
        }
        
        func insertQueryItems(url: String, key: String, value: String) -> URL?{
            var urlObject = URLComponents(string: url)
            var urlComponents = urlObject?.queryItems
            if(urlComponents == nil){
                urlComponents = []
            }
            urlComponents?.removeAll(where: { $0.name == key })
            urlComponents?.append(URLQueryItem(name: key, value: value))
            urlObject?.queryItems = urlComponents
            return urlObject?.url
        
        }
    }
}

class LocationManagerService: NSObject, ObservableObject, CLLocationManagerDelegate {
    var manager: CLLocationManager = CLLocationManager()
    @Published var location: CLLocation?
    @Published var enabled: Bool = false
    
    override init() {
        super.init()
        manager.delegate = self
        
        if CLLocationManager.locationServicesEnabled() {
            manager.requestWhenInUseAuthorization()
            manager.startUpdatingLocation()
        }
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        print("location changed")
        guard let coordinate = locations.last?.coordinate else { return }
        let user_lat = String(format: "%f", coordinate.latitude)
        let user_long = String(format: "%f", coordinate.longitude)
        print(user_lat)
        print(user_long)
           //HERE THE JAVASCRIPTFUNCTION OF THE WEBSERVER SHOULD BE CALLED
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error)
    }
    
    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        enabled = CLLocationManager.locationServicesEnabled()
    }
}
'''

Why disabled button is still clickable in antd?

My component looks like this

...some jsx
<Button onClick={onSaveChanges} disabled={isSaveDisabled}>
  Save
</Button>

I am still somehow able to trigger onSaveChanges function even when isSaveDisabled is true, also hardcoded true to disabled but no luck. Do i have to do something like this ?

disabled={!isSaveDisabled && onSaveChanges}

?

Text not changing when using .innerHTML and var

var name = document.firstElementChild.lastElementChild.lastElementChild.lastElementChild;
name.innerHTML = "XYZ";
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>My Website</title>
  <link rel="stylesheet" href="styles.css">

</head>

<body>

  <h1>Hello</h1>

  <input type="checkbox">

  <button style=":active color:red;">Click Me</button>

  <ul>
    <li class="list">
      <a href="https://www.google.com">Google</a>
    </li>
    <li class="list">Second</li>
    <li class="list">Third</li>
  </ul>

</body>

</html>

So, this is the code for a website, and I wanted to change the text of the last element of the document – “Third” changes to “XYZ”.

When I use the following code, the text does not change.

var name=document.firstElementChild.lastElementChild.lastElementChild.lastElementChild;
name.innerHTML="XYZ";

However, when I use this:

document.firstElementChild.lastElementChild.lastElementChild.lastElementChild.innerHTML="XYZ";

The text on the website, immediately changes. Why is this happening? All I have done is just split the code in two lines instead of writing it in one.

Why a simple `useEffect` is not taking updated value when it is warping any “setInterval/timeout” inside

Why a simple useEffect is not taking updated value when it is warping any setInterval/timeout inside;

https://codesandbox.io/s/gracious-cerf-4183y0?file=/src/StopWatch.js
where variable stopped to initial value;

import { useState, useEffect } from "react";
let timerRef;
const StopWatch = () => {
    const [time, setTime] = useState(0);
    const [isPause, setPause] = useState(false);
    useEffect(() => {
        let _time = time;
        console.log({ time });
        timerRef = setInterval(() => {
            console.log({ _time });
            if (!isPause) {
                setTime(_time + 1);
            }
        }, 5000);
        return () => clearInterval(timerRef);
    }, []);
    const startWatch = () => {
        setPause(false);
    };
    const stopWatch = () => {
        setPause(true);
    };
    return (
        <>
            time: {time}
            <button onClick={startWatch}>Start</button>
            <button onClick={stopWatch}>stop</button>
        </>
    );
};

output

Data from my react front end not getting to mysql database

I have a react front-end, node server, and MySQL database. I’m making use of express server and Axios for my post request. The code doesn’t appear to have an error, also in the console and network in chrome. However, no data gets to my database. I’ll really appreciate the help. Here are my codes;

Client

import React, { useState } from 'react';
import './register.css';
import {Link} from 'react-router-dom';
import Image from '../../assets/Image.png';
import Axios from 'axios';

const Register = () => {

  const [uploadReq, setUploadReq] = useState('')
  const [usernameReq, setUsernameReq] = useState('')
  const [fullnameReq, setFullnameReq] = useState('')
  const [emailReq, setEmailReq] = useState('')
  const [passwordReq, setPasswordReq] = useState('')

  const registration = () => {
    Axios.post("http://localhost3000/register",{
      upload: uploadReq,  
      username: usernameReq,
      fullname: fullnameReq,
      email: emailReq,
      password: passwordReq,
    }).then((response) => {
     console.log(response);
    });

  };

  return (
    <div className='register section__padding'>
      <div className="register-container">
        <h1>register</h1>
        <p className='upload-file'>Upload Profile pic</p>
        <div className="upload-img-show">
          <img src={Image} alt="banner" />
          <p>browse media on your device</p>
        </div>
        <form className='register-writeForm' autoComplete='off' >
          <div className="register-formGroup">
            <label>Upload</label>
            <input type="file" className='custom-file-input'
             onChange={(e) => {
              setUploadReq(e.target.value);  
            }}
          />
          </div>
          <div className="register-formGroup">
            <label>Full Name</label>
            <input type="text" placeholder='Name' 
            onChange={(e) => {
            setFullnameReq(e.target.value);  
          }}
            />
          </div>
          <div className="register-formGroup">
            <label>Username</label>
            <input type="text" onChange={(e) => {
              setUsernameReq(e.target.value);  
            }}placeholder='Username'  />
          </div>
          <div className="register-formGroup">
            <label>Email</label>
            <input type="email" placeholder='Email' 
            onChange={(e) => {
            setEmailReq(e.target.value);  
            }}
            />
          </div>
          <div className="register-formGroup">
            <label>Password</label>
            <input type="text" onChange={(e) => {
              setPasswordReq(e.target.value);  
            }} placeholder='Password'   />
          </div>
         <div className="register-button">
          <button className='register-writeButton' onClick={registration}>register</button>
          <Link to="/login">
            <button className='reg-login-writeButton' >Login</button>
          </Link>
         </div>
        </form>
      </div>
    </div>
   )
};

export default Register;

Server

const express = require("express");
const app = express();
const mysql = require("mysql");
const cors = require("cors"); 

app.use(express.json());
app.use(cors());

const db = mysql.createPool({
    
    host: "localhost",
    user: "root",
    password: "xyz",
    database: "nftdatabase",
 });

 app.post('/register', (req, res) => {

    const upload = req.body.upload
    const Fullname = req.body.fullname
    const Username = req.body.username
    const Email = req.body.email
    const Password = req.body.password

    db.query("INSERT INTO user (upload, fullname, username, email, password) VALUES (?,?,?,?,?)", 
    [upload, Fullname, Username, Email, Password],
    (err, result) => {
        console.log(err);
    });

 });

app.listen(3001, () => {

    console.log("running on port 3001");
});

loop throught an object and return a array of object

How can I loop over this object(data) and return a an array of object (output) just like this. basically with these specific properties and value

data = {
"model-10389": 164703,
"model-10388": 164704,
"model-10387": 164705,
}


const output  = [
{
  modelId : 10389,
 id : 164703
},
{
  modelId : 10388,
  id : 164704
},
{
  modelId : 10387,
  id : 164705
},
]

mock apollo client function written in node not working with jest

I have written following code to get data from GraphQL data service using apollo-boost.

import ApolloClient, { gql, InMemoryCache } from 'apollo-boost';
import * as CONSTANTS from '../constants/campaign-constants';
import fetch from 'node-fetch';

const apiEndpoint = process.env.CAMPAIN_SERVICES_GRAPHQL_ENDPOINT;

export class CampaignGQDAL {

private readonly campaignUtils: CampaignUtils = new CampaignUtils();
private client: ApolloClient<InMemoryCache> = new ApolloClient({
    uri: apiEndpoint,
    fetch: fetch as any
});


/**
 * 
 * @param vin string
 * @returns 
 */
public async getCampaignsForVin(vin: string, token: string): Promise<any> {
    this.client = new ApolloClient({
        uri: apiEndpoint,
        fetch: fetch as any,
        headers: {
            Authorization: token
        }
    });
    
    return this.client.query({
        query: this.GET_CAMPAIGNS_FOR_VIN_QUERY,
        variables: {
            vin
        }
    }).then(result => {
        return result.data.getCampaignsByVin.items;
    }).catch((err) => {
        Logger.info(`error in getting getCampaignsForVin : ${JSON.stringify(err)}`);
        throw this.campaignUtils.populateError(CONSTANTS.ERROR_CODE_500, CONSTANTS.ERRORS.INTERNALSERVERERROR);
    });
}

public GET_CAMPAIGNS_FOR_VIN_QUERY = gql`
    query getCampaignsByVin($vin: String!){
        getCampaignsByVin(vin: $vin) {
            items {
                vin
                SK_campaignId
                completionCode
            }
        }
    }
`;
}

I have tried to write and execute the following unit test case for above code using Jest and mock-apollo-client but it’s not working. Not resolving the provided mock input “mockcampaignsForVIN” Instead of it is hitting real graphQL server. Also do i need to provide real graphQL uri and access token for mockClient ?

import { createMockClient } from 'mock-apollo-client';
import { CampaignGQDAL } from "../../../src/dal/campaign-graphql";

const mockcampaignsForVIN = {
completionCode: "123",
SK_campaignId: 'US_0010'
};

const mockClient = createMockClient();
const campaignGQDAL: CampaignGQDAL = new CampaignGQDAL();

describe('api', () => {
describe('campaigns', () => {
describe('Given a valid campaigns for vin', () => {
  beforeEach(() => {
    jest.resetModules();
  });
  it('Should call query with the vin as a param', async () => {
    jest.doMock('@apollo/client', () => {
      return {
        ...jest.requireActual('@apollo/client'),
        ApolloClient: jest.fn(() => mockClient),
      };
    });
    const queryHandler = jest.fn().mockResolvedValue({ data: { getCampaignsByVin: 
    mockcampaignsForVIN } });
    mockClient.setRequestHandler(campaignGQDAL.GET_CAMPAIGNS_FOR_VIN_QUERY, queryHandler);
    const vin = "123"; // JTEBU5JR8G5353402
    const token = "is it okay to provide dummy token for mockClient ?";
    const result = await campaignGQDAL.getCampaignsForVin(vin,token);
    console.log(result);
    expect(result).toEqual(mockcampaignsForVIN);
    expect(queryHandler).toHaveBeenCalledTimes(2);
  });
  });
  });
  });

Appium unable to locate iOS elements

I am not sure if this is a known issue or just something i’m having with my app.

The issue is that the app i want to write tests for is showing unable to interact with the element for almost all the elements that behind multiple layers and i checked my app it looks like its layered heavily.

what are the solutions to elements that are so far hidden behind layered design?

Do we use for loops to filter through ? what exactly would be recommended

Please if you could advice with examples that would be great

I’m using Appium+webdriverio Javascript

Thank you