Skip to content

Commit

Permalink
fix: check uniqueness of iris (slugs) with different languages (#71)
Browse files Browse the repository at this point in the history
  • Loading branch information
blushi authored Nov 14, 2024
1 parent c357c85 commit 43ee488
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 0 deletions.
2 changes: 2 additions & 0 deletions schemas/documents/registry/creditClass.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import slugifyToIRI from '../../../utils/slugifyToIRI';
import isUniqueSlug from '../../../utils/isUniqueSlug';
import toPlainText from '../../../utils/toPlainText';

export default {
Expand All @@ -20,6 +21,7 @@ export default {
validation: Rule => Rule.required(),
options: {
source: 'name',
isUnique: isUniqueSlug,
slugify: input => {
return `${slugifyToIRI(toPlainText(input))}CreditClass`;
},
Expand Down
2 changes: 2 additions & 0 deletions schemas/documents/shared/ecologicalImpact.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import slugifyToIRI from '../../../utils/slugifyToIRI';
import isUniqueSlug from '../../../utils/isUniqueSlug';

export default {
title: 'Ecological Impact',
Expand All @@ -19,6 +20,7 @@ export default {
validation: Rule => Rule.required(),
options: {
source: 'name',
isUnique: isUniqueSlug,
slugify: input => {
return slugifyToIRI(input);
},
Expand Down
2 changes: 2 additions & 0 deletions schemas/documents/shared/sdg.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import slugifyToIRI from '../../../utils/slugifyToIRI';
import isUniqueSlug from '../../../utils/isUniqueSlug';

export default {
title: 'SDG',
Expand All @@ -19,6 +20,7 @@ export default {
validation: Rule => Rule.required(),
options: {
source: 'title',
isUnique: isUniqueSlug,
slugify: input => {
return slugifyToIRI(input);
},
Expand Down
21 changes: 21 additions & 0 deletions utils/isUniqueSlug.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Custom unique function for iri slugs that only checks the documents of the same type and the same language
export default function isUniqueSlug(slug, context) {
const { document, getClient } = context
const docType = document._type;
const language = document.language || 'en';

const query = `
*[_type == $docType && language == $language && iri.current == $iri && _id != $id][0]
`;

const params = {
docType,
language,
iri: slug,
id: document._id,
};

return getClient({ apiVersion: '2023-01-01' })
.fetch(query, params)
.then((result) => !result);
}

0 comments on commit 43ee488

Please sign in to comment.