tags: JavaScript Maria DB Python

Pokemon DB Part 1
Pokemon DB Part 2
Pokemon DB Part 3
Pokemon DB Part 4
Pokemon DB Part 5

Final functions

This is it the final part of the code -- I will not go through the askCorrectPokemon function - this should be clear by now

//Ask if Pokemon is the correct one
async function askCorrectPokemon() {
  try {
    let yesNO;
    do {
      // Wait for the user's input
      yesNO = await question(`Ist das Pokemon korrekt? (ja/nein)`)        
      // Check if userInput is allowed
      if (!(yesNO === 'ja' || yesNO === 'nein')) {
         console.log(`Nicht korrekt bitte ja oder nein`);        
      }
    } while (!(yesNO === 'ja' || yesNO === 'nein'));        
    // Return the user's input
    console.log(yesNO)
    return yesNO;
  } finally {
    // Close the interface
    rl.close();
  }
}

//Check if Pokemon is already known
async function getFiles() { 
    ReadCard = await fetchData()
    PokeCorrect = await askCorrectPokemon()
    fileList = await fs.readdirSync('JSON_Files')
    newcard = `${PokeName.replace(/:/g, '_')}_${SetID}_${CardNo}.json`

    if (PokeCorrect === 'nein') {
      console.log("Bitte Programm nochmal starten und korrektes Pokemon eintragen")
      return null
    } else {
    try {
      if (fileList.includes(newcard)) {
        console.log(`Pokemon ${newcard} ist vorhanden`)
      } else {
        console.log(`Pokemon ${newcard} ist ${redColor}NICHT${resetColor} vorhanden und Datei wird ${greenColor}angelegt${resetColor}`)
        fs.writeFileSync(`JSON_Files/${PokeName.replace(/:/g, '_')}_${SetID}_${CardNo}.json`, JSON.stringify(data3, null, 2))
      }
    } catch (error) {
      console.error('You are a failure!', error);
      return null;
  }}}

async function main() {
    const result = await getFiles()       
}
main()

Instead we'll concentrate on getFiles function

First we start our functions - fetchData & askCorrectPokemon! We will also create a fileList where we read all files from the subfolder JSON_Files (we will be storing new Pokemon JSONs there)
Then we create our Naming for our JSONs here we use the following

  • Pokemon Name (the replace part will remove any : and replace them with_ which will cause Problems with naming and storing )
  • SetID
  • Card Number

The final result will look something like this

Abra_sv03.5_63.json

After this is done we will check what if our user confirmed the found Pokemon with PokeCorrect from our ask function before.
In case of no we will terminate the Program otherwise we check if the JSON is already in our file list.

If yes --> terminate program and tell user Pokemon is already in folder

If no --> write JSON file in folder JSON_Files (and yes we could have used variable newcard but for some case I forgot to do so)

We then create our function main which we will call afterwards!

FINALLY FINISHED!!!!!

Here the complete code - I hope you have learned something!

// import the SDK in commonJS
const TCGdex = require('@tcgdex/sdk').default;
const fs = require('fs');
const readline = require('readline');

// Instantiate the SDK
const tcgdex = new TCGdex('de');

// Create an interface for reading from the console
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
    })

const question = (prompt) => new Promise((resolve) => {
    rl.question(prompt, resolve);
    })

//Defining colors
const textColor = '\x1b[36m'; // Cyan color
const resetColor = '\x1b[0m'; // Reset color to default
const redColor = '\x1b[31m'; //Red Color
const greenColor = '\x1b[32m' //Green Color

//Question Function
function askQuestion(question) {
  return new Promise(resolve => {
    rl.question(question, resolve);
  });
}

//Input CardNo
async function askForCard() {
  while (true) {
    const input = await askQuestion('Bitte Kartennummer eingeben: ')
    CardNo = parseFloat(input)

    if (!isNaN(CardNo)) {
      console.log(`Es wurde ${CardNo} eingegeben`)
      rl.close
      return CardNo          
    } else {
      console.log("Keine Nummer bitte Nummer eingeben")
    }
  }
}
//Input SetCount
async function askForSet() {
  while (true) {
    const input = await askQuestion('Bitte Setnummer eingeben: ')
    SetCount = parseFloat(input)

    if (!isNaN(SetCount)) {
      console.log(`Es wurde ${SetCount} eingegeben`)
      rl.close
      return SetCount          
    } else {
      console.log("Keine Nummer bitte Nummer eingeben")
    }
  }
}

//Check for Duplicate Sets
async function checkDupes() {   
  CardNo = await askForCard()
  SetCount = await askForSet()
  //Check for Duplicate Official Card Counts
  try {
      const sets = await tcgdex.fetch('sets');
      const duplicateSets = [];

      // Check for Duplicate Official Card Counts of SetCount
      for (const item of sets) {
        const officialCount = item.cardCount.official;

        if (officialCount === SetCount) {
          duplicateSets.push({ SetID: item.id, Name: item.name });
        }
      }

      if (duplicateSets.length > 1) {
        console.log('Hier sind die mehrfachen Sets:');
        duplicateSets.forEach((set, index) => {
          console.log(`${index + 1}. SetID: ${set.SetID}, Name: ${set.Name}`);
        });

        try {
          let choice;

          do {
            // Wait for the user's input
            choice = await question(`Welches Set willst du verwenden (1-${duplicateSets.length}): `);
            choice = parseInt(choice);

            // Check if userInput is valid
            if (isNaN(choice) || choice < 1 || choice > duplicateSets.length) {
              console.log(`Invalid input. Please enter a number between 1 and ${duplicateSets.length}.`);
            }
          } while (isNaN(choice) || choice < 1 || choice > duplicateSets.length);

          // Return the chosen SetID
          return duplicateSets[choice - 1].SetID;

        } finally {
          // Enyjoy life
        }

      } else {
        //Return the only SetId
        console.log('Es gibt keine mehrfachen Sets für SetCount', SetCount);
        return duplicateSets[0].SetID;

      } 
    } catch (error) {
      console.error('Error fetching sets:', error);
      return null;
    }
}

//Fetch Data
async function fetchData() {
    try {
        SetID = await checkDupes()
        data3 = await tcgdex.fetch('sets', SetID, CardNo)        
        //Check if we Card is already in TCGdex        
        if (data3 !== undefined) {
            //Get Pokemon Name
            PokeName = data3.name
            //Get Rarity of Card
            rarity = data3.rarity
            //Get SetID
            SetID = data3.set.id
            //Get Set Name
            SetID_Name = data3.set.name
            //Inform User
            console.log(`Set ID ist ${textColor}${SetID}${resetColor}`)
            console.log(`Set Name ist ${textColor}${SetID_Name}${resetColor}`)
            console.log(`Unser Pokemon ist ${textColor}${PokeName}${resetColor}`)
            console.log(`Unser Pokemon ist ${textColor}${rarity}${resetColor}`)
            //Write Pokemon in JSON File
            //fs.writeFileSync(`JSON_Files/${PokeName}_${SetID}_${CardNo}.json`, JSON.stringify(data3, null, 2))
            //console.log(`Datei ${PokeName}_${SetID}_${CardNo}.json geschrieben`)
            return data3
        //Return Error if Set does NOT contain DATA
        } else {
            console.log(SetID,'ist leider nicht befüllt')
        } 
    } catch (error) {
        console.error('Error fetching sets:', error);
        return null;
    }}

//Ask if Pokemon is the correct one
async function askCorrectPokemon() {
  try {
    let yesNO;
    do {
      // Wait for the user's input
      yesNO = await question(`Ist das Pokemon korrekt? (ja/nein)`)        
      // Check if userInput is allowed
      if (!(yesNO === 'ja' || yesNO === 'nein')) {
         console.log(`Nicht korrekt bitte ja oder nein`);        
      }
    } while (!(yesNO === 'ja' || yesNO === 'nein'));        
    // Return the user's input
    console.log(yesNO)
    return yesNO;
  } finally {
    // Close the interface
    rl.close();
  }
}

//Check if Pokemon is already known
async function getFiles() { 
    ReadCard = await fetchData()
    PokeCorrect = await askCorrectPokemon()
    fileList = await fs.readdirSync('JSON_Files')
    newcard = `${PokeName.replace(/:/g, '_')}_${SetID}_${CardNo}.json`

    if (PokeCorrect === 'nein') {
      console.log("Bitte Programm nochmal starten und korrektes Pokemon eintragen")
      return null
    } else {
    try {
      if (fileList.includes(newcard)) {
        console.log(`Pokemon ${newcard} ist vorhanden`)
      } else {
        console.log(`Pokemon ${newcard} ist ${redColor}NICHT${resetColor} vorhanden und Datei wird ${greenColor}angelegt${resetColor}`)
        fs.writeFileSync(`JSON_Files/${PokeName.replace(/:/g, '_')}_${SetID}_${CardNo}.json`, JSON.stringify(data3, null, 2))
      }
    } catch (error) {
      console.error('You are a failure!', error);
      return null;
  }}}

async function main() {
    const result = await getFiles()
    //const result = await askCorrectPokemon()
    //console.log(data3)    
}
main()