Skip to content

Commit

Permalink
search scryfall api on /api/search (#12)
Browse files Browse the repository at this point in the history
* search scryfall api on search
When I search for a card, the server will hit the scryfall api search endpoint.
This is awesome, cause now we'll get all cards in their database.
Need to figure out a cache of sorts that persists between sessions since Scryfall has asked to do that. Not sure how to accomplish as of now.
I added a TODO to create a Search model that will help me compare results in our db to the results saved in the Search table. Not sure how that would work but it might help?
Essentially I want to check our cache (db) before I hit the Scryfall API. I'd save the different query parameters, total results, last time cached (which can be updated every 24 hours), and maybe the different unique ids returned (might be too granular).

Anyway. Progress! Love it

* fix create types
  • Loading branch information
mathewmorris authored May 9, 2024
1 parent 87cead1 commit 6ab35fe
Show file tree
Hide file tree
Showing 5 changed files with 79 additions and 27 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
Warnings:
- You are about to drop the `cards` table. If the table is not empty, all the data it contains will be lost.
*/
-- DropTable
DROP TABLE `cards`;

-- CreateTable
CREATE TABLE `Card` (
`id` VARCHAR(191) NOT NULL,
`name` TEXT NOT NULL,
`scryfall_id` VARCHAR(191) NOT NULL,
`scryfall_uri` TEXT NOT NULL,
`image_status` TEXT NOT NULL,
`image_uris` JSON NULL,
`card_faces` JSON NULL,
`all_parts` JSON NULL,
`layout` TEXT NOT NULL,

UNIQUE INDEX `Card_scryfall_id_key`(`scryfall_id`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
3 changes: 3 additions & 0 deletions prisma/migrations/migration_lock.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
provider = "mysql"
4 changes: 2 additions & 2 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ model Card {
scryfall_uri String @db.Text
image_status String @db.Text
image_uris Json?
card_faces Json?
all_parts Json?
layout String @db.Text
@@map("cards")
}

model Collection {
Expand Down
13 changes: 1 addition & 12 deletions prisma/seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,7 @@ async function main() {
scryfall_uri: card.scryfall_uri,
}))
});
const lathril = await prisma.card.upsert({
where: { scryfall_id: '098jk2' },
update: {},
create: {
name: 'Lathril Blade of Elves',
layout: 'oihwen',
scryfall_id: '098jk2',
image_status: 'lkffj',
scryfall_uri: 'dsadfk',
},
})
console.log({ lathril })
console.log('cards seeded!');
}

main()
Expand Down
62 changes: 49 additions & 13 deletions src/server/api/routers/card.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,59 @@
import { type Prisma, type Card } from "@prisma/client";
import { TRPCError } from "@trpc/server";
import { z } from "zod";

import {
createTRPCRouter,
publicProcedure,
createTRPCRouter,
publicProcedure,
} from "~/server/api/trpc";

interface ScryfallSearchResponse {
object: string;
total_cards: number;
has_more: boolean;
data: Card[];
}

export const cardRouter = createTRPCRouter({
search: publicProcedure
.input(z.string().min(1))
.query(async ({ ctx, input }) => {
const matches = ctx.prisma.card.findMany({
where: {
name: {
contains: input,
search: publicProcedure
.input(z.string().min(1))
.query(async ({ ctx, input }) => {
// TODO: Create a searchRouter that will save results of search calls to scryfallAPI
// will use to see if search in db returns same number of results
// const matches = await ctx.prisma.card.findMany({
// where: {
// name: {
// contains: input,
// }
// }
// });

const scryfallSearch = await fetch(`https://api.scryfall.com/cards/search?q=${input}`);

if (!scryfallSearch.ok) {
throw new TRPCError({
code: 'INTERNAL_SERVER_ERROR',
message: 'Something went wrong when trying to search the Scryfall API.',
cause: scryfallSearch.statusText,
})
}
}
});

return matches;
}),
const cards = await scryfallSearch.json() as ScryfallSearchResponse;
await ctx.prisma.card.createMany({
skipDuplicates: true,
data: cards.data.map((card) => ({
scryfall_id: card.id,
scryfall_uri: card.scryfall_uri,
name: card.name,
layout: card.layout,
image_status: card.image_status,
all_parts: card.all_parts as Prisma.JsonArray,
card_faces: card.card_faces as Prisma.JsonArray,
image_uris: card.image_uris as Prisma.JsonArray,
})),
});

return cards.data;
}),
});

0 comments on commit 6ab35fe

Please sign in to comment.