Fix isbn and publishedAt schemas and add zod error to notice

This commit is contained in:
Evan Fiordeliso 2026-06-12 09:08:26 -04:00
parent eda363ebbd
commit 6f7b83b0e8
2 changed files with 16 additions and 12 deletions

View File

@ -1,6 +1,7 @@
import { Notice } from "obsidian"; import { Notice } from "obsidian";
import { Command } from "./Command"; import { Command } from "./Command";
import { bookSchema, type Book } from "@src/types"; import { bookSchema, type Book } from "@src/types";
import z from "zod/v4";
export class CreateBookFromClipboardCommand extends Command { export class CreateBookFromClipboardCommand extends Command {
@ -15,16 +16,16 @@ export class CreateBookFromClipboardCommand extends Command {
async callback() { async callback() {
const data = await navigator.clipboard.readText(); 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) { if (!result.success) {
console.error(error.message); console.log("Invalid book: ", result.error)
new Notice("There is not a valid book in the clipboard. Check console for details"); new Notice("Invalid book\n" + z.prettifyError(result.error));
return return
} }
try { try {
await this.createEntry(book); await this.createEntry(result.data);
} catch (error) { } catch (error) {
console.error("Failed to create book:", error); console.error("Failed to create book:", error);
new Notice("Failed to create book. Check console for details."); new Notice("Failed to create book. Check console for details.");

View File

@ -23,6 +23,13 @@ export interface Series {
position: number; 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({ export const bookSchema = z.object({
title: z.string(), title: z.string(),
subtitle: z.string(), subtitle: z.string(),
@ -30,16 +37,12 @@ export const bookSchema = z.object({
authors: z.array(authorSchema), authors: z.array(authorSchema),
series: seriesSchema.nullable(), series: seriesSchema.nullable(),
publisher: z.string(), publisher: z.string(),
publishedAt: z.date(), publishedAt: z.coerce.date(),
genres: z.array(z.string()), genres: z.array(z.string()),
coverImageUrl: z.url(), coverImageUrl: z.url(),
pageCount: z.number().min(0), pageCount: z.number().min(0),
isbn: z.string() isbn: isbn(10),
.transform(val => val.replace(/-+/g, '')) isbn13: isbn(13),
.pipe(z.string().length(10)),
isbn13: z.string()
.transform(val => val.replace(/-+/g, ''))
.pipe(z.string().length(10)),
}); });
export type Book = z.infer<typeof bookSchema>; export type Book = z.infer<typeof bookSchema>;