UNPKG

@yihuangdb/storage-object

Version:

A Node.js storage object layer library using Redis OM

104 lines 3.43 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Model = Model; exports.Field = Field; const storage_1 = require("./storage"); const metadataKey = Symbol('storage:metadata'); function Model(options = {}) { return function (constructor) { const metadata = { collection: options.collection || constructor.name.toLowerCase(), options, fields: Reflect.getMetadata(metadataKey, constructor.prototype) || new Map(), }; const schema = {}; metadata.fields.forEach((fieldOptions, fieldName) => { schema[fieldName] = { type: fieldOptions.type || 'string', indexed: fieldOptions.indexed, sortable: fieldOptions.sortable, normalized: fieldOptions.normalized, separator: fieldOptions.separator, }; }); const storage = new storage_1.StorageObject(metadata.collection, schema, metadata.options); return class extends constructor { static storage = storage; static async initialize() { await storage.initialize(); } static async create(data) { return storage.create(data); } static async findById(id) { return storage.findById(id); } static async findAll(options) { return storage.findAll(options); } static async findOne(query) { return storage.findOne(query); } static async find(query, options) { return storage.find(query, options); } static async update(id, data) { return storage.update(id, data); } static async delete(id) { return storage.delete(id); } static async count(query) { return storage.count(query); } }; }; } function Field(options = {}) { return function (target, propertyKey) { const fields = Reflect.getMetadata(metadataKey, target) || new Map(); const type = options.type || inferType(target, propertyKey); fields.set(propertyKey, { ...options, type, }); Reflect.defineMetadata(metadataKey, fields, target); if (options.default !== undefined) { const defaultValue = options.default; let value = defaultValue; Object.defineProperty(target, propertyKey, { configurable: true, enumerable: true, get: function () { return value; }, set: function (newValue) { value = newValue; }, }); } }; } function inferType(target, propertyKey) { if (!Reflect || !Reflect.getMetadata) { return 'string'; } const type = Reflect.getMetadata('design:type', target, propertyKey); if (type === String) { return 'string'; } if (type === Number) { return 'number'; } if (type === Boolean) { return 'boolean'; } if (type === Date) { return 'date'; } if (type === Array) { return 'string[]'; } return 'string'; } //# sourceMappingURL=decorators.js.map