Skip to content

Instantly share code, notes, and snippets.

@good-idea
Created June 30, 2021 17:52
Show Gist options
  • Save good-idea/35d92508bac8b8c83b1447043bbdfb85 to your computer and use it in GitHub Desktop.
Save good-idea/35d92508bac8b8c83b1447043bbdfb85 to your computer and use it in GitHub Desktop.
import {
Article,
ArticleGroup,
Homepage,
Topic,
Model,
GlossaryTerm,
ObjectScalarProperty,
Steps,
Step,
Callout,
InternalLink,
} from '../../types';
import {
article,
articleGroup,
steps,
homepage,
objectScalarProperty,
model,
topic,
callout,
internalLink,
} from './data';
interface SanityDocument {
_type: string;
_key?: string;
_id?: string;
slug?: {
current: string;
};
}
const get =
<T extends SanityDocument>(key: string, stubs: T[]) =>
(searchValue: string | number): T => {
const stub =
key === 'slug'
? stubs.find((stub) => stub?.slug?.current === searchValue)
: stubs.find((stub) => stub[key] === searchValue);
if (!stub)
throw new Error(
`Could not get stub with value ${key} === ${searchValue}`,
);
return stub;
};
/* Homepage */
export const getHomepageById = get<Homepage>('_id', homepage);
/* Topics */
export const getTopicById = get<Topic>('_id', topic);
export const getTopicByTitle = get<Topic>('title', topic);
export const getTopicBySlug = get<Topic>('slug', topic);
/* Articles & ArticleGroups */
export const getArticleBySlug = get<Article>('slug', article);
export const getArticleGroupBySlug = get<ArticleGroup>('slug', articleGroup);
/* Models */
export const getModelById = get<Model>('_id', model);
export const getModelByTitle = get<Model>('title', model);
/* Steps */
export const getStepsByKey = get<Steps>('_key', steps);
/* Callout */
export const getCalloutByKey = get<Callout>('_key', callout);
/* InternalLink */
export const getInternalLinkByKey = get<InternalLink>('_key', internalLink);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment