1
+ /**
2
+ * Transforms the internal schema to $jsonSchema
3
+ */
1
4
import { ArraySchemaType , DocumentSchemaType , Schema as InternalSchema , SchemaType } from '../schema-analyzer' ;
2
5
import { MongoDBJSONSchema } from '../types' ;
6
+ import { allowAbort } from './util' ;
3
7
4
- const InternalTypeToBsonTypeMap : Record <
8
+ export const InternalTypeToBsonTypeMap : Record <
5
9
SchemaType [ 'name' ] | 'Double' | 'BSONSymbol' ,
6
10
string
7
11
> = {
@@ -36,15 +40,6 @@ const convertInternalType = (type: string) => {
36
40
return bsonType ;
37
41
} ;
38
42
39
- async function allowAbort ( signal ?: AbortSignal ) {
40
- return new Promise < void > ( ( resolve , reject ) =>
41
- setTimeout ( ( ) => {
42
- if ( signal ?. aborted ) return reject ( signal ?. reason || new Error ( 'Operation aborted' ) ) ;
43
- resolve ( ) ;
44
- } )
45
- ) ;
46
- }
47
-
48
43
async function parseType ( type : SchemaType , signal ?: AbortSignal ) : Promise < MongoDBJSONSchema > {
49
44
await allowAbort ( signal ) ;
50
45
const schema : MongoDBJSONSchema = {
@@ -64,6 +59,10 @@ async function parseType(type: SchemaType, signal?: AbortSignal): Promise<MongoD
64
59
return schema ;
65
60
}
66
61
62
+ function isPlainTypesOnly ( types : MongoDBJSONSchema [ ] ) : types is { bsonType : string } [ ] {
63
+ return types . every ( definition => ! ! definition . bsonType && Object . keys ( definition ) . length === 1 ) ;
64
+ }
65
+
67
66
async function parseTypes ( types : SchemaType [ ] , signal ?: AbortSignal ) : Promise < MongoDBJSONSchema > {
68
67
await allowAbort ( signal ) ;
69
68
const definedTypes = types . filter ( type => type . bsonType . toLowerCase ( ) !== 'undefined' ) ;
@@ -72,13 +71,13 @@ async function parseTypes(types: SchemaType[], signal?: AbortSignal): Promise<Mo
72
71
return parseType ( definedTypes [ 0 ] , signal ) ;
73
72
}
74
73
const parsedTypes = await Promise . all ( definedTypes . map ( type => parseType ( type , signal ) ) ) ;
75
- if ( definedTypes . some ( type => [ 'Document' , 'Array' ] . includes ( type . bsonType ) ) ) {
74
+ if ( isPlainTypesOnly ( parsedTypes ) ) {
76
75
return {
77
- anyOf : parsedTypes
76
+ bsonType : parsedTypes . map ( ( { bsonType } ) => bsonType )
78
77
} ;
79
78
}
80
79
return {
81
- bsonType : definedTypes . map ( ( type ) => convertInternalType ( type . bsonType ) )
80
+ anyOf : parsedTypes
82
81
} ;
83
82
}
84
83
0 commit comments