@monkdb/monkdb
Version:
🚀 Official TypeScript SDK for MonkDB — a unified, AI-native database for diverse data workloads
62 lines • 1.91 kB
JavaScript
// --- src/connection/converters.ts ---
import * as ip from 'ip';
import { MonkProgrammingError } from '../errors/MonkErrors.js';
import { DataType } from '../types/index.js';
const toIPAddress = (value) => {
if (value == null)
return null;
return ip.isV4Format(value) || ip.isV6Format(value) ? value : null;
};
const toTimestamp = (value) => {
if (value == null)
return null;
return new Date(value);
};
const toDefault = (value) => value;
const DEFAULT_CONVERTERS = new Map([
[DataType.IP, toIPAddress],
[DataType.TIMESTAMP_WITH_TZ, toTimestamp],
[DataType.TIMESTAMP_WITHOUT_TZ, toTimestamp],
]);
export class MonkConverter {
constructor(initial, fallback) {
this.mappings = new Map();
this.defaultConverter = toDefault;
if (initial) {
this.mappings = new Map(initial);
}
if (fallback) {
this.defaultConverter = fallback;
}
}
get(type) {
if (typeof type === 'number') {
return this.mappings.get(type) ?? this.defaultConverter;
}
const [outer, inner] = type;
if (outer !== DataType.ARRAY) {
throw new MonkProgrammingError(`Data type ${outer} is not an array-compatible type`);
}
const innerConverter = this.get(inner);
return (value) => {
if (!Array.isArray(value))
return null;
return value.map(innerConverter);
};
}
set(type, converter) {
this.mappings.set(type, converter);
}
}
export class MonkDefaultTypeConverter extends MonkConverter {
constructor(overrides) {
const mappings = new Map(DEFAULT_CONVERTERS);
if (overrides) {
for (const [key, fn] of overrides) {
mappings.set(key, fn);
}
}
super(mappings);
}
}
//# sourceMappingURL=converters.js.map