Created
August 16, 2024 10:15
-
-
Save NuroDev/8e758e1abc0bb90c64e7e80d1e219ed3 to your computer and use it in GitHub Desktop.
A small helper utility to create a new Astro collections loader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { AstroError } from "astro/errors"; | |
| import { z } from "astro/zod"; | |
| import type { Loader, LoaderContext } from "astro/loaders"; | |
| interface CustomLoader<T extends z.ZodTypeAny> extends Omit<Loader, "load"> { | |
| load: (ctx: LoaderContext, options: z.infer<T>) => ReturnType<Loader["load"]>; | |
| options?: T; | |
| } | |
| function defineLoader<T extends z.ZodTypeAny = never>( | |
| options: CustomLoader<T>, | |
| ): (userOptions: z.infer<T>) => Loader { | |
| return (userOptions) => ({ | |
| load: async (ctx) => { | |
| if (options.options) { | |
| const parsedOptions = options.options.safeParse(userOptions); | |
| if (!parsedOptions.success) { | |
| throw new AstroError( | |
| "Invalid loader options", | |
| Object.entries(parsedOptions.error.flatten().fieldErrors) | |
| .map(([field, error]) => `${field}: ${error?.join(", ")}`) | |
| .join("\n"), | |
| ); | |
| } | |
| } | |
| return options.load(ctx, userOptions); | |
| }, | |
| name: options.name, | |
| schema: options.schema, | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment