How to make multiple requests via one endpoint

I’m practicing as a front end dev and I should code opening .md files with use express node js. Also, in some .md files could be a links [[path-to-the-md-file]] like this and I should make them looks like this <a href='path-to-the-md-file.md'>link</a>. But I really don’t know how to make this. This is my app.js file:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const serveMarkdownRouter = require('./routes/serveMarkdown'); 
const app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'twig');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users/:id', usersRouter);
app.use(function(req, res, next){
  if(!(String(req.url).includes('/serve-md/'))) res.render('error');
  else{
  const fs = require('fs');
  const parseMD = require('parse-md').default;
  var express = require('express');
  var filePath = 'posts/readme.md'; // default md file
  console.log(req.baseUrl);
  const fileContents = fs.readFileSync(filePath, 'utf8');
  var { metadata, content } = parseMD(fileContents);
  res.render('serve-markdown', {title: 'Serve-markdown', metatitle: metadata['title'], metadescription: metadata['description'], cont: content});
  }     
})
 
app.get('/', function(req, res){
  console.log("Render Working")
  res.send();
});

// app.use('/serve-md/:path', serveMarkdownRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

I know I could do this through some Router like this app.use('/serve-md', serveMarkdownRouter);, but I couldn’t handle all file links via this router. What should I read or do to make my task done? Thanks.

How to correctly wrap and call a function in an object

After many hours looking for a explanation and failing, I am asking it here.

All code here are examples made from what I was working on.

First Approach

Simple object:

let obj = {
    fun: window.getComputedStyle,
    ele: $('#myDiv')[0]
};

When trying the following function call:

obj.fun(obj.ele);

Gives the following error:

Uncaught TypeError: 'getComputedStyle' called on an object that does not implement interface Window.

I am using jQuery to retrieve the JS element, but using document.getElementById would produce the same result.

Second Approach

I did search for a while about different types of objects, and found this style:

let obj = {
    fun: function() {return window.getComputedStyle},
    ele: $('#myDiv')[0]
};

But this type needs to be called differently:

obj.fun()(obj.ele);

This approach works correctly.

Question

Obviously the expanded version of the code works as intended:

window.getComputedStyle($('#myDiv')[0]);

The above code returns the full object correctly.


So my questions are:

  • Why is the first approach (which makes more sense to me) fails?
  • Is there a way to fix the first approach, so I can use the first type of function call?
  • Is this type of function wrapping not supposed to be done?

Thank you!

How to call a function from another .js file in React Native Expo

I’m new to React and I’ve faced such a problem:

I have Main.js file with a button:

import * as React from 'react';
import { StyleSheet, Text, View, SafeAreaView, Pressable, Alert } from 'react-native';
import { MaterialIcons, MaterialCommunityIcons} from '@expo/vector-icons';
import { DrawerActions } from '@react-navigation/native';
import Scanner from './Scanner'

const handleButtonPress = () => Alert.alert('Button pressed')

export default function Main({ navigation }) {
  return (
      ....
      <View style={styles.container}>
        <Pressable style={styles.button} onPress={ handleButtonPress }>
          <Text style={styles.buttonText}>Take charger</Text>
        </Pressable>
      </View>
  );
}

An I have another file Scanner.js:

import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import { BarCodeScanner } from 'expo-barcode-scanner';

export default function Scanner() {
  const [hasPermission, setHasPermission] = useState(null);
  const [scanned, setScanned] = useState(false);

  useEffect(() => {
    (async () => {
      const { status } = await BarCodeScanner.requestPermissionsAsync();
      setHasPermission(status === 'granted');
    })();
  }, []);

  const handleBarCodeScanned = ({ type, data }) => {
    setScanned(true);
    alert(`Bar code with type ${type} and data ${data} has been scanned!`);
  };

  if (hasPermission === null) {
    return <Text>Requesting for camera permission</Text>;
  }
  if (hasPermission === false) {
    return <Text>No access to camera</Text>;
  }

  return (
    <View style={styles.container}>
      <BarCodeScanner
        onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
        style={StyleSheet.absoluteFillObject}
      />
      {scanned && <Button title={'Tap to Scan Again'} onPress={() => setScanned(false)} />}
    </View>
  );
}


const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  }
}); 

How can I call a function Scan() from Scanner.js on button click in the Main()
function in Main.js. I’ve tried onPress={() => Scanner} but it didn’t work for me because of wrong hooks usage.

Close menu when user clicks on div

How can I check if a user is clicking on a div called right-side-container and if they are remove the class of menu-opened.

    toggleMenu() {
      this.open = !this.open;
      document.getElementsByTagName("html")[0].classList.toggle("menu-opened");
      if (this.open) {
        document.addEventListener("click", this.menuClickListener);
      } else {
        document.removeEventListener("click", this.menuClickListener);
      }
    },
    menuClickListener($event) {
      console.log($event);
    },
  },
}; 


// This is what I want to remove when the user is clicking the right-side-container
document.getElementsByTagName("html")[0].classList.remove("menu-opened");

Search all objects and return the values that match

I want to make a search that beside the first object searchs all other objects values inside it and returns in the array all those orders that matched and even if uppercase/lowercase don’t match:

Here is an random order: (not real data)

screenshot

So that is my data I want to search, I have a function but that search only the first layer of the object and not for exampel the customer and vehilce object inside also Is not case sensitive so I would like to have that.

Here it is it:

const findIn = (arr, query) => {
        let queryFormatted = query.toLowerCase();
        return arr.filter((obj) =>
          Object.keys(obj).some((key) => {
            if (typeof obj[key] === 'string') {
              return obj[key]
                .toLowerCase()
                .includes(queryFormatted);
            }
            return false;
          })
        );
      };

Different results by using destructuring – Javascript [duplicate]

I understand that these two calls should return the same value. I think the assignment I made is wrong but I don’t see how to do it right.

info2 () returns the correct value while info () does not.

Client.prototype.info2 = function () {
    return (this.AccountType())
}
Client.prototype.info = function () {
    const {AccountType} = this
    return (AccountType())
}

——- All code ——-

function Client(name, balance) {
    this.name = name;
    this.balance = balance;
}

Client.prototype.AccountType = function () {
    const {balance} = this
    let type;

    if (balance >= 10000) {
        type = 'Platinum'
    } else if (balance >= 5000) {
        type = 'Gold'
    } else {
        type = 'Standard'
    }
    return type;
}

//Expected result: 'Gold'
// Result: 'Gold'

Client.prototype.info = function () {
    const {AccountType} = this
    return (AccountType())
}
//Expected result: 'Gold'
// Result: 'Standard'

Client.prototype.info2 = function () {
    return (this.AccountType())
}
//Expected result: 'Gold'
// Result: 'Gold'

//instances

const Pedro = new Client('Pedro', 8000)

Reactjs, instantiate function with multiple route params

I have a function inside a useEffect hook that fetches data. How do I pass in 2 string literals into the components arguments?
Here is my getObject() function

  const getObject = async (bucketKey, objectKey) => {
    dispatch({ type: GET_OBJECT_BEGIN })
    try {
      const { data } = await authFetch(
        `/oss/buckets/${bucketKey}/objects/${objectKey}/details`
      )
      const { bucketObject } = data
      console.log('bucketObjects', data)
      dispatch({
        type: GET_OBJECT_SUCCESS,
        payload: {
          bucketKey,
          objectKey,
          bucketObject,
        },
      })
      addObjectKeyToLocalStorage({ objectKey })
    } catch (error) {
      console.log(error)
    }
    clearAlert()
  }

Here is my ObjectDetails component, that has a useEffect hook that calls the getObject() function to fetch the data

const ObjectDetails = ({ bucketKey, objectKey }) => {
  const { getObject, isLoading } = useAppContext()

  useEffect(() => {
    getObject(`${bucketKey} ${objectKey}`)
  }, [])

  return (
    <Wrapper>
      <header>Object Details</header>
    </Wrapper>
  )
}

export default ObjectDetails

Here is the issue I have, the url being called from getObject() is showing undefined
http://localhost:3000/api/v1/oss/buckets/undefined%20undefined/objects/undefined/details

Alternatively, there is probably a better way to approach this but I am not sure how?
Below is the link that takes me to the page from above and the url in the link works fine

           <Link
              to={`/buckets/${bucketKey}/objects/${objectKey}/details`}
              className='btn edit-btn'
              onClick={() => getObject(bucketKey, objectKey)}
            >
              Details
            </Link>

why package.json exports field not working in npm package

I have developed an npm package that builds three js files.
in my project I want to import js files like this:

import MyButton from '@bslm/ui/MyButton'

so i used the exports field in my package.json like this:

"type": "module",
"exports": {
  "./MyButton": "./dist/my-button.common.js",
  "./MyInput": "./dist/my-input.common.js",
  "./MyImage": "./dist/my-image.common.js",
}

but when i try:

import MyButton from 'mypackage/MyButton'

I get this error: These dependencies were not found

node version: 14.18.1
npm version: 8.5.4

Add br tag after few anchor tags in jquery

I have following HTML:

<td class="sorting_1">
   <a href="/show/1">1</a>
   <a href="/show/2">2</a>
   <a href="/show/3">3</a>
   <a href="/show/4">4</a>
   <a href="/show/5">5</a>
   <a href="/show/6">6</a>
</td>

Output:

1 2 3 4 5 6

I want to have such that the <br> tag is added after 3 anchor tag, so the output looks like following:

1 2 3
4 5 6

How to do in jQuery?

javascirpt – How to sumthe total quantity of a column when the numbers of rows is dynamic?

How do I write a function to sum the total quantity of a specific column in a table by using javascript

I’m trying to sum the quantity in the same column.
I have 15 columns in my table and more than 1000 of rows. One of the column was the quantity of stock on hand.

When i do filtering, the numbers of row will change accordingly, I only want to display the sum of the column of the rows displaying.

Was quite fresh to javascript, hope to get some help please. Thank you!

Angular getComputedStyle from SCSS

i am trying to get the computed style from SCSS file but it returns an empty string.
is there another way to get the getComputedStyle from SCSS ?

Angular Component:

    const elem = getComputedStyle(document.documentElement);
const colorTest = elem.getPropertyValue('test').trim();   // colorTest = ''

SCSS File:

$test : red;