Socket
Socket
Sign inDemoInstall

metronom

Package Overview
Dependencies
10
Maintainers
2
Versions
13
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 2.1.0 to 2.2.0

9

dist/index.js

@@ -34,4 +34,9 @@ "use strict";

const Enums = __importStar(require("./lib/Enums"));
module.exports = Object.assign(Object.assign(Object.assign({ Model: Model_1.default,
module.exports = {
Model: Model_1.default,
ModelInstance: ModelInstance_1.default,
Metronom: Metronom_1.default }, Constants), Interfaces), Enums);
Metronom: Metronom_1.default,
...Constants,
...Interfaces,
...Enums,
};

@@ -6,2 +6,4 @@ import { RedisClientOptions, RedisClientType } from 'redis';

constructor(options: RedisClientOptions);
set(key: string, value: any): Promise<any>;
get(key: string): Promise<string | null>;
hGetAll(redisKey: string): Promise<object>;

@@ -8,0 +10,0 @@ hSet(redisKey: string, values: [string, any]): Promise<number>;

@@ -10,11 +10,14 @@ "use strict";

class NodeRedisAdaptor {
redisClient;
constructor(options) {
Object.defineProperty(this, "redisClient", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this.redisClient = (0, redis_1.createClient)(options);
}
set(key, value) {
Logger_1.default.log(`set ${key} ${value}`);
return this.redisClient.set(key, value);
}
get(key) {
Logger_1.default.log(`get ${key}`);
return this.redisClient.get(key);
}
hGetAll(redisKey) {

@@ -29,2 +32,3 @@ Logger_1.default.log(`hGetAll ${redisKey}`);

connect() {
Logger_1.default.log('connect');
this.redisClient.connect();

@@ -31,0 +35,0 @@ }

@@ -14,3 +14,5 @@ /**

echo(message: any): any;
set(key: string, value: any): Promise<any>;
get(key: string): Promise<string | null>;
}
export default IRedisAdaptor;
"use strict";
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _a, _Logger_log;
Object.defineProperty(exports, "__esModule", { value: true });

@@ -15,2 +9,3 @@ const Enums_1 = require("./Enums");

class Logger {
static level = null;
constructor(level) {

@@ -30,2 +25,5 @@ if (Logger.level !== null) {

}
static #log(message) {
console.log(message);
}
static log(message) {

@@ -35,3 +33,3 @@ if (!(Logger.level === Enums_1.LogLevels.Information || Logger.level === Enums_1.LogLevels.All)) {

}
__classPrivateFieldGet(this, _a, "m", _Logger_log).call(this, `[ METRONOM ] / ${new Date().toISOString()}: ${message}`);
this.#log(`[ METRONOM ] / ${new Date().toISOString()}: ${message}`);
}

@@ -42,14 +40,5 @@ static error(message) {

}
__classPrivateFieldGet(this, _a, "m", _Logger_log).call(this, `\x1b[31m[ METRONOM ERROR ] / ${new Date().toISOString()}: ${message}\x1b[0m`);
this.#log(`\x1b[31m[ METRONOM ERROR ] / ${new Date().toISOString()}: ${message}\x1b[0m`);
}
}
_a = Logger, _Logger_log = function _Logger_log(message) {
console.log(message);
};
Object.defineProperty(Logger, "level", {
enumerable: true,
configurable: true,
writable: true,
value: null
});
exports.default = Logger;

@@ -11,2 +11,3 @@ import { RedisClientOptions } from 'redis';

declare class Metronom {
#private;
redisClientOptions?: RedisClientOptions;

@@ -37,3 +38,18 @@ log?: boolean | LogLevels;

define(schema: Schema, keyPrefix?: string, modelOptions?: ModelOptions): Model;
/**
* Create String key or update if it exist.
* Redis's "SET" command
* @param {strin} key redis key
* @param {string} value value
* @returns it return "OK" if the process done
*/
setKey(key: string, value: any): Promise<string>;
/**
* Read String key
* Redis's "GET" command
* @param {string} key Redis key
* @returns if the key is exist it return the value else return null
*/
getKey(key: string): Promise<string | null>;
}
export default Metronom;

@@ -7,2 +7,5 @@ "use strict";

const Model_1 = __importDefault(require("./Model"));
const Utilities_1 = require("./Utilities");
const NodeRedisAdaptor_1 = __importDefault(require("./adaptors/NodeRedisAdaptor"));
const Logger_1 = __importDefault(require("./Logger"));
/**

@@ -14,2 +17,5 @@ * Metronom model creator

class Metronom {
redisClientOptions;
log;
#redisClient;
/**

@@ -23,16 +29,5 @@ * Base Metronom object.

constructor(options) {
Object.defineProperty(this, "redisClientOptions", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "log", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this.redisClientOptions = options === null || options === void 0 ? void 0 : options.redisClientOptions;
this.log = options === null || options === void 0 ? void 0 : options.log;
this.redisClientOptions = options?.redisClientOptions;
this.log = options?.log;
this.#redisClient = null;
}

@@ -56,9 +51,50 @@ /**

? this.redisClientOptions
: modelOptions === null || modelOptions === void 0 ? void 0 : modelOptions.redisClientOptions;
: modelOptions?.redisClientOptions;
const log = this.log
? this.log
: modelOptions === null || modelOptions === void 0 ? void 0 : modelOptions.log;
return new Model_1.default(schema, keyPrefix, Object.assign(Object.assign({}, modelOptions), { log, redisClientOptions: redisOption }));
: modelOptions?.log;
return new Model_1.default(schema, keyPrefix, {
...modelOptions,
log,
redisClientOptions: redisOption,
});
}
/**
* Create String key or update if it exist.
* Redis's "SET" command
* @param {strin} key redis key
* @param {string} value value
* @returns it return "OK" if the process done
*/
async setKey(key, value) {
if (key === '') {
(0, Utilities_1.throwError)('setKey: Keys can\'t be empty!');
}
this.#connectToRedis();
// @ts-ignore
return await this.#redisClient.set(key, value);
}
/**
* Read String key
* Redis's "GET" command
* @param {string} key Redis key
* @returns if the key is exist it return the value else return null
*/
async getKey(key) {
if (key === '' || key === undefined) {
(0, Utilities_1.throwError)('getKey: Keys can\'t be empty!');
}
this.#connectToRedis();
// @ts-ignore
return this.#redisClient.get(key);
}
#connectToRedis() {
if (this.#redisClient === null) {
// @ts-ignore
this.#redisClient = new NodeRedisAdaptor_1.default(this.redisClientOptions);
this.#redisClient.connect();
new Logger_1.default(this.log);
}
}
}
exports.default = Metronom;
"use strict";
var __asyncValues = (this && this.__asyncValues) || function (o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -23,2 +16,13 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

class Model {
/** First part of redis key. It's identifier for model class */
keyPrefix;
/** Second part of redis key. It's identifier for record */
keyUnique;
/** Object struct model */
schema;
redisClient;
/** you can't define any key except the fields in `schema`, but if this value is `true`,
* you can only add a value to the schema by giving it `keyUnique`
*/
flexSchema;
/**

@@ -39,42 +43,6 @@ * Represents a Metronom ORM Model

constructor(schema, keyPrefix = 'object', modelOption) {
/** First part of redis key. It's identifier for model class */
Object.defineProperty(this, "keyPrefix", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/** Second part of redis key. It's identifier for record */
Object.defineProperty(this, "keyUnique", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/** Object struct model */
Object.defineProperty(this, "schema", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "redisClient", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
/** you can't define any key except the fields in `schema`, but if this value is `true`,
* you can only add a value to the schema by giving it `keyUnique`
*/
Object.defineProperty(this, "flexSchema", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this.schema = schema;
this.keyPrefix = keyPrefix;
this.flexSchema = (modelOption === null || modelOption === void 0 ? void 0 : modelOption.flexSchema) ? modelOption === null || modelOption === void 0 ? void 0 : modelOption.flexSchema : false;
new Logger_1.default(modelOption === null || modelOption === void 0 ? void 0 : modelOption.log);
this.flexSchema = modelOption?.flexSchema ? modelOption?.flexSchema : false;
new Logger_1.default(modelOption?.log);
if (!this.flexSchema) {

@@ -93,12 +61,12 @@ if (Object.keys(schema).length === 0) {

}
if (!(modelOption === null || modelOption === void 0 ? void 0 : modelOption.keyUnique)) {
if (!modelOption?.keyUnique) {
this.keyUnique = undefined;
}
else {
if (!Object.keys(schema).includes(modelOption === null || modelOption === void 0 ? void 0 : modelOption.keyUnique)) {
(0, Utilities_1.throwError)(`${modelOption === null || modelOption === void 0 ? void 0 : modelOption.keyUnique} keyUnique must be in to schema!`);
if (!Object.keys(schema).includes(modelOption?.keyUnique)) {
(0, Utilities_1.throwError)(`${modelOption?.keyUnique} keyUnique must be in to schema!`);
}
this.keyUnique = modelOption === null || modelOption === void 0 ? void 0 : modelOption.keyUnique;
this.keyUnique = modelOption?.keyUnique;
}
this.redisClient = new NodeRedisAdaptor_1.default(modelOption === null || modelOption === void 0 ? void 0 : modelOption.redisClientOptions);
this.redisClient = new NodeRedisAdaptor_1.default(modelOption?.redisClientOptions);
try {

@@ -172,23 +140,12 @@ this.redisClient.connect();

async getAll(options) {
var e_1, _a;
let keys = await this.redisClient.keys(`${this.keyPrefix}:*`);
if (options === null || options === void 0 ? void 0 : options.limit) {
if (options?.limit) {
keys = keys.slice(0, options.limit);
}
const results = [];
try {
// eslint-disable-next-line no-restricted-syntax
for (var keys_1 = __asyncValues(keys), keys_1_1; keys_1_1 = await keys_1.next(), !keys_1_1.done;) {
const key = keys_1_1.value;
const response = await this._read(key);
results.push(this.createInstance(response, { redisKey: key }));
}
// eslint-disable-next-line no-restricted-syntax
for await (const key of keys) {
const response = await this._read(key);
results.push(this.createInstance(response, { redisKey: key }));
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (keys_1_1 && !keys_1_1.done && (_a = keys_1.return)) await _a.call(keys_1);
}
finally { if (e_1) throw e_1.error; }
}
return results;

@@ -195,0 +152,0 @@ }

"use strict";
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });

@@ -21,2 +10,3 @@ const Utilities_1 = require("./Utilities");

class ModelInstance {
_Model;
/**

@@ -31,8 +21,2 @@ * Represents an object produced from Metronom ORM Model

constructor(data, model, dataInfo) {
Object.defineProperty(this, "_Model", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this._Model = {

@@ -51,3 +35,3 @@ _model: model,

async save() {
const _a = this, { _Model } = _a, data = __rest(_a, ["_Model"]);
const { _Model, ...data } = this;
const { redisClient, flexSchema, schema } = _Model._model;

@@ -61,3 +45,3 @@ await (0, Utilities_1.safeWrite)(data, _Model._dataInfo.redisKey, redisClient, schema, flexSchema);

getPureData() {
const _a = this, { _Model } = _a, data = __rest(_a, ["_Model"]);
const { _Model, ...data } = this;
return data;

@@ -64,0 +48,0 @@ }

@@ -77,6 +77,6 @@ "use strict";

if (!isFlex) { // if isFlex is falsy, you can only save fields inside the schema
const temp = Object.assign({}, data);
const temp = { ...data };
data = {};
Object.entries(schema).forEach(([key, value]) => {
if (value.default === null || value.default === undefined) {
if (Object.hasOwn(data, key)) {
data[key] = value.default;

@@ -83,0 +83,0 @@ }

{
"name": "metronom",
"version": "2.1.0",
"version": "2.2.0",
"description": "Easy to use Redis ORM based on node-redis",

@@ -32,3 +32,3 @@ "main": "dist/index.js",

"lint:fix": "npm run lint -- --fix",
"doc": "typedoc lib/*.ts"
"doc": "typedoc --plugin typedoc-plugin-markdown --out docs lib/*.ts"
},

@@ -47,2 +47,3 @@ "dependencies": {

"typedoc": "^0.23.2",
"typedoc-plugin-markdown": "^3.14.0",
"typescript": "^4.5.5"

@@ -57,3 +58,3 @@ },

},
"homepage": "https://github.com/anchovycation/metronom"
"homepage": "https://anchovycation.github.io/metronom/"
}

@@ -21,7 +21,15 @@ <h1 align="center">

It is used effortlessly without installing any plugins like RedisJSON. The system works with Hashes. It shreds the objects and saves them as key strings in the hash, and while reading, they break it down again according to the given scheme and type conversion with TypeScript.
It is used effortlessly without installing any plugins like RedisJSON. The system works with Hashes. It shreds the objects and saves them as key strings in the hash, and while reading, they break it down again according to the given scheme and type conversion with TypeScript. ***Also you can use String Data type too.***
> Although currently only Hash and String types are processed, our [new version](https://github.com/anchovycation/metronom/milestone/2 "see v3.0.0 milestone") that will support [all core types](https://redis.io/docs/data-types/) is on the way.
| Documentation | Source Code | Package |
| ------- | ----------- | ------- |
| [anchovycation.github.io/metronom](https://anchovycation.github.io/metronom/) | [GitHub](https://github.com/anchovycation/metronom) | [npm](https://www.npmjs.com/package/metronom) |
---
## Let's start
### 1. Install `metronom`
Firstly, instal this package to your project via your package manager.
Firstly, install this package to your project via your package manager.

@@ -43,7 +51,17 @@ **npm**:

const metronom = new Metronom({
host: '172.168.1.123',
port: 1234
redisClientOptions: {
host: '172.168.1.123',
port: 1234
}
});
```
#### 2.1 Get/Set String Key
Now, you can get/set key from defined metronom object
```js
const isSuccess = await metronom.setKey('foo', 'bar'); // its return "OK"
const value = await metronom.getKey('foo'); // bar
```
### 3. Define `Model`

@@ -69,4 +87,7 @@ `Model` is redis hash maper. It has two diffirent flow.

const metronom = new Metronom({
url: "redis://localhost:6380",
// redisClient options
redisClientOptions: {
host: '172.168.1.123',
port: 1234
},
log: LogLevels.Error
});

@@ -127,4 +148,2 @@

```
**Source Code**: [anchovycation/metronom](https://github.com/anchovycation/metronom)
**NPM Package**: [https://www.npmjs.com/package/metronom](https://www.npmjs.com/package/metronom)

@@ -137,3 +156,7 @@ ## Commands

const metronom = new Metronom({
url: 'redis://localhost:6380',
redisClientOptions: {
url: 'redis://localhost:6380',
// host: '172.168.1.123',
// port: 1234
}
});

@@ -166,2 +189,28 @@ ```

#### `setKey`
Set String key
**Paramaters:**
| paramater | Type | Default Value |
| --- | ---- | ------------- |
| key | `string` | |
| value | `string` | |
```js
const isOk = await metronom.setKey('foo', 'bar'); // OK
```
#### `getKey`
Get String key
**Paramaters:**
| paramater | Type | Default Value |
| --- | ---- | ------------- |
| key | `string` | |
```js
// await metronom.setKey('foo', 'bar');
const value = await metronom.getKey('foo'); // bar
```
### Model Basics

@@ -168,0 +217,0 @@ Represents the Redis object you created in your database. You can create, read, update, delete, filter operations. It also includes system information.

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc