1
- import assert from 'assert' ;
2
1
import type { MongoDBJSONSchema } from './types' ;
3
2
4
3
function getBSONType ( property : MongoDBJSONSchema ) : string | string [ ] | undefined {
@@ -17,6 +16,12 @@ function isBSONPrimitive(property: MongoDBJSONSchema): boolean {
17
16
return ! ( isBSONArrayProperty ( property ) || isBSONObjectProperty ( property ) ) ;
18
17
}
19
18
19
+ function assertIsDefined < T > ( value : T ) : asserts value is NonNullable < T > {
20
+ if ( value === undefined || value === null ) {
21
+ throw new Error ( `${ value } is not defined` ) ;
22
+ }
23
+ }
24
+
20
25
function toTypeName ( type : string ) : string {
21
26
// JSON Schema types
22
27
if ( type === 'string' ) {
@@ -100,7 +105,7 @@ function indentSpaces(indent: number) {
100
105
}
101
106
102
107
function arrayType ( types : string [ ] ) {
103
- assert ( types . length , 'expected types' ) ;
108
+ assertIsDefined ( types . length ) ;
104
109
105
110
if ( types . length === 1 ) {
106
111
return `${ types [ 0 ] } []` ;
@@ -115,22 +120,22 @@ function toTypescriptType(properties: Record<string, MongoDBJSONSchema>, indent:
115
120
}
116
121
117
122
if ( isBSONArrayProperty ( schema ) ) {
118
- assert ( schema . items , 'expected schema.items' ) ;
123
+ assertIsDefined ( schema . items ) ;
119
124
return `${ indentSpaces ( indent ) } ${ propertyName } ?: ${ arrayType ( [ ...uniqueTypes ( schema . items ) ] ) } ` ;
120
125
}
121
126
122
127
if ( isBSONObjectProperty ( schema ) ) {
123
- assert ( schema . properties , 'expected schema.properties' ) ;
128
+ assertIsDefined ( schema . properties ) ;
124
129
return `${ indentSpaces ( indent ) } ${ propertyName } ?: ${ toTypescriptType ( schema . properties , indent + 1 ) } ` ;
125
130
}
126
131
127
- assert ( false , 'this should not be possible ') ;
132
+ throw new Error ( 'We should never get here ') ;
128
133
} ) ;
129
134
130
135
return `{\n${ eachFieldDefinition . join ( ';\n' ) } \n${ indentSpaces ( indent - 1 ) } }` ;
131
136
}
132
137
export function toTypescriptTypeDefinition ( databaseName : string , collectionName : string , schema : MongoDBJSONSchema ) : string {
133
- assert ( schema . properties , 'expected schama.properties' ) ;
138
+ assertIsDefined ( schema . properties ) ;
134
139
135
140
return `module ${ databaseName } {
136
141
type ${ collectionName } = ${ toTypescriptType ( schema . properties , 2 ) } ;
0 commit comments