๐Ÿ“ฆ directus / docs

๐Ÿ“„ responseToExample.ts ยท 56 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56import type { OpenAPIObject, ReferenceObject, SchemaObject } from 'openapi3-ts/oas30';

export type ExampleObject = Record<string, unknown>;

/**
 * Converts an openapi response definition to an example object
 * @param openapi - Full openapi spec to pull references from
 * @param responseSchema - Response schema to convert to example objects
 *
 * @note this expects the top level responseSchema to be an object or array of things
 */
export default function (openapi: OpenAPIObject, root: SchemaObject): unknown | null {
	if (root.type !== 'object' && !(root.type === 'array' || root.type === 'string')) {
		return null;
	}

	const parseLevel = (schemaOrRef: SchemaObject | ReferenceObject): unknown => {
		const schemaObj = '$ref' in schemaOrRef ? resolveOasRef<SchemaObject>(openapi, schemaOrRef.$ref) : schemaOrRef;

		if (!schemaObj) return undefined;

		if ('example' in schemaObj) return schemaObj.example;

		if (schemaObj.type === 'object') {
			const obj: ExampleObject = {};

			if (schemaObj.properties) {
				for (const [key, value] of Object.entries(schemaObj.properties)) {
					const parsedVal = parseLevel(value);

					if (parsedVal !== undefined) {
						obj[key] = parsedVal;
					}
				}
			}

			return obj;
		}

		if (schemaObj.type === 'array') {
			if (schemaObj.items) {
				const parsedVal = parseLevel(schemaObj.items);
				if (parsedVal !== undefined) return [parsedVal];
				return [];
			}

			return [];
		}
	};

	const exampleObject: unknown = parseLevel(root);

	if (root.type === 'array') return [exampleObject];
	return exampleObject;
}