Skip to content

Commit

Permalink
feat: rewrote the recursive logic in mutate-sreialize mdx to avoid a …
Browse files Browse the repository at this point in the history
…bunch of errors, thanks https://github.com/MarcosNASA
  • Loading branch information
bdsqqq committed Feb 26, 2023
1 parent 0924ba1 commit e32f8ab
Showing 1 changed file with 23 additions and 20 deletions.
43 changes: 23 additions & 20 deletions lib/mutateSerializeMdx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,31 +13,34 @@ export type RecursiveSerialize<T> = {
: RecursiveSerialize<T[P]>;
};

/**
* @see {@link https://stackoverflow.com/questions/73835176/replace-all-the-nested-object-properties-to-particular-value}
*/
export async function mutateSerializeMdx<
T extends object,
R extends RecursiveSerialize<T>
>(obj: T): Promise<R> {
const keys = Object.keys(obj) as Array<keyof typeof obj>;

for (const key of keys) {
const value = obj[key];

if (typeof value === "string")
// @ts-ignore
obj[key] = await serialize(value, {
mdxOptions: {
remarkPlugins: [remarkGfm],
rehypePlugins: [],
},
});
const entries = Object.entries(obj);

const temp = entries.flatMap(async ([key, value]) => {
if (typeof value == "string") {
return [
key,
await serialize(value, {
mdxOptions: {
remarkPlugins: [remarkGfm],
rehypePlugins: [],
},
}),
];
}

if (typeof value === "object" && value !== null) {
mutateSerializeMdx(value);
return [key, await mutateSerializeMdx(value)];
}
}

// @ts-ignore
return obj;
console.error("Not a string or object", key, value);
return [];
});

const result = Object.fromEntries(await Promise.all(temp));

return result;
}

0 comments on commit e32f8ab

Please sign in to comment.