Need help transforming GraphQL results

A returned schema looks like the following:

{
    data: {
        posts: {
            edges: [
                {
                    post: {
                        id: ‘1’,
                        title: ‘Foo’
                    },
                    post: {
                        id: ‘2’,
                        title: ‘Bar’
                    }
                }
            ]
        }
    }
}

This works and I can use it, but I’m having to create nested interfaces unfortunately.

Question: Can I either simplify the returned results OR transform them with JavaScript map()?

Ideally, I’d like for the GQL response (or resulting object) to be like:

{
    data: {
        posts: [
            post: {
                id: ‘1’,
                title: ‘Foo’
            },
            post: {
                id: ‘2’,
                title: ‘Bar’
            }
        ]
    }
}

Note: I do not have the ability to update the server-side GraphQL schema. The solution must be client/consumer side.

Thanks!

Merge two array of objects not based on key

I want to marge two arrays not based on key

Array1

[
  { size: "45", color: "red" }, 
  { size: "48", color: "blue" }
]

Array2

[
  { designation: "short", price: "540" }, 
  { designation: "jeans", price: "600" }
]

I need to merge these two arrays and expected this array

[
  { size: "45", color: "red", designation: "short" }, 
  { size: "48", color: "blue", designation: "jeans" }
]

How can do it?

Problem, react-lazyload render all components at once

Hi I’m using Marvel API and I have this:

export default function App() {
  const [characters, setCharacters] = React.useState([]);
  
  const items = characters.map((character, idx) => (
    <LazyLoad key={idx} once throttle={2000} height={"300"}>
      <Character
        img={
          character.thumbnail.path +
          "/standard_xlarge." +
          character.thumbnail.extension
        }
        name={character.name}
      />
    </LazyLoad>
  ));

  React.useEffect(() => {
    fetch(
      "https://gateway.marvel.com/v1/public/characters?ts=1&apikey=e8aa37188987325dca0c570b01707e2c&hash=d784691874995aae3b9fb373b5a4d1da&limit=50"
    )
      .then((response) => response.json())
      .then((data) => setCharacters(data.data.results));
  }, []);

  React.useEffect(() => {
    forceCheck();
  });

  return (
    <div className="App">
      <h1>My Hero's</h1>
      <div>{characters.length ? items : null}</div>
    </div>
  );
}



function Character({ img, name }) {
  return (
    <div style={{ height: "300px", width: "200px", backgroundColor: "purple" }}>
      <h3>{name}</h3>
      <img height="200" width="200" src={img} />
    </div>
  );
}

My problem is that when the fetch loads all the data the lazyload components load all at once. Pls Help me. I’m using react-lazyload

My codesandbox

How to get the number of elements for elements that satisfy a condition

I’m having a problem. I have an array as shown below:

0: {type: 'Text', id_a: '123789', value: 'The fifth chapter of the World Première Ducati will be held at the Expo Dubai on December 9th.', number: 2, id: 7}
1: {type: 'Image', id_a: '123789', value: 'b_desertx-dwp2022-2-uc336332-high.jpg', number: 3, id: 8}
2: {type: 'Video youtube', id_a: '123789', value: 'https://youtu.be/SnuyDoXxC4g', number: 5, id: 10}
3: {type: 'Image', id_a: '123456', value: 'moto_guzzi_v100_mandello.jpg', number: 3, id: 3}
4: {type: 'Text', id_a: '123456', value: 'The star of the Piaggio group stand is without doubt ... Discover all his secrets with our video', number: 2, id: 2}

Of these I want, for example, to take those that have an id_a equal to 123456 and have me return the value (therefore, referring to id_a = 123456 it must return the two relative arrays) then

3: {type: 'Image', id_a: '123456', value: 'moto_guzzi_v100_mandello.jpg', number: 3, id: 3}
4: {type: 'Text', id_a: '123456', value: 'The star of the Piaggio group stand is without doubt ... Discover all his secrets with our video', number: 2, id: 2}

Except I get this below

{type: 'Image', id_a: '123456', value: 'moto_guzzi_v100_mandello.jpg', number: 3, id: 3}
{type: 'Text', id_a: '123456', value: 'The star of the Piaggio group stand is without doubt ... Discover all her secrets with our video', number: 2, id: 2}

without the numbering in order to be able to retrieve the value (therefore using the value attribute) of each of them.

How can I do this?

   var myArr = JSON.parse(this.responseText);
   for(var i = 0, len = myArr.Items.length; i < len; i++){           
        var id_art = myArr.Items[i].id_a;
        if(id_art == 123456) {
            myArr.Items[i];
            console.log(myArr.Items[i]);
   }

AntD+React: Browserslist config problem. I can’t customize the theme in Ant Design

I am trying to customize the theme in my very first draft of the AntD+React application. The steps I followed are from this official website. enter link description here

F:apppj1antd-demonode_modulesreact-scriptsscriptsstart.js:19


throw `enter code here`err;
  ^
Error [BrowserslistError]: Browserslist config should be a string or an array of strings with browser queries
    at check (F:apppj1antd-demonode_modulesbrowserslistnode.js:67:11)
    at parsePackage (F:apppj1antd-demonode_modulesbrowserslistnode.js:108:5)
    at F:apppj1antd-demonode_modulesbrowserslistnode.js:327:29
    at eachParent (F:apppj1antd-demonode_modulesbrowserslistnode.js:53:18)
    at Object.findConfig (F:apppj1antd-demonode_modulesbrowserslistnode.js:313:20)
    at Function.loadConfig (F:apppj1antd-demonode_modulesbrowserslistnode.js:232:37)
    at checkBrowsers (F:apppj1antd-demonode_modulesreact-dev-utilsbrowsersHelper.js:45:32)
    at Object.<anonymous> (F:apppj1antd-demonode_modulesreact-scriptsscriptsstart.js:78:1)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) {
  browserslist: true
}
error Command failed with exit code 1.

I don’t know how to deal with it. Can anyone help me out, please? Should I just simply change all the files below? If so, then how to change them.

Mongoose pre and post hooks do not work on models created with Model.discriminator

I am using mongoose 6.1.5.

I have a collection containing multiple types of related documents. Here is parameter-descriptor-item.model.js

const mongoose = require('mongoose');

const { Schema } = mongoose;

/** @summary The schema for a parameter item */
const itemSchema = new Schema({
  _id: String,
  name: Object,
});

itemSchema.pre(/^find/, function () {
  // eslint-disable-next-line no-console
  console.log('item pre hit');
});

/** @summary The base model for all parameter items */
module.exports = mongoose.model('Parameters', itemSchema);

ParameterDescriptor model inherits from ParameterDescriptorItem. Here is parameter-descriptor.model.js

const mongoose = require('mongoose');
const ParameterDescriptorItem = require('./parameter-descriptor-item.model');

const { Schema } = mongoose;

/** @summary The schema for additional fields for a project */
const parameterSchema = new Schema({
  direction: {
    type: String,
    enum: ['in', 'out'],
    required: true,
  },
  default: {
    type: Number,
    required: true,
  },
  min: {
    type: Number,
    required: false,
  },
  max: {
    type: Number,
    required: false,
  },
  unit: {
    type: String,
    required: false,
  },
});

parameterSchema.pre(/^find/, function () {
  // eslint-disable-next-line no-console
  console.log('parameter pre hit');
});


/** @summary The model for a parameter descriptor */
module.exports = ParameterDescriptorItem.discriminator('Parameter', parameterSchema);

And here is code to test the use of pre hooks.

const ParameterDescriptorItem = require('./parameter-descriptor-item.model');
const ParameterDescriptor = require('./parameter-descriptor.model');

await ParameterDescriptorItem.find();
// console shows: 'item pre hit'
await ParameterDescriptor.find();
// there is nothing additional in the console. Neither the 'pre' hooks from
// ParameterDescriptorItem or ParameterDescriptor is called.

This is a significant issue for me. Is there a way to address it? Is there a way to add pre and post hooks to models created with Model.discriminator?

How does one request additional scopes using google-auth-library with npm?

Our UI currently prompts the user to login with default scopes enabled.
In order to support a specific feature in our application, we’d like to request additional permissions only if they opt-in for the feature.

This link from Google explains how to do exactly that, but it uses their old javascript library that’s no longer supported.
How can I achieve the same thing with google-auth-library?

Implement a datePicker using javascript

I am trying to implement a date picker on a field , code is shown below but it does not work.

`
@Html.LabelFor(model => model.TimePeriod.EndDate, htmlAttributes: new { @class = “control-label col-md-8” })

@Html.EditorFor(model => model.TimePeriod.EndDate, new { htmlAttributes = new { @class = “datepicker form-control” } })
@Html.ValidationMessageFor(model => model.TimePeriod.EndDate, “”, new { @class = “text-danger” })

                <script type="text/javascript">
                    var currentTime = new Date()
                    var picker = new Pikaday(
                        {
                            field: document.getElementById('EndDate'),
                            firstDay: 1,
                            minDate: new Date('2010-01-01'),
                            maxDate: new Date('2033-12-12'),
                            yearRange: [2010, 2033],
                            numberOfMonths: 1,
                            theme: 'dark-theme'
                        });
                </script>
            </div>`

ExpressJS: Best way to separate routes and accepting params?

I made a Express.js system where the files in the /routes folder are acting as a classic route (but with one file per route)

Example: /routes/get/user.js will be accessible with http://localhost:8080/user (the /get is to separate methods, it can be /post, /put…)

Here’s my entire index.js file: https://pastebin.com/ALtSeHXc

But actually, my problem is that I can’t pass params into the url like https://localhost:8080/user/random_id_here.

With this system, I think the best idea is to find a way to pass params on separated files too, but I don’t know how can it be done…

Here’s an example of one of my separated file:

module.exports = class NameAPI {
    constructor(client) {
        this.client = client
    }

    async run(req, res) {
        // Code here
    }
}

Maybe you’ll have a better system, or a solution for this. Thanks.

amazon-cognito-identity-js setupMFA problems

I am attempting to setup MFA for users after they reset their passcode. The code runs smoothly until I hit mfaSetup, specifically the line user.associateSoftwareToken(). When I pass in ‘this’ instead of user, I get the following error:

Uncaught (in promise) TypeError: callback is undefined

When I pass in user I get Uncaught (in promise) TypeError: callback.onFailure is not a function

I am truly at a loss of what to do and would appreciate any help.

Code below:


  const onSubmit = (event) => {
    event.preventDefault();

    const authDetails = new AuthenticationDetails({
      Username: email,
      Password: password
    });

    const user = new CognitoUser({
      Username: email,
      Pool: UserPool
    });

    user.authenticateUser(authDetails, {
      onSuccess: (data) => {
        console.log('onSuccess:', data);
        if (location.pathname === '/') {
          // navigate('dashboard');
        }
      },
      onFailure: (err) => {
        console.error('onFailure:', err);
      },
      newPasswordRequired: (data) => {
        console.log(data);
        setNewPasscodeRequired(true);
      },
      mfaRequired: (data) => {
        console.log('mfa required');
      },
      mfaSetup: (challengeName, challengeParameters) => {
        console.log('in mfa setup');
        console.log(user.Session);
        user.associateSoftwareToken(user, {
          onFailure: (err) => {
            console.error('onFailure', err);
          },
          onSuccess: (result) => {
            console.log(result);
          }
        });
      },
      selectMFAType: (challengeName, challengeParameters) => {
        console.log(challengeName, challengeParameters);
        user.sendMFASelectionAnswer('SOFTWARE_TOKEN_MFA', this);
      },
      totpRequired: (secretCode) => {
        console.log(secretCode);
        const challengeAnswer = prompt('Please input the TOTP code.', '');
        user.sendMFACode(challengeAnswer, this, 'SOFTWARE_TOKEN_MFA');
      },
      associateSecretCode: (secretCode) => {
        const challengeAnswer = prompt('Please input the TOTP code.', '');
        user.verifySoftwareToken(challengeAnswer, 'My TOTP device', this);
      }
    });
  };

  const onSubmitPasscode = (event) => {
    event.preventDefault();

    if (passwordFirst !== passwordSecond) {
      alert('the two inputs provided are not the same');
    } else {
      const user = new CognitoUser({
        Username: email,
        Pool: UserPool
      });

      const authDetails = new AuthenticationDetails({
        Username: email,
        Password: password
      });

      user.authenticateUser(authDetails, {
        onFailure: (err) => {
          console.error('onFailure:', err);
        },
        onSuccess: (result) => {
          console.log(result);
        },
        newPasswordRequired: (userAttributes, requiredAttributes) => {
          console.log(userAttributes);
          console.log(requiredAttributes);
          delete userAttributes.email_verified;
          delete userAttributes.phone_number_verified;
          delete userAttributes.phone_number;
          console.log(userAttributes);
          user.completeNewPasswordChallenge(passwordFirst, userAttributes, {
            onFailure: (err) => {
              console.error('onFailure:', err);
            },
            onSuccess: (result) => {
              console.log('call result: ', result);
            },
            mfaSetup: (challengeName, challengeParameters) => {
              console.log('in mfa setup');
              console.log(user.Session);
              user.associateSoftwareToken(this, {
                onFailure: (err) => {
                  console.error('onFailure', err);
                },
                onSuccess: (result) => {
                  console.log(result);
                }
              });
            },
            selectMFAType: (challengeName, challengeParameters) => {
              console.log(challengeName, challengeParameters);
              user.sendMFASelectionAnswer('SOFTWARE_TOKEN_MFA', this);
            },
            totpRequired: (secretCode) => {
              console.log(secretCode);
              const challengeAnswer = prompt('Please input the TOTP code.', '');
              user.sendMFACode(challengeAnswer, this, 'SOFTWARE_TOKEN_MFA');
            },
            associateSecretCode: (secretCode) => {
              const challengeAnswer = prompt('Please input the TOTP code.', '');
              user.verifySoftwareToken(challengeAnswer, 'My TOTP device', this);
            }
          });
        }
      });
    }
  };

  const onMFASetup = () => {
    const user = new CognitoUser({
      Username: email,
      Pool: UserPool
    });

    const authDetails = new AuthenticationDetails({
      Username: email,
      Password: passwordFirst
    });

    console.log(email);
    console.log(passwordFirst);

    user.authenticateUser(authDetails, {
      onFailure: (err) => {
        console.error('onFailure:', err);
      },
      onSuccess: (result) => {
        console.log(result);
      },
      mfaSetup: (challengeName, challengeParameters) => {
        user.associateSoftwareToken(this);
      },
      selectMFAType: (challengeName, challengeParameters) => {
        user.sendMFASelectionAnswer('SOFTWARE_TOKEN_MFA', this);
      },
      totpRequired: (secretCode) => {
        const challengeAnswer = prompt('Please input the TOTP code.', '');
        user.sendMFACode(challengeAnswer, this, 'SOFTWARE_TOKEN_MFA');
      },
      mfaRequired: (codeDeliveryDetails) => {
        const verificationCode = prompt('Please input verification code', '');
        user.sendMFACode(verificationCode, this);
      }
    });
  };

  const sendVerificationPin = (event) => {
    event.preventDefault();
    const user = new CognitoUser({
      Username: email,
      Pool: UserPool
    });

    user.forgotPassword({
      onSuccess: (result) => {
        console.log('call result: ', result);
      },
      onFailure: (err) => {
        alert(err);
      }
    });
  };

  const onResetPassword = (event) => {
    event.preventDefault();

    console.log('in reset');

    const user = new CognitoUser({
      Username: email,
      Pool: UserPool
    });

    console.log('user made');

    if (passwordFirst !== passwordSecond) {
      alert('the two inputs provided are not the same');
    } else {
      console.log('inputs are the same');
      user.confirmPassword(pin, passwordSecond, {
        onSuccess() {
          console.log('Password confirmed!');
          window.location.reload(true);
        },
        onFailure(err) {
          console.log('Password not confirmed!');
          console.log(err);
        }
      });
    }
  };

  return (
    <div>
      {!newPasscodeRequired && !forgotPassword && !setupMFA && (
        <div>
          <form onSubmit={onSubmit}>
            <input type="text" required value={email} onChange={(e) => setEmail(e.target.value)} />
            <input
              type="text"
              required
              value={password}
              onChange={(e) => setPassword(e.target.value)}
            />
            <button type="submit">Login</button>
          </form>
          <button onClick={(e) => setForgotPassword(true)}>
            <Typography sx={{ paddingX: 5 }}>Forgot password?</Typography>
          </button>
        </div>
      )}
      {newPasscodeRequired && (
        <div>
          <form onSubmit={onSubmitPasscode}>
            <Typography>New Password</Typography>
            <input type="text" required onChange={(e) => setPasswordFirst(e.target.value)} />
            <Typography>New Password Again</Typography>
            <input type="text" required onChange={(e) => setPasswordSecond(e.target.value)} />
            <Typography>New Password Requirements</Typography>
            <Typography>
              At least 8 characters long, requiring upper and lower case letters, numbers, and
              special characters
            </Typography>
            <button type="submit">Submit new passcode</button>
          </form>
        </div>
      )}
      {forgotPassword && !newPasscodeRequired && (
        <div>
          <form onSubmit={sendVerificationPin}>
            <Typography>Please input the email for the account</Typography>
            <input type="text" required onChange={(e) => setEmail(e.target.value)} />
            <button type="submit">Send verification pin</button>
          </form>
          <form onSubmit={onResetPassword}>
            <Typography>Input the verification pin sent to your email below</Typography>
            <input type="text" required onChange={(e) => setPin(e.target.value)} />
            <Typography>New Password</Typography>
            <input type="text" required onChange={(e) => setPasswordFirst(e.target.value)} />
            <Typography>New Password Again</Typography>
            <input type="text" required onChange={(e) => setPasswordSecond(e.target.value)} />
            <Typography>New Password Requirements</Typography>
            <Typography>
              At least 8 characters long, requiring upper and lower case letters, numbers, and
              special characters
            </Typography>
            <button type="submit">Reset Password</button>
          </form>
        </div>
      )}
      {setupMFA && (
        <div>
          <div>SetupMFA</div>
          <button onClick={(e) => onMFASetup()}>Generate QR Code</button>
        </div>
      )}
    </div>
  );
};

How to get Vuex to add a urls from a Firebase getDownloadURL promise in Vue

I have an app that is using Firestore Storage JavaScript version 9, Vuex 4, and Vue 3. It needs to download image urls from Firestore Storage to display on an image tag.

My Firestore Storage is structured listings/${userID}/ with image files of that userID in it.

I have one component that needs image urls and is trying to get them from Firestore (line 35).

Listing.vue

<template>
  <div class="listing__container">
    <div class="listing__container_info">
      <h1 class="listing__header">{{ listing.title }}</h1>
      <p class="listing__paragraph">{{ listing.description }}</p>
      <div v-if="!isNaN(listing.stars)">
        <icon-star-line v-for="star in Number(listing.stars)" class="listing__icon" />
      </div>
    </div>
    <div class="listing__container_image">
      <img class="listing__image" :src="listingImageUrls[0]" alt="an image" />
    </div>
    <div class="listing__container_image">
      <img :src="listingImageUrls[1]" alt />
    </div>
  </div>
</template>

<script setup>
const props = defineProps({
  listing: Object,
})
import { computed, ref, toRefs } from 'vue'
import IconStarLine from '~icons/clarity/star-solid'
import { useStore } from 'vuex'

const store = useStore()
const { listing } = toRefs(props)

const userId = 'vlM46kRbhym3a3PW76t4'
store.dispatch('fetchUser', userId)
const user = computed(() => store.state.user)

store.dispatch('fetchListingImageUrls', user.value.id)
const listingImageUrls = computed(() => store.state.listingImageUrls)
</script>

<style lang="postcss">
.listing {
  @apply border-2 border-ui-100 rounded-3xl flex;
  &__header {
    @apply text-primary-900 text-3xl font-bold;
  }
  &__paragraph {
    @apply font-normal;
  }
  &__icon {
    @apply text-primary-500 inline;
  }
  &__container {
    @apply flex;
    &_info {
    }
    &_image {
      @apply w-52 h-36 overflow-hidden;
      .listing__image {
        /* @apply relative top-1/2 left-1/2; */
      }
    }
  }
}
</style>

I have another Vuex script that handles state and is calling getDownloadURL (line 57 to end of file)

store/index.js

import { createStore } from 'vuex'
import { initializeApp } from 'firebase/app'
import { getFirestore, collection, doc, addDoc, getDoc, getDocs, Timestamp } from 'firebase/firestore'
import { getStorage, ref, getDownloadURL, list } from 'firebase/storage'

const firebaseApp = initializeApp({
  apiKey: 'AIzaSyDANDyEb-LZn9OqcOECf93oLL48J1O2sWQ',
  authDomain: 'sploots-d050d.firebaseapp.com',
  projectId: 'sploots-d050d',
  storageBucket: 'sploots-d050d.appspot.com',
  messagingSenderId: '666246994336',
  appId: '1:666246994336:web:e6c1f5abd0467a63d22cc5',
  measurementId: 'G-173Y64V43X'
})

const db = getFirestore()
const storage = getStorage()

export const store = createStore({
  state: {
    user: {},
    listings: [],
    listingImageUrls: []
  },
  mutations: {
    addUser(state, user) {
      state.user = user
    },
    addListings(state, listings) {
      state.listings = listings
    },
    addListingImageUrls(state, urls) {
      state.listingImageUrls = urls
    }
  },
  actions: {
    async fetchUser({ commit }, userId) {
      const userRef = doc(db, `/users/${userId}`)
      const userSnap = await getDoc(userRef)
      commit('addUser', userSnap.data())
      if (!userSnap.exists()) {
        // doc.data() will be undefined in this case
        console.log("No such document!")
      }
    },
    async fetchListings({ commit }, userId) {
      const listingsRef = collection(db, `/users/${userId}/listings`)
      const listingsSnap = await getDocs(listingsRef)
      const listingsClean = []
      listingsSnap.forEach(doc => {
        let docClean = doc.data()
        listingsClean.push(docClean)
      })
      const listings = listingsClean
      commit('addListings', listings)
    },
    async fetchListingImageUrls({ commit }, userId) {
      const folderRef = await ref(storage, `listings/${userId}`)
      const imagesList = await list(folderRef)
      commit('addListingImageUrls', await getUrls(imagesList))
    },
  }
})

const getUrls = async (imagesList) => {
  const urls = imagesList.items.map(async imageRef => {
    const url = await getDownloadURL(imageRef)
    console.log(url)
    return url
  })
  return urls
}

And here is my package.json

{
  "name": "someApp",
  "version": "0.0.0",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "serve": "vite preview"
  },
  "dependencies": {
    "firebase": "^9.4.1",
    "postcss-import": "^14.0.2",
    "vue": "^3.2.16",
    "vue-router": "^4.0.12",
    "vuex": "^4.0.2"
  },
  "devDependencies": {
    "@iconify-json/clarity": "^1.0.1",
    "@vitejs/plugin-vue": "^1.9.3",
    "autoprefixer": "^10.4.0",
    "eslint": "^8.2.0",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-vue": "^8.0.3",
    "postcss": "^8.4.4",
    "postcss-nested": "^5.0.6",
    "prettier": "^2.4.1",
    "tailwindcss": "^2.2.19",
    "unplugin-icons": "^0.12.23",
    "vite": "^2.6.4"
  }
}

Listing.vue is calling fetchListingImageURls on line 35 from store/index.js (line 57 and below) to get image urls from Firebase Storage. With this code the images don’t show. If I log listingImageUrls.value in listings.vue it is a proxy with a target that is an empty array. If I log urls from the store in getURLs it shows the urls as a fulfilled promise.

What is the issue here? I am pretty new to Vuex and Firestore so I think I am probably doing something wrong with one of those, or, as always, I am butchering something with my async calls.

Any help is appreciated 🙂

How to make a double await Node.js

Hi I can´t find a solution to my problem of functions in cascade,

Service A

print(await serviceB.methodA(myParameter));

Service B

async methodA(MyParameter){

            await methodB(MyParamter).then((value) =>{
                serviceA.methodC(value).then((result)=>{
                   console.log('result');
                   return result;
               });

            }
         );
         console.log('hi');
    }

So the output is

hi
undefined
result 

How I can wait to the second cascade of the then?? Because when getting undefined is broking my service A that must get “result”