Skip to content

Commit

Permalink
adds check for language
Browse files Browse the repository at this point in the history
  • Loading branch information
tstikvoort committed Jul 12, 2024
1 parent 0135586 commit b9220f4
Show file tree
Hide file tree
Showing 8 changed files with 41 additions and 28 deletions.
4 changes: 2 additions & 2 deletions src/client.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { SanityClient } from 'sanity';

import { getAllPageMetadata } from './helpers/page-tree';
import { getRawPageMetadataQuery } from './queries';
import { getAllRawPageMetadataQuery } from './queries';
import { PageMetadata, PageTreeConfig } from './types';

export type { PageMetadata } from './types';
Expand All @@ -25,7 +25,7 @@ class PageTreeClient {
}

public async getAllPageMetadata(): Promise<PageMetadata[]> {
const rawPageMetadata = await this.client.fetch(getRawPageMetadataQuery(this.config));
const rawPageMetadata = await this.client.fetch(getAllRawPageMetadataQuery(this.config));
return getAllPageMetadata(this.config, rawPageMetadata);
}
}
4 changes: 2 additions & 2 deletions src/hooks/usePageTree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import { useMemo } from 'react';
import { useListeningQuery } from 'sanity-plugin-utils';

import { mapRawPageMetadatasToPageTree } from '../helpers/page-tree';
import { getRawPageMetadataQuery } from '../queries';
import { getAllRawPageMetadataQuery } from '../queries';
import { PageTreeConfig, RawPageMetadata } from '../types';

export const usePageTree = (config: PageTreeConfig) => {
const { data, loading } = useListeningQuery<RawPageMetadata[]>(getRawPageMetadataQuery(config), {
const { data, loading } = useListeningQuery<RawPageMetadata[]>(getAllRawPageMetadataQuery(config), {
options: { apiVersion: config.apiVersion },
});

Expand Down
4 changes: 2 additions & 2 deletions src/hooks/usePageTreeItem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ import { useMemo } from 'react';
import { useListeningQuery } from 'sanity-plugin-utils';

import { getAllPageMetadata } from '../helpers/page-tree';
import { getRawPageMetadataQuery } from '../queries';
import { getAllRawPageMetadataQuery } from '../queries';
import { PageTreeConfig, RawPageMetadata } from '../types';

export const usePageTreeItem = (documentId: string, config: PageTreeConfig, perspective?: ClientPerspective) => {
const { data, loading } = useListeningQuery<RawPageMetadata[]>(getRawPageMetadataQuery(config), {
const { data, loading } = useListeningQuery<RawPageMetadata[]>(getAllRawPageMetadataQuery(config), {
options: { apiVersion: config.apiVersion, perspective },
});

Expand Down
4 changes: 2 additions & 2 deletions src/next.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { FilteredResponseQueryOptions, SanityClient } from 'next-sanity';

import { getAllPageMetadata } from './helpers/page-tree';
import { getRawPageMetadataQuery } from './queries';
import { getAllRawPageMetadataQuery } from './queries';
import { PageMetadata, PageTreeConfig } from './types';

export type { PageMetadata } from './types';
Expand Down Expand Up @@ -29,7 +29,7 @@ class NextPageTreeClient {

public async getAllPageMetadata(): Promise<PageMetadata[]> {
const rawPageMetadata = await this.client.fetch(
getRawPageMetadataQuery(this.config),
getAllRawPageMetadataQuery(this.config),
undefined,
this.defaultSanityFetchOptions ?? {},
);
Expand Down
19 changes: 12 additions & 7 deletions src/queries/index.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,23 @@
import { getLanguageFieldName } from '../helpers/config';
import { PageTreeConfig } from '../types';

export const getRawPageMetadataQuery = (config: PageTreeConfig) => `*[_type in [${Object.values(config.pageSchemaTypes)
export const getAllRawPageMetadataQuery = (config: PageTreeConfig) => `*[_type in [${Object.values(
config.pageSchemaTypes,
)
.map(key => `"${key}"`)
.join(', ')}]]{
${rawPageMetadataFragment(config)}
}`;

export const getRawPageMetadataQuery = (documentId: string, config: PageTreeConfig) => `*[_id == "${documentId}"]{
${rawPageMetadataFragment(config)}
}`;

export const rawPageMetadataFragment = (config: PageTreeConfig) => `
_id,
_type,
_updatedAt,
parent,
slug,
title,
${getLanguageFieldName(config) ?? ''}
}`;

export const getDocumentTypeQuery = (documentId: string) => `*[_id == "${documentId}"]{
_type
}`;
${getLanguageFieldName(config) ?? ''}`;
2 changes: 2 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ export type PageTreeConfig = {
supportedLanguages: string[];
/* Optional field name of the language field, defaults to "language" */
languageFieldName?: string;
/* Adds validation check to ensure that the language of the document matches the language of the parent document. Default: false */
documentLanguageShouldMatchParent?: boolean;
};
};

Expand Down
28 changes: 17 additions & 11 deletions src/validators/parent-validator.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,17 @@
import { Reference, ValidationContext } from 'sanity';

import { getDocumentTypeQuery } from '../queries';
import { getLanguageFieldName } from '../helpers/config';
import { getRawPageMetadataQuery } from '../queries';
import { PageTreeConfig, RawPageMetadata, SanityRef } from '../types';

/**
* Validates that the slug is unique within the parent page and therefore that entire the path is unique.
*/
export const allowedParentValidator =
(config: PageTreeConfig, ownType: string) =>
async (selectedParent: Reference | undefined, context: ValidationContext) => {
async (selectedParentRef: Reference | undefined, context: ValidationContext) => {
const allowedParents = config.allowedParents?.[ownType];

if (allowedParents === undefined) {
return true;
}

const parentRef = context.document?.parent as SanityRef | undefined;
if (!parentRef) {
return true;
Expand All @@ -27,15 +24,24 @@ export const allowedParentValidator =
}

const client = context.getClient({ apiVersion: config.apiVersion });
const selectedParentType = (await client.fetch<Pick<RawPageMetadata, '_type'>[]>(getDocumentTypeQuery(parentId)))[0]
?._type;
const selectedParent = (await client.fetch<RawPageMetadata[]>(getRawPageMetadataQuery(parentId, config)))?.[0];

if (!selectedParentType) {
if (!selectedParent._type) {
return 'Unable to check the type of the selected parent.';
}

if (!allowedParents.includes(selectedParentType)) {
return `The parent of type "${selectedParentType}" is not allowed for this type of document.`;
if (allowedParents && !allowedParents.includes(selectedParent._type)) {
return `The parent of type "${selectedParent._type}" is not allowed for this type of document.`;
}

if (config.documentInternationalization?.documentLanguageShouldMatchParent) {
const languageFieldName = getLanguageFieldName(config);
const language = context.document?.[languageFieldName];
const parentLanguage = selectedParent?.[languageFieldName];

if (language !== parentLanguage) {
return 'The language of the parent must match the language of the document.';
}
}

return true;
Expand Down
4 changes: 2 additions & 2 deletions src/validators/slug-validator.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { SlugValue, ValidationContext } from 'sanity';

import { DRAFTS_PREFIX } from '../helpers/page-tree';
import { getRawPageMetadataQuery } from '../queries';
import { getAllRawPageMetadataQuery } from '../queries';
import { PageTreeConfig, RawPageMetadata, SanityRef } from '../types';
import { getSanityDocumentId } from '../utils/sanity';

Expand All @@ -17,7 +17,7 @@ export const slugValidator =
return true;
}

const allPages = await client.fetch<RawPageMetadata[]>(getRawPageMetadataQuery(config));
const allPages = await client.fetch<RawPageMetadata[]>(getAllRawPageMetadataQuery(config));
const siblingPages = allPages.filter(page => page.parent?._ref === parentRef._ref);

const siblingPagesWithSameSlug = siblingPages
Expand Down

0 comments on commit b9220f4

Please sign in to comment.