-
Notifications
You must be signed in to change notification settings - Fork 0
/
schemaMetadataWriter.ts
72 lines (66 loc) · 2.85 KB
/
schemaMetadataWriter.ts
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { defaultCommentGenerator } from './defaultCommentGenerator';
import { JSONCommentWriterBase } from './jsonCommentWriterBase';
import { IJSONComment, IJSONCommentConfiguration , JSONSchema} from './types';
export type CommentGenerator = (schema: JSONSchema) => IJSONComment | undefined;
function hasProp(obj: any, key: string | number): boolean {
return Object.prototype.hasOwnProperty.call(obj, key);
}
/**
* A JSON comment writer generating comments for fields specified in JSON schema.
*/
export class SchemaMetadataWriter extends JSONCommentWriterBase<JSONSchema> {
protected readonly root: JSONSchema;
/**
* Construct a new SchemaMetadataWriter.
* @param schemaObject A fully dereferenced JSON schema object
* containing no `$ref`, which can be obtained using libraries like
* `json-schema-ref-parser`.`dereference` with `circular` being true.
* This object is allowed to be recursive.
* @param commentGenerator A function to generate comment string
* from the schema of a field.
* @param configuration Styling configuration for comments.
*/
public constructor(
schemaObject: JSONSchema,
private commentGenerator: CommentGenerator = defaultCommentGenerator,
configuration?: Partial<IJSONCommentConfiguration>
) {
super(configuration);
this.root = <any>{ additionalProperties: schemaObject };
}
protected nextNode(currentNode: Readonly<JSONSchema>, key: string | number)
: Readonly<JSONSchema> | undefined {
if (typeof currentNode.properties === 'object') {
if (hasProp(currentNode.properties, key)) {
const next: boolean | JSONSchema = currentNode.properties[key];
if (typeof next === 'object') {
return next;
}
}
} else if (currentNode.items) {
if (Array.isArray(currentNode.items)) {
if (key >= 0 && key < currentNode.items.length) {
const next: boolean | JSONSchema = currentNode.items[key as number];
if (typeof next === 'object') {
return next;
}
} else if (typeof currentNode.additionalItems === 'object') {
return currentNode.additionalItems;
}
} else if (typeof currentNode.items === 'object') {
return currentNode.items;
}
}
if (typeof currentNode.additionalProperties === 'object') {
return currentNode.additionalProperties;
}
return undefined;
}
protected getComments(currentNode: Readonly<JSONSchema>): IJSONComment[] {
const comment: IJSONComment | undefined = this.commentGenerator(currentNode);
if (comment) {
return [comment];
}
return [];
}
}