generated from tpl/obsidian-sample-plugin
Fix isbn and publishedAt schemas and add zod error to notice
This commit is contained in:
parent
eda363ebbd
commit
6f7b83b0e8
|
|
@ -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.");
|
||||
|
|
|
|||
17
src/types.ts
17
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<typeof bookSchema>;
|
||||
|
|
|
|||
Loading…
Reference in New Issue