UNPKG

remix-utils-rt

Version:

This package contains simple utility functions to use with [React Router](https://reactrouter.com/home).

59 lines 2.03 kB
import { isCookie, } from "react-router"; export function createTypedCookie({ cookie, schema, }) { if (schema._def.typeName === "ZodObject") { let flashSchema = {}; for (let key in schema.shape) { flashSchema[flash(key)] = schema.shape[key].optional(); } } return { isTyped: true, get name() { return cookie.name; }, get isSigned() { return cookie.isSigned; }, get expires() { return cookie.expires; }, async parse(cookieHeader, options) { if (!cookieHeader) return null; let value = await cookie.parse(cookieHeader, options); return await parseSchemaWithFlashKeys(schema, value); }, async serialize(value, options) { let parsedValue = await parseSchemaWithFlashKeys(schema, value); return cookie.serialize(parsedValue, options); }, }; } /** * Returns true if an object is a Remix Utils Typed Cookie container. * * @see https://github.com/sergiodxa/remix-utils#typed-cookies */ export function isTypedCookie(value) { return (isCookie(value) && value.isTyped === true); } function flash(name) { return `__flash_${name}__`; } function parseSchemaWithFlashKeys(schema, value) { // if the Schema is not a ZodObject, we use it directly if (schema._def.typeName !== "ZodObject") { return schema.nullable().parseAsync(value); } // but if it's a ZodObject, we need to add support for flash keys, so we // get the shape of the schema, create a flash key for each key, and then we // extend the original schema with the flash schema and parse the value let objectSchema = schema; let flashSchema = {}; for (let key in objectSchema.shape) { flashSchema[flash(key)] = objectSchema.shape[key].optional(); } return objectSchema.extend(flashSchema).parseAsync(value); } //# sourceMappingURL=typed-cookie.js.map