mongodb-schema
Version:
Infer the probabilistic schema for a MongoDB collection.
94 lines • 3.08 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.convertInternalToMongodb = exports.InternalTypeToBsonTypeMap = void 0;
const util_1 = require("../util");
exports.InternalTypeToBsonTypeMap = {
Double: 'double',
Number: 'double',
String: 'string',
Document: 'object',
Array: 'array',
Binary: 'binData',
Undefined: 'undefined',
ObjectId: 'objectId',
Boolean: 'bool',
Date: 'date',
Null: 'null',
RegExp: 'regex',
BSONRegExp: 'regex',
DBRef: 'dbPointer',
BSONSymbol: 'symbol',
Symbol: 'symbol',
Code: 'javascript',
CodeWScope: 'javascriptWithScope',
Int32: 'int',
Timestamp: 'timestamp',
Long: 'long',
Decimal128: 'decimal',
MinKey: 'minKey',
MaxKey: 'maxKey'
};
const convertInternalType = (type) => {
const bsonType = exports.InternalTypeToBsonTypeMap[type];
if (!bsonType)
throw new Error(`Encountered unknown type: ${type}`);
return bsonType;
};
async function parseType(type, signal) {
var _a;
await (0, util_1.allowAbort)(signal);
const schema = {
bsonType: convertInternalType(type.bsonType)
};
if (type.bsonType === 'Array') {
const items = await parseTypes(type.types);
if (!items.bsonType || ((_a = items.bsonType) === null || _a === void 0 ? void 0 : _a.length) > 0) {
schema.items = items;
}
}
else if (type.bsonType === 'Document') {
Object.assign(schema, await parseFields(type.fields, signal));
}
return schema;
}
function isPlainTypesOnly(types) {
return types.every(definition => !!definition.bsonType && Object.keys(definition).length === 1);
}
async function parseTypes(types, signal) {
await (0, util_1.allowAbort)(signal);
const definedTypes = types.filter(type => type.bsonType.toLowerCase() !== 'undefined');
const isSingleType = definedTypes.length === 1;
if (isSingleType) {
return parseType(definedTypes[0], signal);
}
const parsedTypes = await Promise.all(definedTypes.map(type => parseType(type, signal)));
if (isPlainTypesOnly(parsedTypes)) {
return {
bsonType: parsedTypes.map(({ bsonType }) => bsonType)
};
}
return {
anyOf: parsedTypes
};
}
async function parseFields(fields, signal) {
const required = [];
const properties = {};
for (const field of fields) {
if (field.probability === 1)
required.push(field.name);
properties[field.name] = await parseTypes(field.types, signal);
}
return { properties, ...(required.length > 0 ? { required } : {}) };
}
async function convertInternalToMongodb(internalSchema, options = {}) {
const { required, properties } = await parseFields(internalSchema.fields, options.signal);
const schema = {
bsonType: 'object',
...((required === undefined) ? {} : { required }),
properties
};
return schema;
}
exports.convertInternalToMongodb = convertInternalToMongodb;
//# sourceMappingURL=internalToMongoDB.js.map
;