From a0bd9dd5064692ea409306f7ad7b24090f296e51 Mon Sep 17 00:00:00 2001 From: felixtanhm Date: Tue, 7 May 2024 09:26:45 +0800 Subject: [PATCH] chore: pokemon seeding completed --- .../server/models/pokeDetails.js | 13 +- .../server/models/{pokemon.js => pokemons.js} | 2 + .../server/populateDb.js | 254 ++---------------- 3 files changed, 35 insertions(+), 234 deletions(-) rename full-stack-javascript/21-inventory-application/server/models/{pokemon.js => pokemons.js} (84%) diff --git a/full-stack-javascript/21-inventory-application/server/models/pokeDetails.js b/full-stack-javascript/21-inventory-application/server/models/pokeDetails.js index e6715d6..000dc6f 100644 --- a/full-stack-javascript/21-inventory-application/server/models/pokeDetails.js +++ b/full-stack-javascript/21-inventory-application/server/models/pokeDetails.js @@ -9,8 +9,8 @@ const PokeDetailsSchema = new Schema({ hp: { type: Number, required: true }, attack: { type: Number, required: true }, defense: { type: Number, required: true }, - specialAttack: { type: Number, required: true }, - specialDefense: { type: Number, required: true }, + special_attack: { type: Number, required: true }, + special_defense: { type: Number, required: true }, speed: { type: Number, required: true }, abilities: { type: [String], @@ -18,13 +18,8 @@ const PokeDetailsSchema = new Schema({ return null; }, }, - evolvesTo: { - type: [Schema.Types.ObjectId], - ref: "Pokemon", - default: () => { - return null; - }, - }, + created_at: { type: Date, default: Date.now() }, + last_modified: { type: Date, default: Date.now() }, }); // Export model diff --git a/full-stack-javascript/21-inventory-application/server/models/pokemon.js b/full-stack-javascript/21-inventory-application/server/models/pokemons.js similarity index 84% rename from full-stack-javascript/21-inventory-application/server/models/pokemon.js rename to full-stack-javascript/21-inventory-application/server/models/pokemons.js index d6b9399..62f0bbc 100644 --- a/full-stack-javascript/21-inventory-application/server/models/pokemon.js +++ b/full-stack-javascript/21-inventory-application/server/models/pokemons.js @@ -13,6 +13,8 @@ const PokeSchema = new Schema({ }, avatar: { type: String, required: true }, details: { type: Schema.Types.ObjectId, ref: "PokeDetails", required: true }, + created_at: { type: Date, default: Date.now() }, + last_modified: { type: Date, default: Date.now() }, }); // Virtual for pokemon's URL diff --git a/full-stack-javascript/21-inventory-application/server/populateDb.js b/full-stack-javascript/21-inventory-application/server/populateDb.js index c8b7ecf..98209b3 100644 --- a/full-stack-javascript/21-inventory-application/server/populateDb.js +++ b/full-stack-javascript/21-inventory-application/server/populateDb.js @@ -8,12 +8,9 @@ console.log( // Get arguments passed on command line const userArgs = process.argv.slice(2); -const Pokemon = require("./models/pokemon"); +const Pokemons = require("./models/pokemons"); const PokeDetails = require("./models/pokeDetails"); -const pokemon = []; -const pokeDetails = []; - const mongoose = require("mongoose"); mongoose.set("strictQuery", false); @@ -26,15 +23,26 @@ async function main() { await mongoose.connect(mongoDB); console.log("Debug: Should be connected?"); const response = await axios.get( - "https://pokeapi.co/api/v2/pokemon/?limit=1" + "https://pokeapi.co/api/v2/pokemon/?limit=151" ); let expandList = []; if (response.status === 200) { expandList = await Promise.all( response.data.results.map(async (item) => { try { - const singleResponse = await axios.get(item.url); - item = { ...item, ...singleResponse.data }; + const details = await axios.get(item.url); + item = { ...item, ...details.data }; + return item; + } catch (error) { + console.log({ ...item, error }); + } + }) + ); + expandList = await Promise.all( + expandList.map(async (item) => { + try { + const species = await axios.get(item.species.url); + item = { ...item, ...species.data }; return item; } catch (error) { console.log({ ...item, error }); @@ -42,27 +50,15 @@ async function main() { }) ); } - // console.log("-----LIST START-----"); - // console.log(expandList); - // console.log("-----LIST END-----"); - console.log(`List Length: ${expandList.length}`); - const { newPokemon, newPokeDetails } = processPokeData(expandList[0]); - - const detailsRef = await createPokeDetails(newPokeDetails); - - await createPokemon(newPokemon, detailsRef); - // await createGenres(); - // await createAuthors(); - - console.log("Debug: Closing mongoose"); - mongoose.connection.close(); + expandList.forEach(async (item) => { + const { newPokemon, newPokeDetails } = processPokeData(item); + const detailsRef = await createPokeDetails(newPokeDetails); + await createPokemon(newPokemon, detailsRef); + }); } function processPokeData(data) { - console.log("Processing Pokemon:"); - console.log(data); - const newPokemon = { name: data.name, dexId: data.order, @@ -75,222 +71,30 @@ function processPokeData(data) { const newPokeDetails = { height: data.height, weight: data.weight, - // has_gender: data.height, + has_gender: Boolean(data.gender_rate), hp: data.stats[0].base_stat, attack: data.stats[1].base_stat, defense: data.stats[2].base_stat, - specialAttack: data.stats[3].base_stat, - specialDefense: data.stats[4].base_stat, + special_attack: data.stats[3].base_stat, + special_defense: data.stats[4].base_stat, speed: data.stats[5].base_stat, abilities: data.abilities.map((aObj) => { return aObj.ability.name; }), - // evolvesTo: [{ type: Schema.Types.ObjectId, ref: "Pokemon" }], }; return { newPokemon, newPokeDetails }; } async function createPokeDetails(newPokeDetails) { const pokeDetails = new PokeDetails(newPokeDetails); - console.log(`\n Poke Details:`); - console.log(pokeDetails); + await pokeDetails.save(); + console.log(`\nPoke Details Added`); return pokeDetails; } async function createPokemon(newPokemon, detailsRef) { - const pokemon = new Pokemon({ ...newPokemon, details: detailsRef }); - console.log(`\n Pokemon:`); - console.log(pokemon); -} - -// We pass the index to the ...Create functions so that, for example, -// genre[0] will always be the Fantasy genre, regardless of the order -// in which the elements of promise.all's argument complete. -async function genreCreate(index, name) { - const genre = new Genre({ name: name }); - await genre.save(); - genres[index] = genre; - console.log(`Added genre: ${name}`); -} - -async function authorCreate(index, first_name, family_name, d_birth, d_death) { - const authordetail = { first_name: first_name, family_name: family_name }; - if (d_birth != false) authordetail.date_of_birth = d_birth; - if (d_death != false) authordetail.date_of_death = d_death; - - const author = new Author(authordetail); - - await author.save(); - authors[index] = author; - console.log(`Added author: ${first_name} ${family_name}`); -} - -async function bookCreate(index, title, summary, isbn, author, genre) { - const bookdetail = { - title: title, - summary: summary, - author: author, - isbn: isbn, - }; - if (genre != false) bookdetail.genre = genre; - - const book = new Book(bookdetail); - await book.save(); - books[index] = book; - console.log(`Added book: ${title}`); -} - -async function bookInstanceCreate(index, book, imprint, due_back, status) { - const bookinstancedetail = { - book: book, - imprint: imprint, - }; - if (due_back != false) bookinstancedetail.due_back = due_back; - if (status != false) bookinstancedetail.status = status; - - const bookinstance = new BookInstance(bookinstancedetail); - await bookinstance.save(); - bookinstances[index] = bookinstance; - console.log(`Added bookinstance: ${imprint}`); -} - -async function createGenres() { - console.log("Adding genres"); - await Promise.all([ - genreCreate(0, "Fantasy"), - genreCreate(1, "Science Fiction"), - genreCreate(2, "French Poetry"), - ]); -} - -async function createAuthors() { - console.log("Adding authors"); - await Promise.all([ - authorCreate(0, "Patrick", "Rothfuss", "1973-06-06", false), - authorCreate(1, "Ben", "Bova", "1932-11-8", false), - authorCreate(2, "Isaac", "Asimov", "1920-01-02", "1992-04-06"), - authorCreate(3, "Bob", "Billings", false, false), - authorCreate(4, "Jim", "Jones", "1971-12-16", false), - ]); -} - -async function createBooks() { - console.log("Adding Books"); - await Promise.all([ - bookCreate( - 0, - "The Name of the Wind (The Kingkiller Chronicle, #1)", - "I have stolen princesses back from sleeping barrow kings. I burned down the town of Trebon. I have spent the night with Felurian and left with both my sanity and my life. I was expelled from the University at a younger age than most people are allowed in. I tread paths by moonlight that others fear to speak of during day. I have talked to Gods, loved women, and written songs that make the minstrels weep.", - "9781473211896", - authors[0], - [genres[0]] - ), - bookCreate( - 1, - "The Wise Man's Fear (The Kingkiller Chronicle, #2)", - "Picking up the tale of Kvothe Kingkiller once again, we follow him into exile, into political intrigue, courtship, adventure, love and magic... and further along the path that has turned Kvothe, the mightiest magician of his age, a legend in his own time, into Kote, the unassuming pub landlord.", - "9788401352836", - authors[0], - [genres[0]] - ), - bookCreate( - 2, - "The Slow Regard of Silent Things (Kingkiller Chronicle)", - "Deep below the University, there is a dark place. Few people know of it: a broken web of ancient passageways and abandoned rooms. A young woman lives there, tucked among the sprawling tunnels of the Underthing, snug in the heart of this forgotten place.", - "9780756411336", - authors[0], - [genres[0]] - ), - bookCreate( - 3, - "Apes and Angels", - "Humankind headed out to the stars not for conquest, nor exploration, nor even for curiosity. Humans went to the stars in a desperate crusade to save intelligent life wherever they found it. A wave of death is spreading through the Milky Way galaxy, an expanding sphere of lethal gamma ...", - "9780765379528", - authors[1], - [genres[1]] - ), - bookCreate( - 4, - "Death Wave", - "In Ben Bova's previous novel New Earth, Jordan Kell led the first human mission beyond the solar system. They discovered the ruins of an ancient alien civilization. But one alien AI survived, and it revealed to Jordan Kell that an explosion in the black hole at the heart of the Milky Way galaxy has created a wave of deadly radiation, expanding out from the core toward Earth. Unless the human race acts to save itself, all life on Earth will be wiped out...", - "9780765379504", - authors[1], - [genres[1]] - ), - bookCreate( - 5, - "Test Book 1", - "Summary of test book 1", - "ISBN111111", - authors[4], - [genres[0], genres[1]] - ), - bookCreate( - 6, - "Test Book 2", - "Summary of test book 2", - "ISBN222222", - authors[4], - false - ), - ]); -} - -async function createBookInstances() { - console.log("Adding authors"); - await Promise.all([ - bookInstanceCreate( - 0, - books[0], - "London Gollancz, 2014.", - false, - "Available" - ), - bookInstanceCreate(1, books[1], " Gollancz, 2011.", false, "Loaned"), - bookInstanceCreate(2, books[2], " Gollancz, 2015.", false, false), - bookInstanceCreate( - 3, - books[3], - "New York Tom Doherty Associates, 2016.", - false, - "Available" - ), - bookInstanceCreate( - 4, - books[3], - "New York Tom Doherty Associates, 2016.", - false, - "Available" - ), - bookInstanceCreate( - 5, - books[3], - "New York Tom Doherty Associates, 2016.", - false, - "Available" - ), - bookInstanceCreate( - 6, - books[4], - "New York, NY Tom Doherty Associates, LLC, 2015.", - false, - "Available" - ), - bookInstanceCreate( - 7, - books[4], - "New York, NY Tom Doherty Associates, LLC, 2015.", - false, - "Maintenance" - ), - bookInstanceCreate( - 8, - books[4], - "New York, NY Tom Doherty Associates, LLC, 2015.", - false, - "Loaned" - ), - bookInstanceCreate(9, books[0], "Imprint XXX2", false, false), - bookInstanceCreate(10, books[1], "Imprint XXX3", false, false), - ]); + const pokemon = new Pokemons({ ...newPokemon, details: detailsRef }); + await pokemon.save(); + console.log(`Pokemon: ${pokemon.name}`); + console.log(`-------------`); }