Filtering items on the backend

I am filtering my items from the backend by query object which takes : brand,size,price.
Then I skip and limit ( pagination ) the list that I got.
Now the problem is when I want to filter by price in my app I got a slider which gets two values in array, example: [199,800] so I want to get all products between that range.

This is how I tried to do that:

getProductsPagination: async (
  _,
  { page, productsFiltersInput: { size, brand, price, color } }
) => {
  const query = {};
  if (size) {
    query.size = size;
  }
  if (brand) {
    query.brand = brand;
  }
  if (color) {
    query.color = color;
  }

  let result = Product.find(query);
  let products;
  const skip = (page - 1) * 12;
  const limit = 12;
  const totalItems = await Product.countDocuments(query);
  const pages = Math.ceil(totalItems / limit);
  result = result.skip(skip).limit(limit);

  products = await result;
  if (price.length > 0) {
    products = products.filter(
      (x) => x.price > price[0] && x.price < price[1]
    );
  }

  return { products, numOfPages: pages };
},

The problem here as you can guess I am getting the products between that price range but I get them in seperate pages. I get 3 items in that range each item on each page which I don’t want to. I want them to be all in same page. Now I know what I am doing wrong but I am really don’t know how to continue from here. would like to get some hints!

Getting at select Yahoo Finance data returned by Fetch in ReactJS [duplicate]

In React I can use Fetch() to get all the data from https://query2.finance.yahoo.com/v8/finance/chart/M6E=F and store it, then see it using:

let actualData = await response.json();
console.log(actualData);

but how to do I get at the lower levels of that data now stored in actualData, such as chartresultindicatorsopen or any other individual item that I can see when I drill down through the data? So far all I have found is information about parsing the entire thing back, not individual elements of it.

With the HTMLMediaElement seeked event in use with video, how do you access the seeked time?

The MDN docs give the following example seeked event code:

video.addEventListener('seeked', (evt) => {
  console.log('Video found the playback position it was looking for.');
});

My question is, how can I access the playback position it was looking for? Ideally, I want something like this:

video.addEventListener('seeked', (evt) => {
  console.log('position it was looking for', evt.positionItWasLookingFor);
});

If the above is not possible, can I rely on video.currentTime instead? Consider the following code:

video.addEventListener('seeked', (event) => {
  console.log('position it was looking for', video.currentTime);
});

video.currentTime = 10
setTimeout(() => video.currentTime = 20, 50)
setTimeout(() => video.currentTime = 30, 100)

Is this approach valid?

I would prefer my 1st suggested approach if its possible. If not, is my 2nd approach valid? Or is there a totally different solution that I am overlooking?

TIA

sync function behaves as async. How can I await it? [duplicate]

I’m quite confused about this code as it should behave sync, but it doesn’t return data in time.

In my experience, the following should happen:

  1. pdf.create is called
  2. blob and pdfSize is set
  3. console.log(BLOB AND SIZE)
  4. console.log(BLOB AND SIZE OUTSIDE)
  5. uploadFile

But this is what really happens:

  1. pdf.create is called
  2. console.log(BLOB AND SIZE OUTSIDE) (undefined)
  3. uploadFile (Throws an error)
  4. blob and pdfSize is set
  5. console.log(BLOB AND SIZE)

I am using html-pdf node package

resolve: async (parent, args, { req }) => {
        try {
        //...
          let blob = undefined;
          let pdfSize = 0;
          const pdfId = uuidv4();
          
           pdf.create(args.data.htmlTemplate, {
              //...
            })
            .toBuffer((err, buffer) => {
              if (err) {
                console.log(err);
              }

              blob = Buffer.from(buffer).toString('base64') as unknown as Blob;
              pdfSize = Buffer.byteLength(buffer);
              console.log('BLOB AND SIZE: ', blob, pdfSize);
            });

          console.log('BLOB AND SIZE OUTSIDE: ', blob, pdfSize);
          await uploadFile(pdfId, blob as unknown as string, 'application/pdf');
//...
        } catch (error) {
          console.error(JSON.stringify(error, null, 2));
          if (error instanceof Error) {
            throw new Error(error.message);
          }
        }
      },

There are no indication by typescript that .pdfCreate is async or a promise, and awaiting it does not work.

Im I not understanding the function chaining correctly?

How can I get to to work in the order I mentioned above?

Couldn’t start a graphQL server

Code:

const { ApolloServer, gql } = require("apollo-server-express");

const typeDefs = gql`
  type Query {
    hello: String
  }
`;

const resolvers = {
  Query: {
    hello: () => {
      return "World!!";
    },
  },
};

const server = new ApolloServer({
  typeDefs,
  resolvers,
});

server.listen().then(({ url }) => {
  console.log("Server is ready at " + url);
});

Trying to run the above code node index.js returns

TypeError: server.listen is not a function

How can I update an article with img?

I am building the crud for my news-website. The create and read function are working. But when I want to update my article with img file, I get the following error:

A component is changing an uncontrolled input to be controlled. This
is likely caused by the value changing from undefined to a defined
value, which should not happen.

I tried it with useRef(), but nothing changes.
Nothing is updated.

Here is my edit-file:

const MainnewsEdit = () => {
    const {mainnews, isLoading, isError, message} = useSelector((state)=>state.mainnews);
    //Bringing in the saved data
    const savedData = {
        ressort:"",
        theme:"",
        title:"",
        content:"",
    };
    const [data, setData] = useState(savedData);
    //special for file
   const [fileData, setFileData] = useState({
    img:""
});
   const {img} = fileData;
   const fileInput = useRef(img);

   //logic
    const dispatch = useDispatch();
    const {id} = useParams();

    useEffect(()=>{
        if(isError){
            window.alert(message);
        }
            dispatch(getMainNews(id));

            return ()=>{
                dispatch(reset());
            }
        
    },[dispatch, isError, id, message]);
    //Bring Data into savedData
    useEffect(()=>{
        if(mainnews){
        setData({...mainnews})
        }
        return ()=>{
            dispatch(reset());
        }
    },[mainnews, dispatch]);
    console.log(data);
    //updateFileData
    const updateFileData = (e)=>{
        // const file = fileInput.current.files[0];
        // setFileData(file);
        setFileData((prevState)=>({
            ...prevState,
            [e.targte.name]: e.target.files[0],
        }));
        handlePreview(img);
    };
    console.log(fileData);
    //preview
    const [preview, setPreview] = useState("");
    const handlePreview = (file)=>{
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onloadend = ()=>{
            setPreview(reader.result);
        }
    }
    //updateData
    const updateData = (e)=>{
        setData((prevState)=>({
            ...prevState,
            [e.target.name]:e.target.value,
        }))
       
    }
    const {ressort, theme, title, content} = data;
    const onSubmit = (e)=>{
        e.preventDefault();
        const mainnewsData = new FormData();
        mainnewsData.append("ressort", data.ressort);
        mainnewsData.append("theme", data.theme);
        mainnewsData.append("title", data.title);
        mainnewsData.append("content", data.content);
        mainnewsData.append("img", fileData)
       
        dispatch(updateMainNews(mainnewsData))
    }

That is my input:

<MainNewsForm onSubmit={onSubmit}>
            <Formgroup>
                <Label htmlFor="img">Image</Label>
                <Input type="file" name="img" id="img" ref={fileInput} onChange={updateFileData} style={{background:"var(--blue)", color:"var(--white)"}}/>
                {preview && <img src={preview} alt={preview} title={preview} style={{height:"200px", width:"400px"}}/>}
            </Formgroup>
            <Formgroup>
                <Label htmlFor="ressort">Ressort</Label>
                <Input type="text" name="ressort" id="ressort" value={ressort} onChange={updateData}/>
            </Formgroup>
            <Formgroup>
                <Label htmlFor="theme">Theme</Label>
                <Input type="text" name="theme" id="theme" value={theme} onChange={updateData}/>
            </Formgroup>
            <Formgroup>
                <Label htmlFor="title">Title</Label>
                <Input type="text" name="title" id="title" value={title} onChange={updateData}/>
            </Formgroup>
            <Formgroup>
                <Label htmlFor="content">Content</Label>
                <Textarea type="text" name="content" id="content" value={content} onChange={updateData}></Textarea>
            </Formgroup>
            <ButtonHolder>
                <UpdateButton type="submit">Update</UpdateButton>
            </ButtonHolder>
        </MainNewsForm>

await-sleeping in JavaScript

Is this a valid way to emulate sleep() in JavaScript, when using async/await?

async function sleep(msec) {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, msec);
  });
}

Usage:

async function testSleep() {
  console.log('going to sleep', new Date());
  for (let i = 0; i < 8; i++) {
    await sleep(500);
    console.log('slept a little bit');
  }
  console.log('done sleeping', new Date());
}

This sleeps 8 times for 500 msec each time.

> await testSleep()
going to sleep 2022-07-13T09:56:05.793Z
slept a little bit
slept a little bit
slept a little bit
slept a little bit
slept a little bit
slept a little bit
slept a little bit
slept a little bit
done sleeping 2022-07-13T09:56:09.802Z

It works — but are there any gotchas that I’m not taking into account?


To clarify: I only intend to use it in test code (waiting for something to happen). I know that you’re not really supposed to sleep in JavaScript.

Calling a nested function with a string (window[]) in JS

How to call a nested function with only a string? eg:

    function oot(wha)   {
        oot.inn = inn;
        function inn(wha)
        {First.innerHTML+="Inner ["+wha+"]";}
    Second.innerHTML+="Outer ["+wha+"]";
                        }
    oot("1");   
    oot.inn("2");   //works okay
    window["oot"]("3"); //works okay
    window["oot.inn"]("4"); //<The problem, doesn't work.

The b-button is not displayed in the b-table VueJs

Im starting at Vue Js, my problem is that my b-button is not shown in my table and I don’t understand why.

Here is my HTML code:

<div id="listlocales">
            <div class="overflow-auto">
                <b-button size ="sm" href="{% url 'newLocal'}" variant="outline-primary"> Nuevo Local</b-button>
                <br></br>
                <b-table
                id="my-table"
                striped responsive="sm"
                :items="items"
                :fields="fields"
                :per-page="recordsPerPage"
                :current-page="currentPage">
                    <template #cell(actions)='data'>
                        <b-button size="sm" variant="primary" @click="getLocales()"> Editar </b-button>
                        <b-button size="sm" variant="danger" href="{% url 'newLocal' %}"> Eliminar </b-button>
                    </template>
                </b-table>
                <b-pagination
                v-model="currentPage"
                :total-rows="totalPages"
                :per-page="recordsPerPage"
                aria-controls="my-table"
                ></b-pagination>
            </div>
        </div>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
        <script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.js"></script>
        <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

And here is my script Vue code:

        <script>
            const listloc = new Vue({
                el: '#listlocales',
                data: {
                    items: [],
                    currentPage: 1,
                    totalPages: 0,
                    recordsPerPage: 10,
                    isLoading: false,
                    fields: [
                        { key: 'id', label: 'ID' },
                        { key: 'descripcion', label: 'Descripcion' },
                        { key: 'clave', label: 'Clave' },
                        { key: 'responsable', label: 'Responsable' },
                        { key: 'actions', label: ''}
                    ]
                }, ...
            });
        </script>
    </body>
</html>

I tried to use v-slot instead cell but isn’t working anyway… Can someone help me for solving this issue.

How to avoid .then() nesting when working with API Calls in Cypress?

With my team we’re trying to find a more readable way to handle dependent API calls in Cypress. We have some code just like this nowadays:

// nested code
      cy.request('GET', myUrl).its('body').then(res => {
        cy.request('GET', res).its('body').then(subRes => {
          cy.request('GET', subRes).its('body').then(subSubRes => {
            expect(subSubRes, myMessage).to.eq(myEvaluation);
          })
        })
      })

We have thought about this solution also but I think we doesn’t gain a lot in readability.

// less nested code?
      let response;
      let subResponse;
      cy.request('GET', myUrl).its('body').then(res => {
        response = res;
      })
      
      cy.then(() => {
        cy.request('GET', response).its('body').then(subRes => {
          subResponse = subRes;
        })
      })

      cy.then(() => {
        cy.request('GET', subResponse).its('body').then(subSubRes => {
          expect(subSubRes, myMessage).to.eq(myEvaluation);
        })
      })

Do you have any ideas to handle this kind of logic without getting into a pyramid?
Thanks in advance!

unable to retrieve data from api

//index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Weather app</title>
  </head>
  <body>
    <form action="/" method="post">
      <label for="cityInput">City name: </label>
      <input id=cityInput type="text" name="cityName">
      <button type="submit" name="button">Go</button>
    </form>

  </body>
</html>

//app.js

const express = require('express');
const https = require('https');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({extended: true}));

app.get("/", function(req, res) {
  res.sendFile(__dirname + "/index.html");
});

app.post("/",function(req, res) {
    const query = "req.body.cityName"
    const apiKey = "191bd75b0cb71e7071b3d753788b8732"
    const unit = "metric"
    const url = "https://api.openweathermap.org/data/2.5/weather?q=" + query + "&appid=" + apiKey + "&units=" + unit;
    https.get(url,function(response) {
      console.log(response.statusCode);

      response.on("data",function(data) {
        const weatherData = JSON.parse(data)
        const temp = weatherData.main.temp;
        const weatherDescription = weatherData.weather[0].description;
        const icon = weatherData.weather[0].icon;
        const imgURL = "http://openweathermap.org/img/wn/" + icon +"@2x.png"
        res.write("<p>The weather is completely "+ weatherDescription +"</p>");
        res.write("<h1>The temperature of " + query + " is " + temp +" degrees celsius </h1>");
        res.write("<img src=" + imgURL +">");
        res.send()
      })
    })
  });
app.listen(3000, function() {
  console.log("Server is running on port 3000");
});

weatherData.main.temp is giving error in app.post part.It is not retrieving data from weather api. I am taking data from openweathermap.org and it is giving error-cannot give reading of undefined (reading ‘temp’).

Does any browser allow me to step through network requests one-by-one?

I’m hoping to find which of my page’s many network requests are triggering a problem. (Or rather, I want to guide someone else through this process remotely.)

Is there any browser that offers a way to “step through” network requests in the dev tools, pausing the loading of other resources for an arbitrary period before I tell it to step on to the next request?

This is a common feature in IDE environments, but I’m not sure if I’ve ever heard of it in the browser. (I also tried googling a few phrases without success.) But I’m not a frontender, so maybe it’s common knowledge.

Vite: Identifier ‘require$$0’ has already been declared

I am trying to set up Vite build system for my existing project.

Dev build works fine, but when built for production, the bundle gives this error during runtime:

index.89943202.js:319 Uncaught ReferenceError: require is not defined
    at index.89943202.js:319:23570
    at ir (index.89943202.js:305:34977)
    at index.89943202.js:319:23158

I’ve googled for solutions and added this option to my vite.config.cjs:

    commonjsOptions: {
      transformMixedEsModules: true
    },

After that, the build now fails with:

file: proj-path/node_modules/some-custom-library/build/index.es.js:55:0
53: import ArrowBackIosIcon from '@material-ui/icons/ArrowBackIos';
54: import ArrowForwardIosIcon from '@material-ui/icons/ArrowForwardIos';
55: import require$$0 from 'object-is';
    ^
56: import require$$1 from 'has';
57: import _propTypes from 'prop-types';
error during build:
Error: Identifier 'require$$0' has already been declared

This library is included through “module”: “./build/index.es.js”.

I think the problem here is that the library is somehow built in a separate context from the main bundle and now symbols overlap, because they didn’t know about existing symbols during build time.

How to get rid of this error?

This is my Vite configuration:

import { defineConfig } from 'vite';
import path from 'path';
import envCompatible from 'vite-plugin-env-compatible';
import { injectHtml } from 'vite-plugin-html';
import { viteCommonjs } from '@originjs/vite-plugin-commonjs';
import react from '@vitejs/plugin-react'
import svgr from 'vite-plugin-svgr'
import checker from 'vite-plugin-checker';

const dirname = __dirname


// https://vitejs.dev/config/
export default defineConfig({
  resolve: {
    alias: [
      {
        find: '@',
        replacement: path.resolve(dirname, 'src')
      }
    ],
    extensions: [
      '.mjs',
      '.js',
      '.ts',
      '.jsx',
      '.tsx',
      '.json',
      '.vue'
    ]
  },
  plugins: [
    svgr(),
    react(),
    viteCommonjs(),
    envCompatible({ prefix: "REACT_APP" }),
    injectHtml(),
    checker({
      typescript: true,
    }),
  ],
  build: {
    rollupOptions: {},
    outDir: './build',
    minify: "esbuild",
    target: 'es2015',
    commonjsOptions: {
      transformMixedEsModules: true
    },
  },
})

Material-UI DesktopDatePicker onError returning null for reason

So I am using Material-UI’s DesktopDatePicker as such

 <LocalizationProvider dateAdapter={AdapterDateFns}>
                        <DesktopDatePicker
                          label="Requested Delivery Date"
                          inputFormat="MM/dd/yyyy"
                          value={requestedDate}
                          defaultCalendarMonth={minimumDeliveryDate}
                          open={openDate}
                          clearable={true}
                          onClose={() => setOpenDate(false)}
                          minDate={minimumDeliveryDate}
                          onError={(event1, event2) => {
                            console.log(event1);
                            console.log(event2);
                          }}
                          onChange={(date) => {
                            const formattedDate = moment(date).isValid()
                              ? moment(date).format("MM/DD/YYYY")
                              : "Invalid Date Format";
                            setRequestedDate(formattedDate);
                            setRequestedDateInTabs(formattedDate);
                            if (requestedDateError) setRequestedDateError("");
                            setDirty();
                            setFormChanged(true);
                          }}
                          disabled={create || adminManage ? false : true}
                          renderInput={(params) => (
                            <TextField
                              {...params}
                              fullWidth
                              onKeyPress={(e) => {
                                e.preventDefault();
                              }}
                              size="small"
                              onKeyDown={(e) => {
                                if (e.code !== "Backspace") {
                                  e.preventDefault();
                                }
                              }}
                              onClick={() => {
                                if (create || adminManage) {
                                  setOpenDate(!openDate);
                                }
                              }}
                              error={requestedDateError}
                              helperText={requestedDateError}
                              onChange={(e) => {
                                e.preventDefault();
                              }}
                            />
                          )}
                        />
                      </LocalizationProvider>

The minimum date is usually a few days from the current date so whenever the user first opens the date picker and the date previously in it is before the minimum allowed date, it automatically corrects it to the minimum date possible.

However, in this case it is not displaying the new date unless I choose a different date then choose it again (it does however set the requestedDate value to it).

when I add the onError function to display the possible reason and value, it is returning the following data:

null
07/27/2022

so I am not able to locate the error happening.