Executing Prisma query in loop: Promise { }

My code:

const getStats = async (projects) => {
  return projects.map(async (project) => {
    const count = await db.ping.count({
      where: { projectId: project.id },
    })
    console.log("Result is: " + count)
    return count
  })
}

The return value (there are two different projects, so two elements are correct):

[ Promise { <pending> }, Promise { <pending> } ]

If I understand that correctly, my outer promise when I call the function gets resolved correctly. Hence the array itself is not wrapped in a Promise. However, my two values still seem to be wrapped in a promise. The weird thing is that the console.log calls output the correct count number for each project, without any Promises:

Result is: 8
Result is: 1

Can anyone help me out here?

PUT request from React through superagent being sent with no content

The method sending the request looks like this:

const updateCompany = ({sessionKey},company) => {
    const tempCompany = company.newCompany;
    console.log("sessionkey:" + sessionKey);
    console.log("check123" + JSON.stringify(tempCompany,getCircularReplacer()));
    const url = createServiceUrl(`api/company/${sessionKey}/${tempCompany.id}`);
    request
        .put(url)
        .send({ Company: tempCompany })
        .end((err, res) => {
            if (res.ok) {
                console.log("Updated OK!")
            }
        });
}

The check123 console.log prints the object I’m trying to send with all the expected values and keys, but for some unknown reason the request going out is completely empty and all I get back from the controller is a 204. I suppose I’m supposed to do something differently here, but I can’t see what.

React-Native Firestore – Get user info for a comment section

I’m building an app using react-native and react-native-firebase and i’m running into an issue while trying to implement a comment section.

My tree of data is currently like that :
collection(comments)/doc(currentUser.uid)/collection(userComments)/doc(commentCreatorID)

Within this doc commentCreatorID there is all the data i need. So basically the content, a timestamp…

For this part everything works perfectly but in order to havethe commentCreator’s infos stick with his post, i need to grab them somewhere else.
The way i do that is taking the doc(commentCreatorID), as it is the uid of this user and ask firestore to give me the data from the document with this same id within my “users” collection.

Here is my code :

  const [comments, setComments] = useState([])
  const [commentsReady, setCommentsReady] = useState([])

useEffect(() => {

        setComments([])
        setLoading(true)
        firestore()
        .collection('comments')
        .doc(auth().currentUser.uid)
        .collection('userComments')
        .get()
        .then((snapshot) => {
            let comments = snapshot.docs.map(doc => {
                const data = doc.data()
                const id = doc.id
                return {id, ...data}
            })
            setComments(comments)
        })
        .then(() => {
            comments.forEach(comment => {
                firestore()
                .collection("users")
                .doc(comment.id)
                .get()
                .then((snapshot) => {
                    const data = snapshot.data()
                    setCommentsReady({comments, ...data})       
                })
            })
        })
       console.log(commentsReady)
        setLoading(false)
    }, [handleScroll4])

This doesn’t seem to works well as for now. My log throw an empty array right into my face..
I’m grabbing each comment correctly tho and even each user’s data corresponding to their uids.
I can log them once ForEach have been done.
But for some reason i can’t have them set to my state commentsReady.

Did i miss something ?

Thanks for your time

How to edit an embed?

I cannot edit an embed that is already posted, here is my code :

const c = client.channels.cache.get('919237216692215829')
const m = c.messages.cache.get('919675014633095179')
const embed = new MessageEmbed()
//embed..
m.edit(embed)

console:

m.edit(embed)
  ^

TypeError: Cannot read property 'edit' of undefined```

Excute Javascript when order status is changed in the back-end

I am trying to execute a JavaScript file for when the order status is changed in the back-end. But it doesn’t seem to work. Below is the code I am currently using. Can anybody tell me what I am doing wrong? When I try to enqueue the script in other places, it does work.

function script_on_order_complete( $order_id ) {
    wp_register_script('test', get_template_directory_uri() .'/js/test.js',false);
    wp_enqueue_script( 'test');
}
add_action( 'woocommerce_order_status_completed', 'script_on_order_complete', 10, 1 );

Changing the size of a with the value of fetched data

I am fetching data from an api and display some props of them using mapping and I want to change the width of the accordingly with the value of the props.

<h5>
    <span className="viewcount" ref={boxSize}>
    {`View Count: ${item.statistics.viewCount}`}</span>
</h5>

For example, this is a prop called “viewcount” from the api item, and I want the width of this component to be 200px when the viewcount prop is a number of 200.
How can I acheive it?

P.S.: I’m using react.

How to attach user credentials to the request pipeline in expressjs?

I am trying to write a middleware that extracts the user model and attach it to the request pipeline.
I have already written a token extractor middleware and managed to attach the token to the request pipeline, but for some reason when I try to extract the user model, it works fine inside the middleware function yet inside my controller it returns as undefined.

Here’s what I have tried:

utils/middleware.js

const tokenExtractor = async (request, response, next) => {    
        const authorization = await request.get('authorization');
       if (authorization && authorization.toLowerCase().startsWith('bearer ')) {
         request.token = authorization.substring(7);         
       } else{
         request.token = null;
        }
        next();
};

const userExtractor = async (request, response, next) => {  
  tokenExtractor(request, response, next);
  if(request.token){
    const decodedToken = jwt.verify(request.token, process.env.SECRET);    
    request.user = await User.findById(decodedToken.id);
    console.log(request.user); // Works
    next();
  } else{
    response.status(403).json({ error: 'no token received' });
  }
};

Inside my controllers it breaks down:

controllers/blogs.js

blogRouter.post("/", async (request, response, next) => {
  if (request.body.title && request.body.url) {
    const token = request.token;    
    if (!token) {
      return response.status(401).json({ error: 'invalid token' });
    }
      
    console.log(request.user); // undefined !
    if(!request.user){
      return response.status(401).json({ error: 'invalid user' });
    }
    
    const user = request.user;    
    
    const blog = new Blog({
      title: request.body.title,
      author: request.body.author,
      url: request.body.url,
      likes: request.body.likes,
      user: user._id,
    });

    
    await blog.save();    
    
    user.blogs = user.blogs.concat(blog._id);
    await user.save();
    
    response.status(201).json(blog);
  }
  response.status(400).end();
});

Both middleware are already attached to the express app.

Argument type number is not assignable to parameter type string | undefined Type number is not assignable to type string

i am bit confused with this warning Argument type number is not assignable to parameter type string | undefined Type number is not assignable to type string

Take the following peace of code :

function createCalculator() {

    let calculator = {
        sum() {
            return this.a + this.b;
        },

        mul() {
            return this.a * this.b;
        },

        read() {
            this.a = +prompt('a?', 0);
            this.b = +prompt('b?', 0);
        }
    };

    calculator.read([1,3,6]);
    console.log( calculator.sum() );
    console.log( calculator.mul() );

}
let calculator;
calculator = createCalculator();

also i have one warning :

Void function return value is used

i want the follow :

the function
createCalculator () returns an object with three methods:

read (arr) accepts a table of numbers and saves it in its field
object.

sum () returns the sum of the table values

mul () returns the product of the table values.

React-app frontend & express backend using nginx on ubuntu

I have been searching google for a couple of hours, been through multiple pages, and watching youtube videos but I am simply not able to find any guidance towards what to do in my case.

I have a react-app frontend running on Nginx.
With the frontend react-app I am running some Axios requests, example:

await axios.post("http://localhost:5000/api/getMessages", {});

I then have my express server receiving the requests and sending back responses, example:

app.post('/api/getMessages', (req, res) => {
    Messages.find().sort('-createdAt').limit(10)
        .then((result) => {
            res.send(result)
        })
})

Everything works fine in my local environment, but I am unsure of what to do when putting it on a live server with a domain using Nginx. I am able to get the react-app up and working just fine, but when making an axios request it simply returns net::ERR_CONNECTION_REFUSED

This is with my express server running in the back like a normal node project.

Ionic app with node not deploying correctly on Heroku

I have a program in ionic and I am trying to deploy it to heroku, but it gives me this error:

2021-12-12T13:20:32.269136+00:00 app[web.1]: - Generating browser application bundles (phase: setup)...
2021-12-12T13:20:49.881823+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
2021-12-12T13:20:49.912813+00:00 heroku[web.1]: Stopping process with SIGKILL
2021-12-12T13:20:50.102339+00:00 heroku[web.1]: Process exited with status 137
2021-12-12T13:20:50.173468+00:00 heroku[web.1]: State changed from starting to crashed
2021-12-12T13:24:11.000000+00:00 app[api]: Build started by user [email protected]
2021-12-12T13:26:30.635761+00:00 app[api]: Deploy 83d7c481 by user [email protected]
2021-12-12T13:26:30.635761+00:00 app[api]: Release v5 created by user [email protected]
2021-12-12T13:26:31.297561+00:00 heroku[web.1]: State changed from crashed to starting
2021-12-12T13:26:41.118110+00:00 heroku[web.1]: Starting process with command `npm run build && npm start`
2021-12-12T13:26:42.104400+00:00 app[web.1]:
2021-12-12T13:26:42.104411+00:00 app[web.1]: > [email protected] build /app
2021-12-12T13:26:42.104411+00:00 app[web.1]: > ng build --prod
2021-12-12T13:26:42.104411+00:00 app[web.1]:
2021-12-12T13:26:42.648877+00:00 app[web.1]: Option "--prod" is deprecated: Use "--configuration production" instead.
2021-12-12T13:26:44.791613+00:00 app[web.1]: - Generating browser application bundles (phase: setup)...
2021-12-12T13:26:45.000000+00:00 app[api]: Build succeeded
2021-12-12T13:27:14.252438+00:00 heroku[web.1]: Process running mem=874M(170.8%)
2021-12-12T13:27:14.254036+00:00 heroku[web.1]: Error R14 (Memory quota exceeded)
2021-12-12T13:27:35.021299+00:00 heroku[web.1]: Process running mem=923M(180.3%)
2021-12-12T13:27:35.022699+00:00 heroku[web.1]: Error R14 (Memory quota exceeded)
2021-12-12T13:27:41.252535+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
2021-12-12T13:27:41.288420+00:00 heroku[web.1]: Stopping process with SIGKILL
2021-12-12T13:27:41.863714+00:00 heroku[web.1]: Process exited with status 137
2021-12-12T13:27:41.912756+00:00 heroku[web.1]: State changed from starting to crashed

My package.json is :

{
  "name": "sigevaMantUI",
  "version": "0.0.1",
  "author": "Ionic Framework",
  "homepage": "https://ionicframework.com/",
  "engines": {
    "node": "14.x",
    "npm": "6.14.15"
  },
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build --prod",
    "watch": "ng build --watch --configuration development",
    "prepush": "npm run build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "preinstall": "npm i -g http-server && npm i -g @angular/cli"
  },
  "private": true,
  "dependencies": {
    "@angular/cli": "~12.1.1",
    "@angular/compiler": "~12.1.1",
    "@angular/compiler-cli": "~12.1.1",
    "@angular-devkit/build-angular": "~12.1.1",
    "@capacitor/cli": "3.3.2",
    "@ionic/angular-toolkit": "^4.0.0",
    "@angular-eslint/builder": "~12.0.0",
    "@angular-eslint/eslint-plugin": "~12.0.0",
    "@angular-eslint/eslint-plugin-template": "~12.0.0",
    "@angular-eslint/template-parser": "~12.0.0",
    "@angular/common": "~12.1.1",
    "@angular/core": "~12.1.1",
    "@angular/forms": "~12.1.1",
    "@angular/platform-browser": "~12.1.1",
    "@angular/platform-browser-dynamic": "~12.1.1",
    "@angular/router": "~12.1.1",
    "@capacitor/app": "1.0.6",
    "@capacitor/core": "3.3.2",
    "@capacitor/haptics": "1.1.3",
    "@capacitor/keyboard": "1.1.3",
    "@capacitor/status-bar": "1.0.6",
    "@ionic/angular": "^5.5.2",
    "rxjs": "~6.6.0",
    "tslib": "^2.2.0",
    "zone.js": "~0.11.4",
    "typescript": "~4.2.4"
  },
  "devDependencies": {
    "@angular/language-service": "~12.0.1",
    "@types/jasmine": "~3.6.0",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "^12.11.1",
    "@typescript-eslint/eslint-plugin": "4.16.1",
    "@typescript-eslint/parser": "4.16.1",
    "eslint": "^7.6.0",
    "eslint-plugin-import": "2.22.1",
    "eslint-plugin-jsdoc": "30.7.6",
    "eslint-plugin-prefer-arrow": "1.2.2",
    "jasmine-core": "~3.8.0",
    "jasmine-spec-reporter": "~5.0.0",
    "karma": "~6.3.2",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-coverage-istanbul-reporter": "~3.0.2",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "^1.5.0",
    "protractor": "~7.0.0",
    "ts-node": "~8.3.0"
  },
  "description": "An Ionic project"
}

Procfile:

web: npm run build && npm start

When I execute it in local, it works fine. However, when I push it to Heroku, it tells me that an aplicacion error occurr and I have to put this command “heroku logs –tail” to see the error that I have put before.

p5.js parent() | Uncaught (in promise) TypeError: Cannot read properties of null (reading ‘appendChild’)

I do exactly as the library docs here.

I have an error

Uncaught (in promise) TypeError: Cannot read properties of null (reading 'appendChild')

index.html

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="styles/index.css" />
        <script src="libs/p5.min.js"></script>
        <script src="scripts/barcode.js"></script>
    </head>
    <body>
        <div class="container"></div>
    </body>
</html>

Tried defer on the barcode script import, and putting it in the end.

barcode.js

function setup() {
    let cnv = createCanvas(500, 500);
    cnv.parent("container");
}

Tried this, nothing changed

async function setup() {
        let cnv = await createCanvas(500, 500);
        cnv.parent("container");
}

Thanks for your insight !

Strange body padding (VueJS + Nuxt, CSS)

I have little VueJS + NuxtJS and it has background gif. For now it looks like this:

body {
  margin: 0 auto;
  background: url("assets/video/background-darked.gif") no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  @media only screen and (max-width: 860px) {
    overflow-y: scroll;
  }
}

As you can I have it on the whole body, but I don’t really need it, this background gif should be only on a few pages, so, if change body to classname (let’s say main) and use this class like that:

<template>
  <div class='main'>
    <Header />
  </div>
</template>

I will have that strange paddings:

enter image description here

How may I fix this?

How to get all string variable values from JS code

I have a long code that I want to export all the string values within it into a text file.
I want to do that so I can let someone else fix some of the English in it ahahaha.

How can I do that?

Example, the text file should be something like:

var1: ‘Hello world’

var2: ‘foo’

var3: ‘bar’