This is a code that uses the Scryfall API to search for Magic the Gathering cards based on user input. The first line prompts the user to enter the name of the card they want to search for. The second line sends a request to the Scryfall API with the user's query, and the third line converts the response to JSON format.
The code then checks if the API returned any search results. If there are no results, the code outputs "No results found." If there is only one result, the code creates a new record in a table called "Cards" in a service like Airtable with the card's information, and outputs a confirmation message. If there are multiple results, the code prompts the user to select the correct card from a list, and then creates a new record for that card in the "Cards" table.
The issue arises when after the list of potential cards is loaded as search results, if it cant parse the card name it gives a bunch of options, no matter what option you choose, it wont actually add the choice as a record. What could I do to modify it to add the card as a record?
let userQuery = await input.textAsync('Enter the name of the Magic the Gathering card you want to search for:');
let scryfallResponse = await fetch(`https://api.scryfall.com/cards/search?q=${encodeURIComponent(userQuery)}`);
let cardList = await scryfallResponse.json();
if (cardList.data.length === 0) {
output.text('No results found.');
} else if (cardList.data.length === 1) {
let cardData = cardList.data[0];
let newCard = await base.getTable('Cards').createRecordAsync({
'Card Name': cardData.name,
'Mana Cost': cardData.mana_cost,
'Card Type': cardData.type_line,
'Power': cardData.power,
'Toughness': cardData.toughness,
'Oracle Text': cardData.oracle_text,
'Card Image': cardData.image_uris.normal,
});
// @ts-ignore
output.text(`The card "${newCard.getCellValueAsString('Card name')}" has been added to the "Cards" table.`);
} else {
let cardNames = cardList.data.map(card => card.name);
let selectedIndex = await input.buttonsAsync('Select the correct card:', cardNames);
console.log(`selectedIndex = ${selectedIndex}`);
if (selectedIndex !== -1) {
console.log(`cardNames[selectedIndex] = ${cardNames[selectedIndex]}`);
let selectedCard = cardList.data.find(card => card.name === cardNames[selectedIndex]);
console.log(`selectedCard = ${JSON.stringify(selectedCard)}`);
if (selectedCard) {
let newCard = await base.getTable('Cards').createRecordAsync({
'Card Name': selectedCard.name,
'Mana Cost': selectedCard.mana_cost,
'Card Type': selectedCard.type_line,
'Power': selectedCard.power,
'Toughness': selectedCard.toughness,
'Oracle Text': selectedCard.oracle_text,
'Card Image': selectedCard.image_uris.normal,
});
output.text(`The card "${newCard.getCellValueAsString('Card name')}" has been added to the "Cards" table.`);
} else {
output.text('No card was selected.');
}
} else {
output.text('No card was selected.');
}
}