PHP multiple Object creation from DB

Hi I am very new to PHP and Objects and have become very confused on the best way to create a collection of objects created from a database. Below is an example of what is working for me but its a single object with array properties. Is this the best options or do I create multiple objects for each book and if I create multiple objects how do I loop through to display on my grid.

<?php
declare(strict_types=1); // FAIL FAST
//##############################################
class Books {
// Properties
    protected $id_type=array();
    protected $title=array();
    protected $brief=array();
//==============================================    
function set_books($id, $mysqli)
    {
        //DB Query 
        $result = $stm->get_result();
        $stm->close();

        while ($rows = $result->fetch_assoc()) {
        $this-title[] = $rows['title'];
        $this->brief[] = $rows['brief'];
        }
    }
//==============================================
function get_title()
    {
        return $this->title;
    }
//==============================================
}
$books = new Books();
$books->set_books(4, $mysqli);
$book_count = count($books->get_title());
$i=0;
while ($i < $book_count) {
    
echo "<h1>".$books->get_title()[$i]."</h1>";    

$i++;
}
?>

I have google and cannot find the exact answer I am looking for most examples show a single object like displaying a single book not a list of books.

Making an Enigma Machine in React

I am making the plugboard functionality for an enigma machine in React. I currently have a keyboard layout displayed on the screen (a, b, c, d, …) not qwerty. Regardless, my idea was that a user could hold the control key to activate the plugboard functionality, then click on a letter (or key) to connect a plug there, then the next click, while still holding the control key, would connect the other end of the plug. These plug connections would be shown through color coding, changing the background color of the key of the two connected letters. When an already active key was clicked, it and its connected key, would be deactivated. The issues I’ve run into are limiting the amount of connections to only two letters. Here is my code so far…

import { useState, useContext } from "react";

const colors = [
    "#FF69B480",
    "#66330080",
    "#FFC10780",
    "#8E24AA80",
    "#00BFFF80",
    "#3B3F5480",
    "#FF980080",
    "#0097A780",
    "#E91E6380",
    "#F7DC6F80",
    "#4B008280",
    "#32CD3280",
    "#7081f080",
];

const Letter = ({ letter, ctrlPressed, setCtrlPressed }) => {
    const [activeConnections, setActiveConnections] = useState({});
    const [currentColorIndex, setCurrentColorIndex] = useState(0);
    const [clickCount, setClickCount] = useState(0);

    const handleClick = () => {
        if (ctrlPressed) {
            if (activeConnections[letter]) {
                // Deactivate the connection
                const connectedLetter = Object.keys(activeConnections).find(
                    (key) =>
                        activeConnections[key] === activeConnections[letter] &&
                        key !== letter
                );
                setActiveConnections((prevConnections) => {
                    const newConnections = { ...prevConnections };
                    delete newConnections[letter];
                    delete newConnections[connectedLetter];
                    return newConnections;
                });
            } else {
                // Activate a new connection
                const currentColor =
                    colors[Math.floor(clickCount / 2) % colors.length];
                setActiveConnections((prevConnections) => ({
                    ...prevConnections,
                    [letter]: currentColor,
                }));
                setClickCount(clickCount + 1);
            }
        }
    };

    return (
        <span
            className='letter'
            style={{
                backgroundColor: activeConnections[letter] || "#444",
            }}
            onClick={handleClick}
        >
            {letter}
        </span>
    );
};

export default Letter;

I’ve had ideas that maybe left click for activation and right click for deactivation, or left for one end of the plug and right click for the other end of the plug? Not sure that that quite solves all of my current issues.

FYI: the ctrlPressed state is global and being used as a prop from the parent App component (yes, I know it is not performance best practice, but easy for a personal development project). My array of letters is also being generated and imported from the parent Keyboard component.

App with plugboard toggled OFF

App with plugboard toggled ON

Is there any way to execute simple JavaScript expressions in Java 21 without any manual installations?

For example, I have version 21 installed and as far as I understand, I can’t use Nashorn engine anymore.

But maybe GraalVM is available for me?

I have installed all the necessary dependencies:

    <dependency>
        <groupId>org.graalvm.js</groupId>
        <artifactId>js</artifactId>
        <version>21.1.0</version>
    </dependency>
    <dependency>
        <groupId>org.graalvm.js</groupId>
        <artifactId>js-scriptengine</artifactId>
        <version>21.1.0</version>
    </dependency>

And here’s a simple example that I’m trying to execute:

public static void main(String[] args) throws ScriptException {
    try (Context context = Context.newBuilder("js")
            .allowAllAccess(true)
            .build()) {
        // Evaluate JavaScript code
        String jsCode = "console.log('Hello, GraalVM!');";
        context.eval("js", jsCode);
    } catch (Exception e) {
        throw new ScriptException("Script execution failed: " + e.getMessage());
    }
}

However, I get an error:

Exception in thread “main” javax.script.ScriptException: Script
execution failed: A language with id ‘js’ is not installed. Installed
languages are: []. at org.example.Main.main(Main.java:23)

I also tried something like this:

public static void main(String[] args) throws ScriptException {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine  = manager.getEngineByName("JavaScript");
    engine.eval("print('HI');");
}

But I got another error:

Exception in thread “main” java.lang.NullPointerException: Cannot
invoke “javax.script.ScriptEngine.eval(String)” because “engine” is
null at org.example.Main.main(Main.java:20)

The problem is that manual installation of any components is impossible for some reason. I just need to some dependencies and make everything works. Something “out of the box”. Is there any workaround for this problem? Maybe there are any other available engines?

Thanks everyone.

Why doesn’t web3 gun library work well together with Angular v18.2?

I’m trying to incorporate gun web3 library into my Angular app, but I’m running into the following error:

[vite] Internal server error: Cannot find module ‘./lib/text-encoding’
Require stack:

I’m using Angular v18.2 so Vite is incorporated into the pipeline, but it is not included in package.json nor the tsconfig.json nor the angular.json.

Everyting seemed to work fine until I decided to move my login logic into seperate component from the main app.component.ts

async ConnectMetaMask(){
    await this.MetaMaskSDK.request({ method: 'eth_requestAccounts' }).then((accounts : any) => {    
      this.UserAccount = accounts[0];
    });

    if(this.UserAccount != null){
      const gun = Gun();
      this.accountConnected = true;

      gun.get(`~@${this.UserAccount + "STF"}`).once(data => {
        console.log(data);
        if (data) {
          this.loginNeeded = true;
        } else {
          this.registerNeeded = true;
        }
      });
    }
  }

  async Login(){
    const gun = Gun();
    const user = gun.user();
    const SEA = Gun.SEA;
    
    if(this.loginNeeded){
      user.auth(this.UserAccount + "STF", this.myForm.get('password')?.value, (ack) =>{
        if ('err' in ack) {
          // Niepoprawne hasło
        } else {
          console.log("zalogowano");
          this.loggeduserData.loggedUserWalletAddress = this.UserAccount;
          this.loggeduserData.loggedUserWalletAddressSTF = this.UserAccount + "STF";
          this.routerAN.navigate(['/dashboard']);
        }
      });
    }
    else{
      user.create(this.UserAccount + "STF", this.myForm.get('password')?.value, ack => {
        if (ack) {
          console.log('Error:', ack);
        } else {
          console.log('User created successfully:', ack);
        }
      });
    }
  }

I generated a new component, moved my logic there and the error popped. These are my imports from the new component with login:

import { Component, OnInit } from '@angular/core';
import { PinataSDK } from "pinata-web3";
import { Router, RouterLink, RouterModule, RouterOutlet } from '@angular/router';
import { CommonModule } from '@angular/common';
import { FormBuilder, FormControl, FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MetaMaskSDK } from "@metamask/sdk";
import Gun from 'gun';
import 'gun/sea';
import { LoggedUserDataService } from '../../../resources/LoggedUserDataService/logged-user-data.service';
import { env } from '../../../env';

Developer seems to give a sort of solution to this problem (https://gun.eco/docs/Vite), but it requires a change too be made inside
vite.config.js which is not available in Angular v18.2.

I would appreciate any help

Scrapping an image from webview and return it as base64

I am trying to convert an image img/tab_25/05/38/37/bl1005194/chapter_1/1-1728176695-o.webp from a webview to base64.

The issue is that the image is protected So I am unable to fetch the image on the serverside.

So I thought about injecting the fetching and converting code to the webview, I thought that as it is from the same orgin I wont get an issue downloading it and converting it to base64.

Here is that code I am using

const getImage = async function (img) {
     let src = img.getAttribute("src")
       return new Promise(
        async (onSuccess, onError) => {
          try {
            const response = await fetch(src, {
              mode: 'no-cors',
              referer:"https://chapmanganato.to/",
              accept: "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8",
              "accept-encoding":"gzip, deflate, br, zstd",
              "user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
            });
            const blob = await response.blob();
            const reader = new FileReader();
            reader.onerror = function (e) {
              console.error(e);
              alert(e)
              onSuccess("");
            }
            reader.onload = function () {
              if (reader.result)
                onSuccess("data:image/jpg;base64,"+reader.result.toString().split(",")[1]);
              else onSuccess("");
            };
            reader.readAsDataURL(blob);
          } catch (e) {
            console.error(e);
            alert(e)
            onSuccess("");
          }
        }
      );
    }

    const getImages = async function () {
        try{
        let imgArray = [];
        let imgs = [...document.querySelectorAll("${parser?.selector}")];
        for (let img of imgs) {
            let src = await getImage(img);
            if (src && src.length>10)
            imgArray.push(src)
        }

        var payload = {
            name: "images",
            url: "${currentUrl}",
            data: imgArray
        };
        window.ReactNativeWebView.postMessage(JSON.stringify(payload));
    }catch(e) {alert(e)}
    }

The above code return data:image/jpg;base64, as result will be empty.

I am assuming that the issue is with .webp

Here is the site I am trying to scrap images from https://manganato.com/

And for those that want a repredusable code, it is not possible as this code has to be run from inside a webview so no need to ask.

Here is the whole react-native component


import WebView from "react-native-webview";
import { Html } from "../native";
import * as React from "react";

export default () => {
  const state = buildState({
    loading: context.parser.find(context.player.novel.parserName)?.protectedChapter == true
  }).build();

  const webview = useRef();

  context.useEffect(() => {
    processData();
  }, "player.currentChapter")

  useEffect(() => {
    processData();
  }, []);

  let parser = context.parser.find(
    context.player.book.parserName
  );

  let processData = () => {
    parser = context.parser.find(
      context.player.book.parserName
    );
    if (context.parser.find(context.player.novel.parserName)?.protectedChapter != true)
      return;


    if (parser?.protectedChapter !== true || state.loading)
      return;

    if (context.player.currentChapter?.content?.has()) {
      return;
    }

    state.loading = true;
  }
  let currentUrl = context.player.currentChapter?.url;

  const script = `
       try {
    const getImage = async function (img) {
     let src = img.getAttribute("src")
       return new Promise(
        async (onSuccess, onError) => {
          try {
            const response = await fetch(src, {
              mode: 'no-cors',
              referer:"https://chapmanganato.to/",
              accept: "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8",
              "accept-encoding":"gzip, deflate, br, zstd",
              "user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
            });
            const blob = await response.blob();
            const reader = new FileReader();
            reader.onerror = function (e) {
              console.error(e);
              alert(e)
              onSuccess("");
            }
            reader.onload = function () {
              if (reader.result)
                onSuccess("data:image/jpg;base64,"+reader.result);
              else onSuccess("");
            };
            reader.readAsDataURL(blob);
          } catch (e) {
            console.error(e);
            alert(e)
            onSuccess("");
          }
        }
      );
    }

    const getImages = async function () {
        try{
        let imgArray = [];
        let imgs = [...document.querySelectorAll("${parser?.selector}")];
        for (let img of imgs) {
            let src = await getImage(img);
            if (src && src.length>10)
            imgArray.push(src)
        }

        var payload = {
            name: "images",
            url: "${currentUrl}",
            data: imgArray
        };
        window.ReactNativeWebView.postMessage(JSON.stringify(payload));
    }catch(e) {alert(e)}
    }
    
    const getHtml = async function () {
        var payload = {
            name: "html",
            url: "${currentUrl}",
            data: document.querySelector("${parser?.selector}").outerHTML
        };
        window.ReactNativeWebView.postMessage(JSON.stringify(payload));

    }

    const parse = function () {
        if ("${parser.type}" == "Manga")
           getImages();  
        else  getHtml();
    }
    
    if (document.readyState === "loading") {
        document.addEventListener("DOMContentLoaded", (event) => {
            parse();
        });
    } else {
        parse()
    }
} catch (e) {
    alert(e)
}true;`;


  let web = (state.loading && context.parser.find(context.player.novel.parserName)?.protectedChapter == true ? (
    <WebView
      ref={(r) => webview.current = r}
      injectedJavaScript={script}
      nestedScrollEnabled={true}
      cacheEnabled={true}
      source={{
        uri: currentUrl,
        baseUrl: ""
      }}
      onMessage={async ({ nativeEvent }) => {
        let data = JSON.parse(nativeEvent.data);

        //console.warn(data.url, currentUrl)
        if (data.name === "images") {
          console.log(data.data[0])
          data.data = data.data.map(x => `<img src="${x}" />`).join("n");

        }
        if (currentUrl === data.url) {
          context.player.currentChapter.content = data.data;
          //console.warn(context.player.novel.type)
          await context.player.getChapterContent("hhvh");

          state.loading = false;
        }
      }}
      contentMode="mobile"
      scalesPageToFit={true}
      originWhitelist={["*"]}
      scrollEnabled={true}
      userAgent="Mozilla/5.0 (Linux; Android 4.1.1; Galaxy Nexus Build/JRO03C) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19"
      setSupportMultipleWindows={false}
      style={[
        {
          flexGrow: 1,
          zIndex: 70,
          flex: 1
        }
      ]}
      allowFileAccess={true}
      allowFileAccessFromFileURLs={true}
      allowUniversalAccessFromFileURLs={
        true
      }
      javaScriptEnabled={true}
    />
  ) : null);

  return { loading: state.loading, web };
}

Why does my website keep redirecting me to the spotify authentication page?

Im using the spotify PKCE authentication for my website. However, no matter if I press agree or cancel, it just keeps redirecting back to the authentication page. I am trying to make a website that will recommend music based on certain criteria and play said music, should I even be using the PKCE authentication or a different one? I’m very new to this stuff.

const clientId = '';
const code = undefined;
if (!code) {
  redirectToAuthCodeFlow(clientId);
} else {
  const accessToken =  getAccessToken(clientId, code);
  const profile =  fetchProfile(accessToken);
  populateUI(profile);
}

async function redirectToAuthCodeFlow(clientId) {
  // TODO: Redirect to Spotify authorization page
  const verifier = generateCodeVerifier(128);
  const challenge = await generateCodeChallenge(verifier);

  localStorage.setItem("verifier", verifier);

  const params = new URLSearchParams();
  params.append("client_id", clientId);
  params.append("response_type", "code");
  params.append("redirect_uri", "http://127.0.0.1:3000/index.html");
  params.append("scope", "user-read-private user-read-email");
  params.append("code_challenge_method", "S256");
  params.append("code_challenge", challenge);

  document.location = `https://accounts.spotify.com/authorize?${params.toString()}`;
}

function generateCodeVerifier(length) {
  let text = '';
  let possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

  for (let i = 0; i < length; i++) {
      text += possible.charAt(Math.floor(Math.random() * possible.length));
  }
  return text;
}

async function generateCodeChallenge(codeVerifier) {
  const data = new TextEncoder().encode(codeVerifier);
  const digest = await window.crypto.subtle.digest('SHA-256', data);
  return btoa(String.fromCharCode.apply(null, [...new Uint8Array(digest)]))
      .replace(/+/g, '-')
      .replace(///g, '_')
      .replace(/=+$/, '');
}


async function getAccessToken(clientId, code) {
  // TODO: Get access token for code
  const verifier = localStorage.getItem("verifier");

    const params = new URLSearchParams();
    params.append("client_id", clientId);
    params.append("grant_type", "authorization_code");
    params.append("code", code);
    params.append("redirect_uri", "http://localhost:5173/callback");
    params.append("code_verifier", verifier);

    const result = await fetch("https://accounts.spotify.com/api/token", {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: params
    });

    const { access_token } = await result.json();
    return access_token;
    console.log(access_token);

}

Most of the code is copied from spotify’s website.

Read or count pages of a digital signed pdf document using php or javascript

I am trying to read a pdf which is digitally signed. I tried using different php libraries and also js libraries, each of them works well with a normal pdf document but if the document is digitally signed then it cant read it. Tried libraries mpdf, setassign/fpdi etc. I even tried to remove the digital signature and make a copy of it and then count the pages of the document using ghostscript but not working, but it can’t remove the sign, Is there any way around to do it ? any idea would be appreciated.

How to make trigger change work in Select2?

There is a piece of code that is responsible for updating the QR code during events [‘paste’, ‘keyup’, ‘change’], but for some reason the Select2 list does not work and accordingly, does not transmit data.

my part of code

let apply_reload_qr_code_event_listeners = () => {
        document.querySelectorAll('[data-reload-qr-code]').forEach(element => {
            let events = ['paste', 'keyup', 'change'];
            events.forEach(event_type => {
                element.removeEventListener(event_type, reload_qr_code_event_listener);
                element.addEventListener(event_type, reload_qr_code_event_listener);
            })
        });
    }

Even though data-reload-qr-code is added to input Select2, it does not work, but all other fields work without problems.

How to stop page theme FLASH in Next.JS 15 using Tailwind CSS and prevent hydration mismatch

Is it possible to implement a successful page theme initialisation without the common flash issue, and whilst also avoiding any hydration mismatch errors?

My solution so far has been to execute JavaScript before the full page renders, by using <script> in the <head> tag, to check the users localStorage, and then apply the theme.

This works perfectly, except I am getting a hydration error in the console. This is obviously because the localStorage can only be checked on the client side, so the server-rendered HTML and client-rendered HTML never match.

I’d just ignore this console error, but isn’t it true that a hydration mismatch indicates that React had to discard the server-rendered HTML and re-render the tree on the client? I’m not particularly happy with having to accept that for concern of performance degradation.

The only other solution there seems to be from my research is either to pass the users selected theme through cookies, which I’d rather less prefer as localStorage is more persistent – or to save the users preference server side, which seems a bit unnecessary all for the sake of avoiding a half second flash.

Is there really no way to do this using localStorage? My main question is more focused on avoiding this hydration issue. I’ve already got a solution that works, but I don’t want to avoid the hydration mismatch. The best I can come up with is setting a default Tailwind theme class such as light to the <html> tag. This way, I can eliminate half the issue by assuring the hydration error only occurs if the theme is dark, rather than there always being a mismatch. Would like to get the other half, but can’t logically think how to do it. Maybe there is some clever way?

Code below:

import type { Metadata } from "next";
import "./globals.css";
import NavBar from "./components/NavBar/NavBar";
import Footer from "./components/Footer/Footer";

export const metadata: Metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  const initTheme = `
  (function() {
    const theme = localStorage.getItem("theme") || "light";
    document.documentElement.classList.remove('light', 'dark');
    document.documentElement.classList.add(theme);})();
  `;
  return (
    <html lang="en" className="light">
      <head>
        <link rel="stylesheet" href="https://rsms.me/inter/inter.css" />
        <script dangerouslySetInnerHTML={{ __html: initTheme }} />
      </head>
      <body>
        <NavBar></NavBar>
        {children}
        <Footer></Footer>
      </body>
    </html>
  );
}

Javascript class, initialize with object & optional values

I have a few questions regarding the code below:

export class Person {
    constructor(obj = { id: 0, name: '', lastName: '', eyeColor: '', age: 0 }) {
        this.id = obj.id;
        this.name = obj.name;
        this.lastName = obj.lastName;
        this.eyeColor = obj.eyeColor;
        this.age = obj.age;
    }

    yearOfBirth() {
        return new Date().getFullYear() - this.age;
    }

    json() {
        return JSON.stringify(this);
    }
}

FWIW: I prefer to create an object using this syntax:

let newPerson = new Person(
  { 
    id: 0, 
    name: "Werner", 
    lastName: "Venter", 
    age: 37
  }
);

I really dislike this way:

let newPerson = new Person(0, "Werner", "Venter", 37);

It just reads easier for me when I have the parameter name with the value. Anyway, I digress…

  1. Is this the correct/accepted way to create an object class? I will be using it to receive data from an API that sends it in this format as JSON.
  2. How do I make a parameter optional? Mainly why I need this is that the ID value is not required when creating a new entry on the API, so I would prefer not to include the ID value when creating the object.
  3. Finally, do you have any opinion/advice on this approach?

Thank you in advance guys. Really appreciate this community.

Referencing Json files in Storyline 360

Storyline gives advice on how to add external Javascript to a course:
https://access.articulate.com/support/article/Articulate-Storyline-360-JavaScript-Best-Practices-and-Examples

By adding the following to the story.html file:

<script LANGUAGE="JavaScript1.2" SRC="/story_content/MyJavaScriptFunctions.js" TYPE="text/javascript"></script>

And then inserting the .js file into the story_content folder.

Is there a way to insert a .json file into story_content and have javascript reference it?

Error [ERR_REQUIRE_CYCLE_MODULE]: Cannot require() ES Module…but I’m not

Trying to run my node app, with node main.js, but getting this error: Error [ERR_REQUIRE_CYCLE_MODULE]: Cannot require() ES Module. I have also tried node --experimental-specifier-resolution=node main.js.

My main.js file imports things from './schema/index.js' using regular esm syntax, like: import { importName } from './schema/index.js'. I am not using require, so not sure why it’s accusing me of that.

Full error shown below.

What am I doing wrong here?

→ node main.js
node:internal/modules/esm/loader:315
        throw new ERR_REQUIRE_CYCLE_MODULE(message);
              ^

Error [ERR_REQUIRE_CYCLE_MODULE]: Cannot require() ES Module /path/to/app/schema/index.js in a cycle. (from /path/to/app/noop.js)
    at ModuleLoader.importSyncForRequire (node:internal/modules/esm/loader:315:15)
    at loadESMFromCJS (node:internal/modules/cjs/loader:1414:24)
    at Module._compile (node:internal/modules/cjs/loader:1547:5)
    at Object..js (node:internal/modules/cjs/loader:1677:16)
    at Module.load (node:internal/modules/cjs/loader:1318:32)
    at Function._load (node:internal/modules/cjs/loader:1128:12)
    at TracingChannel.traceSync (node:diagnostics_channel:322:14)
    at wrapModuleLoad (node:internal/modules/cjs/loader:219:24)
    at Module.require (node:internal/modules/cjs/loader:1340:12)
    at require (node:internal/modules/helpers:138:16) {
  code: 'ERR_REQUIRE_CYCLE_MODULE'
}

Node.js v22.12.0

PS. There is no file called noop.js, and I have no idea what that part means!! Has anyone seen this before?

package.json:

{
  "name": "writing-api-subgraph-storybook",
  "version": "0.0.1",
  "dependencies": {},
  "packageManager": "[email protected]",
  "module": "./main.js",
  "type": "module",
  "main": "./main.js"
}

How do you pass a bound method as a parameter in javascript?

I’m trying to pass a bound method to a function, but I can’t quite figure out the syntax. It seems like javascript wants to somehow differentiate between an unbound method and a bound method, but where the calling context changes that. (Most programming languages simply define a method as a bound class function).

What’s the syntax for passing a bound method to a function, and then calling that bound method in the new scope?

Here’s the relevant snippets

const mongoose = require('mongoose');
const caching = require('../lib/caching')

const Blog = mongoose.model('Blog');

// This is where I'm trying to pass a method to another function. I'm unclear of the syntax here
Blog.find = caching.makeCachable(Blog.find.bind(Blog), Blog)

module.exports = app => {
  app.get('/api/blogs', requireLogin, async (req, res) => {
    let blogs = await Blog.find({_user: req.user.id});
    return res.send(blogs);
  });

  // ... other routes
}

caching.js

const util = require('util');
const redis = require('redis');

const client = redis.createClient('redis://localhost:6379');
const asyncGet = util.promisify(client.get).bind(client);

const DEFAULT_CACHING = [
    'EX', 60 * 60 * 1,//caching expires after 4 hours
]

// This is where I take the method and pass it on to another function. I hope this just passes through
function makeCachable(method, thisObject) {
    console.log(method, thisObject, `${method.className}.${method.name}`);
    return cachedQuery.bind(method, `${thisObject.className}.${method.name}`);
}

async function cachedQuery(queryFunction, queryKey, queryParams=null, cacheConfig=DEFAULT_CACHING) {
    //check redis before executing queryFunction
    const redisKey = JSON.stringify([queryKey, queryParams]);
    const cacheValue = await asyncGet(redisKey);

    if(cacheValue) {
        return JSON.parse(cacheValue);
    }
    
    // This is where I try to call the bound method
    const blogs = await queryFunction.call(queryParams);
    
    if(blogs) {
        client.set(redisKey, JSON.stringify(blogs), ...cacheConfig);
    }

    return blogs;
}

exports.makeCachable = makeCachable;

Combine data from different cells in a table

I’m trying to read data stored in a csv file and present it in a table, using JavaScript. The csv data (comma delimited) is (I reduced it to be much smaller than the actual one):

Number, PDF1, PDF2, PDF3
0,,,
1,1.pdf,,
2,2a.pdf,2b.pdf,
3,3a.pdf,3b.pdf,3c.pdf

The correspondence between cells in the csv and online is 1 to 1, except 3 last columns (PDF1/2/3). I need them to appear online in the same cell (for each row) as links, separated by space. That is, instead of 3 columns PDF1/2/3 there will be just one, called PDF, containing links to pdfs 1, 2 and 3, if present. The desired output is:

| Number | PDF                                      |
| 0      |                                          |
| 1      | [link>1.pdf]                             |
| 2      | [link>2a.pdf] [link>2b.pdf]              |
| 3      | [link>3a.pdf] [link>3b.pdf] [link>3c.pdf]|

What I have so far:

html:

<span id="output"></span>

JS:

async function fetchCSV(url) {
    try {
        const response = await fetch(url);
        const data = await response.text();
        document.getElementById('output').innerText = data;
        processData(data);
    } catch (error) {
        console.error('Error fetching CSV:', error);
    }
}

//Link to csv file
fetchCSV('https://blabla/myfile.csv');

//read csv and save contents to variable "lines"
function processData(csv){
    var allTextLines = csv.split(/rn|n/);
    var lines = [];
    var keys = allTextLines.shift().split(','); //first line (headers) of csv
    while (allTextLines.length) {
        var arr = allTextLines.shift().split(',');
        var obj = {};
        for(var i = 0; i < keys.length; i++){
            obj[keys[i]] = arr[i];
    }
        lines.push(obj);
    }
    console.log(lines);
    drawOutput(lines);
}

//draw table function drawOutput(lines){
    //clear previous data
    document.getElementById("output").innerHTML = "";
    var table = document.createElement("table");

//first row (cols names) with "th"
var tableHeader = table.insertRow(-1);
Object.keys(lines[0]).forEach(function(key){
    if (key == "PDF1") {} //don't show "PDF1" column
    else if (key == "PDF2") {} //don't show "PDF2" column
    else {
        var el = document.createElement("TH");
        if (key == "PDF3") {el.innerHTML = "PDF";} //show "PDF3" column as "PDF"
        else {el.innerHTML = key;}
        tableHeader.appendChild(el);
    }
});

//the data (rest of the table)
for (var i = 0; i < lines.length-1; i++) {
    var row = table.insertRow(-1);
    Object.keys(lines[0]).forEach(function(key){
      if (key == "PDF1") {var pdflink1 = lines[i][key];}
      else if (key == "PDF2") {var pdflink2 = lines[i][key];}
      else if (key == "PDF3") {var pdflink3 = lines[i][key];
          var data = row.insertCell(-1);
          if (pdflink1 != []) {
              var a1 = document.createElement('a');
              a1.innerHTML = 'pdf1 ';
              a1.href = "dir/" + pdflink1;
              data.appendChild(a1);
          }
          if (pdflink2 != []) {
              var a2 = document.createElement('a');
              a2.innerHTML = 'pdf2 ';
              a2.href = "dir/" + pdflink2;
              data.appendChild(a2);
          }
          if (pdflink3 != []) {
              var a3 = document.createElement('a');
              a3.innerHTML = 'pdf3';
              a3.href = "dir/" + pdflink3;
              data.appendChild(a3);}
          }
      else {
    var data = row.insertCell(-1);
    data.appendChild(document.createTextNode(lines[i][key]));
  }});
}
document.getElementById("output").appendChild(table);
}

Everything seems to work OK, but I’m struggling to “keep” the pdf names in pdflink1 and pdflink2 to put them together with pdflink3 when key == “PDF3” is true. Out of three, only the latter is presented as desired in the output:

| Number | PDF                                         |
| 0      |                                             |
| 1      | [dir/undefined]                             |
| 2      | [dir/undefined] [dir/undefined]             |
| 3      | [dir/undefined] [dir/undefined] [dir/3c.pdf]|

I appreciate any assistance. Thank you.

JS, Is there a way web client access file cached date of image url?

I have a react component for thumbnails in client,

export default function Thumbnail({
  url,
  updatedDate, // updatedDate is from server api
}) {
  const cachedDate = new Date(.....);
  const queryStr = cachedDate < updatedDate ? '?force=' + Math.random() : '';

  return (
    <img
      src={url + queryStr}
      alt={'THUMB'}
    />

)}

How can I get cachedDate? Is it possible?