Skip to content

Instantly share code, notes, and snippets.

View employee451's full-sized avatar

Aske Hippe Brun employee451

View GitHub Profile
@employee451
employee451 / resolveSanityGraphqlReferences.ts
Last active May 7, 2024 10:17
Resolve references in Sanity data (GraphQL)
import { groq } from 'next-sanity' // Replace with another library if you don't use Next.JS
import { client } from './client' // Replace this with wherever you have set up your client
/**
* Resolves all unresolved references when fetching from the Sanity GraphQL API.
* There is no native way to do this, so we have to do it manually.
* @param data
*/
export const resolveSanityGraphqlReferences = async <T = unknown>(
// @see https://gist.github.com/employee451/938ae007cddd9733b64acb9a958428bd
import { getNestedObjectKeyNames } from '@shared/helpers/getNestedObjectKeyNames'
type MissingKeyResult = {
/** The index of the object that has the missing key */
missingKeyObject: number
/** The index of the object where the missing key comes from */
missingKeyOrigin: number
/** Name of the key that is missing */
keyName: string
/**
* Returns an array with the names of the keys of an object.
* Supports nested objects.
*
* @example
* getObjectKeyNames({
* some: {
* nested: {
* value: 'string'
* }
type AcceptedArrayContents = string | { [key: string]: any }
/**
* Sorts an array alphabetically. If an object is provided, it sorts by the provided sortProperty.
* @param array
* @param sortProperty
*/
const sortArrayAlphabetically = (
array: AcceptedArrayContents[] = [],
sortProperty = ''
type RetrierResponseType<DataType> =
| {
success: false
data?: any
}
| {
success: true
data: DataType
}
// @see https://gist.github.com/employee451/b4414c0cc4f5a818eea82f881c4dc227
import getNestedProperty from './getNestedProperty'
/**
* Returns an array without duplicate items based on the provided object property
*/
function removeArrayDuplicatesByProperty<ItemType = any>(
array: ItemType[],
property: string
): ItemType[] {
/**
* Takes an object of key-value pairs, and assembles them to a URI string
* @param { Object } object
* @returns { String } A URI string
*/
export const objectToUriString = (object: {
[key: string]: string | number | null | undefined
}): string =>
Object.keys(object)
.map((key) => key + '=' + encodeURIComponent(object[key] || ''))
/**
* Safely gets a value from object using the provided path. Return `undefined` if it doesn't exist
* Similar to lodash.get: https://lodash.com/docs/#get
*
* @param {{}} obj - target object
* @param {string} path - path to a nested value
* @param {*} defaultValue - gets returned if path resolved to `undefined`
*
* @see https://gist.github.com/jeneg/9767afdcca45601ea44930ea03e0febf#gistcomment-1935901
*/