feat(*): Update pokedex entry data structure and re-add error handling

This commit is contained in:
Josh Creek
2024-07-14 16:16:18 +01:00
parent 90f6bd6e75
commit 7467a4425f
9 changed files with 21000 additions and 4187 deletions
@@ -43,14 +43,33 @@
{/if} {/if}
<div class="bg-white text-black rounded-lg p-4"> <div class="bg-white text-black rounded-lg p-4">
{#if showForms}
<p><strong>Box:</strong> {pokedexEntry.boxPlacementForms.box}</p>
<p><strong>Row:</strong> {pokedexEntry.boxPlacementForms.row}</p>
<p><strong>Column:</strong> {pokedexEntry.boxPlacementForms.column}</p>
<p><strong>Can Gigantamax:</strong> {pokedexEntry.canGigantamax ? 'Yes' : 'No'}</p>
{:else}
<p><strong>Box:</strong> {pokedexEntry.boxPlacement.box}</p> <p><strong>Box:</strong> {pokedexEntry.boxPlacement.box}</p>
<p><strong>Row:</strong> {pokedexEntry.boxPlacement.row}</p> <p><strong>Row:</strong> {pokedexEntry.boxPlacement.row}</p>
<p><strong>Column:</strong> {pokedexEntry.boxPlacement.column}</p> <p><strong>Column:</strong> {pokedexEntry.boxPlacement.column}</p>
{#if showForms}
<p><strong>Can Gigantamax:</strong> {pokedexEntry.canGigantamax ? 'Yes' : 'No'}</p>
{/if} {/if}
{#if pokedexEntry.notes}
<p><strong>Notes:</strong> {pokedexEntry.notes}</p> {#if pokedexEntry.evolutionInformation}
<p><strong>Evolution Info:</strong> {pokedexEntry.evolutionInformation}</p>
{/if}
{#if pokedexEntry.catchInformation.length > 0}
<p><strong>Catch Info:</strong></p>
<ul class="list-disc list-inside">
{#each pokedexEntry.catchInformation as info}
<li>
<ul>
<li><strong>Location:</strong> {info.game}</li>
<li><strong>Method:</strong> {info.location}</li>
<li><strong>Level:</strong> {info.notes}</li>
</ul>
</li>
{/each}
</ul>
{/if} {/if}
</div> </div>
</div> </div>
+9730 -1390
View File
File diff suppressed because it is too large Load Diff
+20
View File
@@ -3,14 +3,22 @@ import mongoose, { Schema, Document } from 'mongoose';
export interface PokedexEntry extends Document { export interface PokedexEntry extends Document {
pokedexNumber: number; pokedexNumber: number;
boxPlacement: { box: number; row: number; column: number }; boxPlacement: { box: number; row: number; column: number };
boxPlacementForms: { box: number; row: number; column: number };
pokemon: string; pokemon: string;
form: string; form: string;
canGigantamax: boolean; canGigantamax: boolean;
regionToCatchIn: string; regionToCatchIn: string;
gamesToCatchIn: string[]; gamesToCatchIn: string[];
regionToEvolveIn: string; regionToEvolveIn: string;
evolutionInformation: string;
catchInformation: [
{
game: string;
location: string;
notes: string; notes: string;
} }
];
}
const pokedexEntrySchema = new Schema<PokedexEntry>({ const pokedexEntrySchema = new Schema<PokedexEntry>({
pokedexNumber: Number, pokedexNumber: Number,
@@ -19,13 +27,25 @@ const pokedexEntrySchema = new Schema<PokedexEntry>({
row: Number, row: Number,
column: Number column: Number
}, },
boxPlacementForms: {
box: Number,
row: Number,
column: Number
},
pokemon: String, pokemon: String,
form: String, form: String,
canGigantamax: Boolean, canGigantamax: Boolean,
regionToCatchIn: String, regionToCatchIn: String,
gamesToCatchIn: Array<string>, gamesToCatchIn: Array<string>,
regionToEvolveIn: String, regionToEvolveIn: String,
evolutionInformation: String,
catchInformation: [
{
game: String,
location: String,
notes: String notes: String
}
]
}); });
export default mongoose.model<PokedexEntry>('PokedexEntry', pokedexEntrySchema); export default mongoose.model<PokedexEntry>('PokedexEntry', pokedexEntrySchema);
@@ -22,16 +22,19 @@ class CombinedDataRepository {
}, },
{ {
$sort: { $sort: {
'boxPlacement.box': 1, 'boxPlacementForms.box': 1,
'boxPlacement.row': 1, 'boxPlacementForms.row': 1,
'boxPlacement.column': 1 'boxPlacementForms.column': 1
} }
}, },
{ $skip: skip }, { $skip: skip },
{ $limit: limit } { $limit: limit }
]).exec(); ]).exec();
return combinedData.map((data) => ({ // Filter out entries with no catch records
const filteredData = combinedData.filter((data) => data.catchRecord);
return filteredData.map((data) => ({
pokedexEntry: data as PokedexEntry, pokedexEntry: data as PokedexEntry,
catchRecord: data.catchRecord as CatchRecord catchRecord: data.catchRecord as CatchRecord
})); }));
+4
View File
@@ -10,6 +10,10 @@ export const GET = async ({ url }) => {
await dbConnect(); await dbConnect();
const repo = new CombinedDataRepository(); const repo = new CombinedDataRepository();
const combinedData = await repo.findCombinedData(page, limit); const combinedData = await repo.findCombinedData(page, limit);
if (combinedData.length === 0) {
return json({ error: 'No combined data found' }, { status: 404 });
}
const totalCount = await repo.countCombinedData(); const totalCount = await repo.countCombinedData();
const totalPages = Math.ceil(totalCount / limit); const totalPages = Math.ceil(totalCount / limit);
+85 -4
View File
@@ -7,11 +7,15 @@
import PokedexEntryCatchRecord from '$lib/components/pokedex/PokedexEntryCatchRecord.svelte'; import PokedexEntryCatchRecord from '$lib/components/pokedex/PokedexEntryCatchRecord.svelte';
import Pagination from '$lib/components/Pagination.svelte'; import Pagination from '$lib/components/Pagination.svelte';
import { browser } from '$app/environment'; import { browser } from '$app/environment';
import type { PokedexEntry } from '$lib/models/PokedexEntry';
let combinedData = null as CombinedData[] | null; let combinedData = null as CombinedData[] | null;
let currentPage = 1 as number; let currentPage = 1 as number;
let itemsPerPage = 20 as number; let itemsPerPage = 20 as number;
let totalPages = 0 as number; let totalPages = 0 as number;
let creatingRecords = false;
let totalRecordsCreated = 0;
let failedToLoad = false;
let localUser: User | null; let localUser: User | null;
const unsubscribe = user.subscribe((value) => { const unsubscribe = user.subscribe((value) => {
@@ -32,17 +36,19 @@
async function getData() { async function getData() {
combinedData = null; combinedData = null;
const response = await fetch(`/api/combined-data?page=${currentPage}&limit=${itemsPerPage}`); const response = await fetch(`/api/combined-data?page=${currentPage}&limit=${itemsPerPage}`);
const data = await response.json(); const data = await response.json();
if (data.error) {
failedToLoad = true;
return;
}
combinedData = data.combinedData; combinedData = data.combinedData;
totalPages = data.totalPages; totalPages = data.totalPages;
} }
onMount(async () => {
await getData();
});
$: { $: {
if (browser) { if (browser) {
currentPage, itemsPerPage, getData(); currentPage, itemsPerPage, getData();
@@ -73,6 +79,66 @@
console.error('Error updating catch record:', error); console.error('Error updating catch record:', error);
} }
} }
async function getPokedexEntries() {
const response = await fetch('/api/pokedexentries');
if (!response.ok) {
throw new Error('Failed to fetch Pokémon data');
}
return await response.json();
}
async function createCatchRecords() {
// this user doesn't have any catch records, so we need to create them
await getPokedexEntries().then(async (pokedexEntries) => {
// If there are no catch records, make one for each pokedex entry
creatingRecords = true;
const newCatchRecords = pokedexEntries.map((entry: PokedexEntry) => ({
userId: localUser?.id,
pokedexEntryId: entry._id,
haveToEvolve: false,
caught: false,
inHome: false,
hasGigantamaxed: false,
personalNotes: ''
}));
if (newCatchRecords.length === 0) {
alert('No pokedex entries to create catch records for');
return;
}
const batchSize = 500;
for (let i = 0; i < newCatchRecords.length; i += batchSize) {
const batch = newCatchRecords.slice(i, i + batchSize);
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(batch)
};
try {
const response = await fetch('/api/catch-records', requestOptions);
if (!response.ok) {
throw new Error('Failed to create catch records');
}
const createdRecords = await response.json();
totalRecordsCreated += createdRecords.length;
console.log(`Created ${createdRecords.length} catch records`);
} catch (error) {
console.error('Error creating catch records:', error);
}
}
console.log('Created catch records for each pokedex entry');
creatingRecords = false;
failedToLoad = false;
await getData();
});
}
</script> </script>
<svelte:head> <svelte:head>
@@ -110,6 +176,21 @@
on:updateCatch={() => updateACatch(catchRecord)} on:updateCatch={() => updateACatch(catchRecord)}
/> />
{/each} {/each}
{:else if failedToLoad}
{#if creatingRecords && totalRecordsCreated > 0}
<p>Processed {totalRecordsCreated} Pokédex entries so far...</p>
<p>Please be patient, this may take some time.</p>
{:else if creatingRecords}
<p>Processing...</p>
<p>Please be patient, this may take some time.</p>
{:else}
<h1>Failed to load</h1>
<p>
If you're seeing this, you probably haven't created your Pokédex data yet. Please do so
by clicking this button.
</p>
<button class="btn" on:click={createCatchRecords}>Create Pokédex data</button>
{/if}
{:else} {:else}
<div class="min-w-max mx-auto"> <div class="min-w-max mx-auto">
<h1>Loading Pokédex</h1> <h1>Loading Pokédex</h1>
+7 -1
View File
@@ -12,6 +12,11 @@ fs.createReadStream(inputFilePath)
const entry = { const entry = {
pokedexNumber: parseInt(data['Dex #']), pokedexNumber: parseInt(data['Dex #']),
boxPlacement: { boxPlacement: {
box: parseInt(data['No Form Box']),
row: parseInt(data['No Form Row']),
column: parseInt(data['No Form Column'])
},
boxPlacementForms: {
box: parseInt(data['Home Box']), box: parseInt(data['Home Box']),
row: parseInt(data['Home Row']), row: parseInt(data['Home Row']),
column: parseInt(data['Home Column']) column: parseInt(data['Home Column'])
@@ -22,7 +27,8 @@ fs.createReadStream(inputFilePath)
regionToCatchIn: data['Region'], regionToCatchIn: data['Region'],
gamesToCatchIn: data['Catch In These Games'].split(',').map((game) => game.trim()), gamesToCatchIn: data['Catch In These Games'].split(',').map((game) => game.trim()),
regionToEvolveIn: data['Evolve In Region'], regionToEvolveIn: data['Evolve In Region'],
notes: data['Notes to obtain'] evolutionInformation: data['Evolution Info'],
catchInformation: []
}; };
results.push(entry); results.push(entry);
}) })
+9730 -1390
View File
File diff suppressed because it is too large Load Diff
+1062 -1062
View File
File diff suppressed because it is too large Load Diff