ts-to-mongo-schema v1.0.4
Introduction
This program allows the user to convert Typescript defined interfaces or type alias declarations, to MongoDB bson type schemas. This is achieved through the steps below
Program Logic
Setup
//paths const projectPath = "../../testProject"; const configPath = projectPath + "/tsconfig.json"; const filePath = projectPath + "/src/types/testFile.tsx";
const bsonSchema = generateSchema({ configPath: configPath, identifier: "Person", filePath: filePath, extension: '.tsx', });
</details>
## Error Management
<details>
<summary>Click To Expand!</summary>
<br>
If the program cannot parse the property type, an empty object will be returned in the property type's place. The user can then modify this manually, in the generated schema.
Example Typescript:
```typescript
type ArrayOneOrMore<T> = {
0: T;
} & Array<T>;
interface Person{
name: string;
interests: ArrayOneOrMore<string>
}
BSON Schema Result:
{
bsonType: 'object'
properties: {
name: {bsonType: string}
//empty object
interests: {}
}
required: [
name,
interests
]
}
Note:
This will usually occur if the interface or type depends on a custom generic, or an imported type from a third-party library. If this is the case, please use the resolveCustomGenerics function to provide a custom value. This outlined below.
Providing Custom Values for Custom Generics
When the program returns too many empty objects for property values, there could be an unsupported custom generic that does not allow for the extraction of properties. However, that does not mean all hope is lost.
Find the offending generics and pass in a map to help the program identify them, and parse them according to custom logic
type ResolveCustomParams = {
propertiesPerArg?: any[];
combinedProperties?: { [key: string]: any };
};
const bsonSchema = generateSchema({
configPath: configPath,
identifier: "Person",
filePath: filePath,
extension: '.tsx',
resolveCustomGenerics: {
//the test file contains a custom generic declared as ArrayOneOrMore.
//Therefore, the key is the name of the generic, and attached function
//returns the custom value for that generic
ArrayOneOrMore: (props: ResolveCustomParams) => {
return {
bsonType: "array",
items: props.combinedProperties,
minItems: 1,
};
},
},
});