Skip to content

Instantly share code, notes, and snippets.

@Frulko
Forked from 8mist/nomarlizeStrapiData.ts
Created February 5, 2023 10:34
Show Gist options
  • Save Frulko/51a52394b2e7c7f6c0c8d89965dabe81 to your computer and use it in GitHub Desktop.
Save Frulko/51a52394b2e7c7f6c0c8d89965dabe81 to your computer and use it in GitHub Desktop.
export type Obj = Record<any, any>;
export const isArray = Array.isArray;
export const isObject = (val: unknown): val is Obj => {
return val !== null && typeof val === 'object';
};
export type StrapiAttributesObject = {
attributes: any;
};
export type StrapiCollectionWithData = {
data: StrapiAttributesObject[] | StrapiAttributesObject | [] | null;
};
/**
* Checks if the given object has the data property.
*
* @param {Obj} arg - The object to check.
* @returns True if the object has the data property, false otherwise.
*/
const isStrapiCollectionWithData = (arg: Obj): arg is StrapiCollectionWithData => {
return !!arg && 'data' in arg;
};
/**
* Checks if the given object has the attributes property.
*
* @param {Obj} arg - The object to check.
* @returns True if the object has the attributes property, false otherwise.
*/
const isStrapiAttributesObject = (arg: Obj): arg is StrapiAttributesObject => {
return !!arg && 'attributes' in arg;
};
/**
* Extracts the attributes property from the given object.
* If the object does not have the attributes property, the object is returned.
*
* @param {Obj} data - The object to extract the attributes property from.
* @returns The attributes property of the given object.
*/
const extractStrapiAttributes = (data: Obj) => {
let extractedData = {};
for (const key in data) {
if (key === 'attributes') {
extractedData = { ...data[key] };
} else {
extractedData[key] = data[key];
}
}
return extractedData;
};
/**
* Normalizes the given Strapi data.
*
* @param {Obj} data - The data to normalize.
* @returns The normalized data.
*/
export const normalizeStrapiData = (data: Obj) => {
if (!isObject(data) || data === null) return data;
if (isStrapiCollectionWithData(data)) {
if (isArray(data.data)) {
data = [...data.data];
} else if (isStrapiAttributesObject(data.data) || isObject(data.data)) {
data = extractStrapiAttributes({ ...data.data });
} else if (data.data === null) {
data = null;
} else {
data = extractStrapiAttributes(data);
}
}
const normalizedData: Obj = {};
for (const key in data) {
normalizedData[key] = normalizeStrapiData(data[key]);
}
return normalizedData;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment