Skip to content

Commit

Permalink
fix(redirect): conditional required depending on destination type
Browse files Browse the repository at this point in the history
  • Loading branch information
mathiazom committed Sep 10, 2024
1 parent 31e000f commit bd4e5e0
Showing 1 changed file with 29 additions and 4 deletions.
33 changes: 29 additions & 4 deletions studio/schemas/documents/redirect.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,34 @@
import { defineField, defineType, type Slug } from "sanity";
import { SlugRule } from "@sanity/types";
import { SanityDocument, SlugRule } from "@sanity/types";
import { pageBuilderID } from "../builders/pageBuilder";
import { blogId } from "./blog";
import { compensationsId } from "./compensations";
import PrefixedSlugInput from "../../components/PrefixedSlugInput";

const slugValidator = (rule: SlugRule) =>
const slugRequired = (rule: SlugRule) =>
rule.required().custom((value: Slug | undefined) => {
if (!value || !value.current) return "Can't be blank";
return true;
});

const requiredIfDestinationType = (
type: string,
document: SanityDocument | undefined,
value: unknown,
) => {
const destination = document?.destination;
if (
typeof destination === "object" &&
destination !== null &&
"type" in destination &&
destination.type === type &&
value === undefined
) {
return "Can't be blank";
}
return true;
};

export const redirectId = "redirect";

const redirect = defineType({
Expand All @@ -23,7 +41,7 @@ const redirect = defineType({
title: "Source",
description: "Which url should this redirect apply for",
type: "slug",
validation: slugValidator,
validation: (rule) => slugRequired(rule),
components: {
input: (props) => PrefixedSlugInput({ prefix: "/", ...props }),
},
Expand Down Expand Up @@ -58,14 +76,21 @@ const redirect = defineType({
{ type: compensationsId },
],
hidden: ({ parent }) => parent?.type !== "reference",
validation: (rule) =>
rule.custom((value, { document }) =>
requiredIfDestinationType("reference", document, value),
),
}),
defineField({
name: "slug",
title: "Slug",
description: "Where should the user be redirected?",
type: "slug",
hidden: ({ parent }) => parent?.type !== "slug",
validation: slugValidator,
validation: (rule) =>
rule.custom((value, { document }) =>
requiredIfDestinationType("slug", document, value),
),
options: {
isUnique: () => {
/*
Expand Down

0 comments on commit bd4e5e0

Please sign in to comment.