jdb-lite
Version:
A lightweight schema-based JSON database library with validation
115 lines • 3.7 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Schema = void 0;
class Schema {
constructor(definition, options = {}) {
this.methods = {};
this.statics = {};
this.virtuals = {};
this.preHooks = {};
this.postHooks = {};
this.indexes = [];
this.definition = definition;
this.options = {
timestamps: false,
...options
};
// Add timestamps if enabled
if (this.options.timestamps) {
this.definition.createdAt = { type: 'Date', default: () => new Date() };
this.definition.updatedAt = { type: 'Date', default: () => new Date() };
}
}
add(obj) {
Object.assign(this.definition, obj);
}
pre(method, fn) {
if (!this.preHooks[method]) {
this.preHooks[method] = [];
}
this.preHooks[method].push(fn);
}
post(method, fn) {
if (!this.postHooks[method]) {
this.postHooks[method] = [];
}
this.postHooks[method].push(fn);
}
virtual(name) {
const virtualType = {
get: (fn) => {
// Store getter function
return virtualType;
},
set: (fn) => {
// Store setter function
return virtualType;
}
};
this.virtuals[name] = virtualType;
return virtualType;
}
index(fields) {
this.indexes.push(fields);
}
plugin(fn, options) {
fn(this, options);
}
validate(doc) {
const errors = [];
for (const [key, schemaType] of Object.entries(this.definition)) {
const value = doc[key];
if (Array.isArray(schemaType)) {
// Handle array types
continue;
}
const typeDef = schemaType;
// Check required fields
if (typeDef.required && (value === undefined || value === null)) {
errors.push(`Field '${key}' is required`);
continue;
}
// Skip validation if value is undefined/null and not required
if (value === undefined || value === null) {
continue;
}
// Type validation
if (!this.validateType(value, typeDef.type)) {
errors.push(`Field '${key}' must be of type ${typeDef.type}`);
}
// Custom validation
if (typeDef.validate && !typeDef.validate(value)) {
errors.push(`Field '${key}' failed custom validation`);
}
}
return errors;
}
validateType(value, type) {
switch (type) {
case 'String':
return typeof value === 'string';
case 'Number':
return typeof value === 'number' && !isNaN(value);
case 'Boolean':
return typeof value === 'boolean';
case 'Date':
return value instanceof Date || !isNaN(Date.parse(value));
case 'Array':
return Array.isArray(value);
case 'Object':
return typeof value === 'object' && value !== null && !Array.isArray(value);
case 'ObjectId':
return typeof value === 'string' && /^[0-9a-fA-F]{24}$/.test(value);
default:
return true;
}
}
getPreHooks(method) {
return this.preHooks[method] || [];
}
getPostHooks(method) {
return this.postHooks[method] || [];
}
}
exports.Schema = Schema;
//# sourceMappingURL=schema.js.map