This page gives TypeScript types for Document items and one function that turns raw Delivery API entries into them, skipping broken data. The code is trimmed from the sample project in examples/document-manager-next.
TypeScript types#
Use a union on kind, so a folder can't be treated as a file:
type Base = {
id: string;
title: string;
slug: string;
/** Plain paragraphs from the rich text description. */
description?: string[];
};
export type DocFile = Base & {
kind: "file";
versionLabel?: string;
file?: { url: string; fileName: string; contentType: string; size: number };
};
export type DocFolder = Base & { kind: "folder"; items: DocItem[] };
export type DocLibrary = Base & { kind: "library"; items: DocItem[] };
export type DocItem = DocLibrary | DocFolder | DocFile;Walking the tree safely#
Data can be broken: the app flags problems, but doesn't stop edits made in the default editor or the API. Convert raw entries to the types above in one function that applies these rules:
- Skip unresolved or unpublished links. An unresolved link has no
fields. - Skip items with no valid
kindor no title. - Stop at loops. Track the IDs on the current path. A file shared by two folders still shows in both, because only the current path counts.
- Read only the fields valid for each kind. Ignore
itemson files, andfileandversionLabelon folders and libraries.
const KINDS = ["library", "folder", "file"];
export function toDocItem(entry: Entry, seen = new Set<string>()): DocItem | null {
const f = entry.fields;
const id = entry.sys.id;
if (!f || seen.has(id) || !KINDS.includes(f.kind) || typeof f.title !== "string") return null;
const base = { id, title: f.title, slug: f.slug ?? id };
if (f.kind === "file") {
const asset = f.file?.fields?.file;
return {
...base,
kind: "file",
versionLabel: f.versionLabel,
file: asset && {
url: `https:${asset.url}`,
fileName: asset.fileName,
contentType: asset.contentType,
size: asset.details?.size ?? 0,
},
};
}
const path = new Set(seen).add(id);
const items = ((f.items ?? []) as Entry[])
.map((child) => toDocItem(child, path))
.filter((item): item is DocItem => item !== null);
return { ...base, kind: f.kind, items };
}The sample also turns the rich text description into plain paragraphs. For the full thing, use @contentful/rich-text-react-renderer.
Reading a file is safe only after its asset is published. Document Manager publishes a file's asset when you publish the file, but an asset can still be missing if someone unpublished it by hand. The file && check above handles that.