diff --git a/src/commands/CreateBookFromClipboardCommand.ts b/src/commands/CreateBookFromClipboardCommand.ts index 22260b9..b196540 100644 --- a/src/commands/CreateBookFromClipboardCommand.ts +++ b/src/commands/CreateBookFromClipboardCommand.ts @@ -1,6 +1,7 @@ import { Notice } from "obsidian"; import { Command } from "./Command"; import { bookSchema, type Book } from "@src/types"; +import z from "zod/v4"; export class CreateBookFromClipboardCommand extends Command { @@ -15,16 +16,16 @@ export class CreateBookFromClipboardCommand extends Command { async callback() { const data = await navigator.clipboard.readText(); - const { data: book, success, error } = await bookSchema.safeParseAsync(JSON.parse(data)); + const result = await bookSchema.safeParseAsync(JSON.parse(data)); - if (!success) { - console.error(error.message); - new Notice("There is not a valid book in the clipboard. Check console for details"); + if (!result.success) { + console.log("Invalid book: ", result.error) + new Notice("Invalid book\n" + z.prettifyError(result.error)); return } try { - await this.createEntry(book); + await this.createEntry(result.data); } catch (error) { console.error("Failed to create book:", error); new Notice("Failed to create book. Check console for details."); diff --git a/src/types.ts b/src/types.ts index 1451c7f..5fca4b8 100644 --- a/src/types.ts +++ b/src/types.ts @@ -23,6 +23,13 @@ export interface Series { position: number; } +function isbn(len: number) { + return z.preprocess( + val => (typeof val === "string" ? val.replace(/[\s-]+/g, "") : val), + z.string().length(len).nullable() + ); +} + export const bookSchema = z.object({ title: z.string(), subtitle: z.string(), @@ -30,16 +37,12 @@ export const bookSchema = z.object({ authors: z.array(authorSchema), series: seriesSchema.nullable(), publisher: z.string(), - publishedAt: z.date(), + publishedAt: z.coerce.date(), genres: z.array(z.string()), coverImageUrl: z.url(), pageCount: z.number().min(0), - isbn: z.string() - .transform(val => val.replace(/-+/g, '')) - .pipe(z.string().length(10)), - isbn13: z.string() - .transform(val => val.replace(/-+/g, '')) - .pipe(z.string().length(10)), + isbn: isbn(10), + isbn13: isbn(13), }); export type Book = z.infer;