Rick1Marques / star-wars-bazar-app

https://star-wars-bazaar-gamma-three.vercel.app/
2 stars 2 forks source link

add data basa #17

Closed Rick1Marques closed 9 months ago

vercel[bot] commented 9 months ago

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
star-wars-bazar-app ✅ Ready (Inspect) Visit Preview 💬 Add feedback Sep 26, 2023 10:18am
miriam-ertl commented 9 months ago

👍🏻 Only some clean code snippits could be optimized.

moonwave99 commented 9 months ago

A couple of comments:

The intuition you had for generating the listings is right! You can write a sample function for that - putting it all together in the utils:

// db/utils.js
export function sampleMany(array = [], quantity = 1) {
  // SEE: https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
  const shuffled = array.toSorted(() => Math.random() - 0.5);
  return shuffled.slice(0, quantity);
}

// recycle the function above!
export function sample(array = []) {
  return sampleMany(array, 1)[0];
}

export function random(max, min) {
  return Math.floor(Math.random() * (max - min) + min);
}

Now the users from your fixture files can become just:

import { random } from './utils.js';

export const users = defaultUsers.map((user) => ({
  ...user,
  credits: random(1000000, 500000),
  listings: Array.from({ length: random(15, 5) }, () => ({
    price: random(5000000, 200000),
  })),
}));

(Array.from({ length: x }, () => ...) is a quick way to get an array of length x in JS. the callback function works like in .map())

Finally your import.js script:

import { sampleMany, sample, random } from "./utils.js";

...

const createdStarships = await Starship.insertMany(starships);

...

await Promise.all(
  users.map(async ({ listings, ...user }, index) => {
    console.log(`Creating user: ${index}...`);
    const newUser = await User.create(user);

    console.log(`Saving listings for user: ${index}...`);

    const savedListings = await Listing.insertMany(
      listings.map((listing) => ({
        ...listing,
        user: newUser._id,
        starship: sample(createdStarships),
      }))
    );

    newUser.listings = savedListings.map((x) => x._id);
    newUser.starships = sampleMany(createdStarships, random(5, 1));

    await newUser.save();
  })
);

Final: make sure that your listings and starships are consistent - I assume you can list starships you don't own!

Little trick: