Join our webinar on Wednesday, June 26, at 1pm EDTHow Chia Mitigates Risk in the Crypto Industry.Register
Socket
Socket
Sign inDemoInstall

@n1md7/indexeddb-promise

Package Overview
Dependencies
8
Maintainers
1
Versions
32
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 6.1.1 to 7.0.0

tests/DB.test.ts

5

lib/array-sorter.js

@@ -33,3 +33,2 @@ "use strict";

return data.sort(function (next, current) {
var _a, _b, _c, _d;
// Sorting by number key

@@ -40,5 +39,5 @@ if (!isNaN(current) && !isNaN(next)) {

// Alphabetical sorting
if (((_a = current) === null || _a === void 0 ? void 0 : _a.toLowerCase()) > ((_b = next) === null || _b === void 0 ? void 0 : _b.toLowerCase()))
if ((current === null || current === void 0 ? void 0 : current.toLowerCase()) > (next === null || next === void 0 ? void 0 : next.toLowerCase()))
return -1;
if (((_c = current) === null || _c === void 0 ? void 0 : _c.toLowerCase()) < ((_d = next) === null || _d === void 0 ? void 0 : _d.toLowerCase()))
if ((current === null || current === void 0 ? void 0 : current.toLowerCase()) < (next === null || next === void 0 ? void 0 : next.toLowerCase()))
return 1;

@@ -45,0 +44,0 @@ return 0;

@@ -6,3 +6,3 @@ import { Optional } from 'utility-types';

protected readonly config: ConfigType | ConfigType<Function>;
private readonly __connection;
private __connection;
protected readonly databaseName: string;

@@ -12,4 +12,5 @@ protected readonly tables: string[];

constructor(config: ConfigType | ConfigType<Function>);
connect(): Promise<IDBDatabase>;
get configuration(): ConfigType<TableType> | ConfigType<Function>;
get connection(): Promise<IDBDatabase>;
get connection(): IDBDatabase;
/**

@@ -16,0 +17,0 @@ * @description This method is used to get the indexes of the table, verify and return it.

39

lib/Database.js

@@ -67,5 +67,5 @@ "use strict";

function Database(config) {
var _this = this;
var _a;
this.config = config;
this.__connection = null;
this.databaseName = 'DefaultDatabase';

@@ -93,2 +93,3 @@ this.tables = ['DefaultTable'];

timestamps: classMeta.timestamps,
initData: classMeta.initialData,
primaryKey: {},

@@ -128,3 +129,6 @@ indexes: {},

this.databaseVersion = this.config.version;
this.__connection = new Promise(function (resolve, reject) {
}
Database.prototype.connect = function () {
var _this = this;
return new Promise(function (resolve, reject) {
if (!window || !('indexedDB' in window) || !('open' in window.indexedDB)) {

@@ -136,13 +140,13 @@ return reject('Unsupported environment');

request.onsuccess = function () {
var __connection = request.result;
__connection.onversionchange = function () {
console.info("[" + _this.databaseName + "]: Database version changed.");
console.info("[" + _this.databaseName + "]: Connection closed.");
__connection.close();
_this.__connection = request.result;
_this.__connection.onversionchange = function () {
console.info("[".concat(_this.databaseName, "]: Database version changed."));
console.info("[".concat(_this.databaseName, "]: Connection closed."));
_this.__connection.close();
};
return resolve(__connection);
return resolve(_this.__connection);
};
request.onblocked = function () {
request.result.close();
console.error("[" + _this.databaseName + "]: " + (request.error || 'Database blocked'));
console.error("[".concat(_this.databaseName, "]: ").concat(request.error || 'Database blocked'));
};

@@ -153,3 +157,3 @@ request.onupgradeneeded = function (event) {

});
}
};
Object.defineProperty(Database.prototype, "configuration", {

@@ -194,3 +198,3 @@ get: function () {

request.onblocked = function () {
console.log("[" + name + "]: Couldn't delete database due to the operation being blocked");
console.log("[".concat(name, "]: Couldn't delete database due to the operation being blocked"));
};

@@ -220,3 +224,3 @@ request.onsuccess = function () { return resolve('Database has been removed'); };

db.deleteObjectStore(table.name);
console.info("[" + database.name + "]: DB version changed, removing table: " + table.name + " for the fresh start");
console.info("[".concat(database.name, "]: DB version changed, removing table: ").concat(table.name, " for the fresh start"));
}

@@ -273,2 +277,4 @@ store = db.createObjectStore(table.name, {

Database.prototype.useModel = function (target) {
if (this.connection === null)
throw new Error('Database is not connected. Did you call .connect()?');
var tableName = { value: '' };

@@ -282,3 +288,3 @@ if (typeof target === 'string')

if (!this.tables.includes(tableName.value)) {
throw new Error("[" + this.databaseName + "]: Table [" + tableName.value + "] does not exist.");
throw new Error("[".concat(this.databaseName, "]: Table [").concat(tableName.value, "] does not exist."));
}

@@ -289,5 +295,6 @@ var table = this.config.tables.find(function (_a) {

});
if (typeof target === 'string')
return new Model_1.default(this.__connection, table);
return new Model_1.default(this.__connection, table);
if (typeof target === 'string') {
return new Model_1.default(this.connection, table);
}
return new Model_1.default(this.connection, table, target);
};

@@ -294,0 +301,0 @@ return Database;

@@ -5,2 +5,3 @@ import 'reflect-metadata';

timestamps: boolean;
initialData: Record<string, IDBValidKey | IDBKeyRange>[];
};

@@ -61,2 +62,3 @@ declare type IndexedPropertyType = Partial<{

export declare const Indexed: (options?: IndexedPropertyType) => (target: any, propertyName: PropertyType) => void;
export declare const getPrimaryKey: (target: Function) => string;
export {};

@@ -14,3 +14,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.Indexed = exports.PrimaryKey = exports.getClassMetadata = exports.getPropertyMetadata = exports.Table = void 0;
exports.getPrimaryKey = exports.Indexed = exports.PrimaryKey = exports.getClassMetadata = exports.getPropertyMetadata = exports.Table = void 0;
require("reflect-metadata");

@@ -28,2 +28,3 @@ var PROPERTY_ATTRIBUTE_OPTIONS = Symbol('PROPERTY_ATTRIBUTE_OPTIONS');

timestamps: false,
initialData: [],
};

@@ -102,2 +103,12 @@ var assignOptions = __assign(__assign({}, defaultOptions), options);

exports.Indexed = Indexed;
var getPrimaryKey = function (target) {
var properties = getPropertyMetadata(target);
var propertyEntries = Object.entries(properties);
for (var _i = 0, propertyEntries_1 = propertyEntries; _i < propertyEntries_1.length; _i++) {
var _a = propertyEntries_1[_i], propertyName = _a[0], property = _a[1];
if (property.primaryKey)
return propertyName;
}
};
exports.getPrimaryKey = getPrimaryKey;
//# sourceMappingURL=Decorators.js.map
export { Database } from './Database';
export { default as Model } from './Model';
export * from './Decorators';
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {

@@ -12,7 +16,12 @@ if (k2 === undefined) k2 = k;

};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Database = void 0;
exports.Model = exports.Database = void 0;
var Database_1 = require("./Database");
Object.defineProperty(exports, "Database", { enumerable: true, get: function () { return Database_1.Database; } });
var Model_1 = require("./Model");
Object.defineProperty(exports, "Model", { enumerable: true, get: function () { return __importDefault(Model_1).default; } });
__exportStar(require("./Decorators"), exports);
//# sourceMappingURL=index.js.map
import { Optional } from 'utility-types';
import { OptionsType, TableType, TimeStampsType } from './types';
export default class Model<DataType extends Optional<TimeStampsType>> {
private readonly connection;
private readonly db;
private readonly table;
constructor(connection: Promise<IDBDatabase>, table: TableType);
private readonly tableClass;
constructor(db: IDBDatabase, table: TableType, tableClass?: Function);
/**

@@ -37,2 +38,3 @@ * @description This method is used to insert data into the table.

deleteByPk(pKey: IDBValidKey | IDBKeyRange): Promise<IDBValidKey | IDBKeyRange | undefined>;
private resolveValue;
}

@@ -55,6 +55,10 @@ "use strict";

var Database_1 = require("./Database");
var class_transformer_1 = require("class-transformer");
var Decorators_1 = require("./Decorators");
var Model = /** @class */ (function () {
function Model(connection, table) {
this.connection = connection;
function Model(db, table, tableClass) {
if (tableClass === void 0) { tableClass = null; }
this.db = db;
this.table = table;
this.tableClass = tableClass;
}

@@ -70,14 +74,22 @@ /**

try {
var verifiedInsertData_1 = __assign(__assign({}, Database_1.Database.verify(data, [_this.table])), (_this.table.timestamps && {
var verifiedInsertData = __assign(__assign({}, Database_1.Database.verify(data, [_this.table])), (_this.table.timestamps && {
createdAt: Date.now(),
updatedAt: Date.now(),
}));
_this.connection.then(function (db) {
var request = db
.transaction(_this.table.name, 'readwrite')
.objectStore(_this.table.name)
.add(verifiedInsertData_1);
request.onsuccess = function () { return resolve(data); };
request.onerror = function () { return reject(request.error || 'Unable to add data. Check the unique values'); };
});
var primary_1 = { key: null };
try {
primary_1.key = (0, Decorators_1.getPrimaryKey)(_this.tableClass);
}
catch (e) {
// No primary key found
}
var request_1 = _this.db
.transaction(_this.table.name, 'readwrite')
.objectStore(_this.table.name)
.add(verifiedInsertData);
request_1.onsuccess = function () {
var _a;
return resolve(_this.resolveValue(__assign(__assign({}, data), (primary_1.key && (_a = {}, _a[primary_1.key] = request_1.result, _a)))));
};
request_1.onerror = function () { return reject(request_1.error || 'Unable to add data. Check the unique values'); };
}

@@ -99,9 +111,7 @@ catch (e) {

return [2 /*return*/, new Promise(function (resolve, reject) {
_this.connection.then(function (db) {
var transaction = db.transaction(_this.table.name, 'readonly');
var objectStore = transaction.objectStore(_this.table.name);
var request = objectStore.get(pKey);
request.onerror = function () { return reject(request.error || 'Unable to retrieve data from the model'); };
request.onsuccess = function () { return resolve(request.result); };
});
var transaction = _this.db.transaction(_this.table.name, 'readonly');
var objectStore = transaction.objectStore(_this.table.name);
var request = objectStore.get(pKey);
request.onerror = function () { return reject(request.error || 'Unable to retrieve data from the model'); };
request.onsuccess = function () { return resolve(_this.resolveValue(request.result)); };
})];

@@ -119,9 +129,7 @@ });

return [2 /*return*/, new Promise(function (resolve, reject) {
_this.connection.then(function (db) {
var transaction = db.transaction(_this.table.name, 'readonly');
var objectStore = transaction.objectStore(_this.table.name);
var request = objectStore.index(indexName).get(value);
request.onerror = function () { return reject(request.error || "Unable to retrieve data from the model by " + indexName); };
request.onsuccess = function () { return resolve(request.result); };
});
var transaction = _this.db.transaction(_this.table.name, 'readonly');
var objectStore = transaction.objectStore(_this.table.name);
var request = objectStore.index(indexName).get(value);
request.onerror = function () { return reject(request.error || "Unable to retrieve data from the model by ".concat(indexName)); };
request.onsuccess = function () { return resolve(_this.resolveValue(request.result)); };
})];

@@ -139,8 +147,6 @@ });

return [2 /*return*/, new Promise(function (resolve, reject) {
_this.connection.then(function (db) {
var objectStore = db.transaction(_this.table.name, 'readonly').objectStore(_this.table.name);
var request = objectStore.getAll();
request.onsuccess = function () { return resolve(request.result); };
request.onerror = function () { return reject(request.error || "Can't get data from database"); };
});
var objectStore = _this.db.transaction(_this.table.name, 'readonly').objectStore(_this.table.name);
var request = objectStore.getAll();
request.onsuccess = function () { return resolve(_this.resolveValue(request.result)); };
request.onerror = function () { return reject(request.error || "Can't get data from database"); };
})];

@@ -155,8 +161,6 @@ });

return [2 /*return*/, new Promise(function (resolve, reject) {
_this.connection.then(function (db) {
var objectStore = db.transaction(_this.table.name, 'readonly').objectStore(_this.table.name);
var request = objectStore.openCursor();
request.onsuccess = function () { return resolve(request); };
request.onerror = function () { return reject(request.error || "Can't get data from database"); };
});
var objectStore = _this.db.transaction(_this.table.name, 'readonly').objectStore(_this.table.name);
var request = objectStore.openCursor();
request.onsuccess = function () { return resolve(request); };
request.onerror = function () { return reject(request.error || "Can't get data from database"); };
})];

@@ -217,13 +221,21 @@ });

return new Promise(function (resolve, reject) {
_this.connection.then(function (db) {
_this.selectByPk(pKey).then(function (fetchedData) {
var transaction = db.transaction(_this.table.name, 'readwrite');
var store = transaction.objectStore(_this.table.name);
var data = Object.assign(fetchedData, dataToUpdate);
if (_this.table.timestamps)
data.createdAt = Date.now();
var save = store.put(data);
save.onsuccess = function () { return resolve(data); };
save.onerror = function () { return reject(save.error || "Couldn't update data"); };
});
_this.selectByPk(pKey).then(function (fetchedData) {
var transaction = _this.db.transaction(_this.table.name, 'readwrite');
var store = transaction.objectStore(_this.table.name);
var data = Object.assign(fetchedData, dataToUpdate);
var primary = { key: null };
try {
primary.key = (0, Decorators_1.getPrimaryKey)(_this.tableClass);
}
catch (e) {
// No primary key found
}
if (_this.table.timestamps)
data.createdAt = Date.now();
var save = store.put(data);
save.onsuccess = function () {
var _a;
resolve(_this.resolveValue(__assign(__assign({}, data), (primary.key && (_a = {}, _a[primary.key] = save.result, _a)))));
};
save.onerror = function () { return reject(save.error || "Couldn't update data"); };
});

@@ -238,10 +250,18 @@ });

return new Promise(function (resolve, reject) {
_this.connection.then(function (db) {
var transaction = db.transaction(_this.table.name, 'readwrite');
var request = transaction.objectStore(_this.table.name).delete(pKey);
request.onsuccess = function () { return resolve(pKey); };
request.onerror = function () { return reject(request.error || "Couldn't remove an item"); };
});
var transaction = _this.db.transaction(_this.table.name, 'readwrite');
var request = transaction.objectStore(_this.table.name).delete(pKey);
request.onsuccess = function () { return resolve(pKey); };
request.onerror = function () { return reject(request.error || "Couldn't remove an item"); };
});
};
Model.prototype.resolveValue = function (value) {
var _this = this;
if (this.tableClass) {
if (Array.isArray(value)) {
return value.map(function (item) { return (0, class_transformer_1.plainToInstance)(_this.tableClass, item); });
}
return (0, class_transformer_1.plainToInstance)(this.tableClass, value);
}
return value;
};
return Model;

@@ -248,0 +268,0 @@ }());

{
"name": "@n1md7/indexeddb-promise",
"version": "6.1.1",
"version": "7.0.0",
"description": "Indexed DB wrapper with promises",

@@ -63,3 +63,2 @@ "main": "./lib/index.js",

"prettier": "2.4.1",
"reflect-metadata": "^0.1.13",
"ts-jest": "^27.0.7",

@@ -69,3 +68,6 @@ "ts-node": "^10.4.0",

"typescript": "^4.4.4",
"utility-types": "^3.10.0"
"utility-types": "^3.10.0",
"class-transformer": "^0.5.1",
"joi": "^17.6.0",
"reflect-metadata": "^0.1.13"
},

@@ -87,5 +89,12 @@ "lint-staged": {

},
"dependencies": {
"peerDependencies": {
"reflect-metadata": "^0.1.13",
"class-transformer": "^0.5.1",
"joi": "^17.5.0"
}
},
"engines": {
"node": ">=12.0.0",
"npm": ">=6.0.0"
},
"engineStrict": true
}

@@ -10,3 +10,3 @@ import { Optional } from 'utility-types';

export class Database {
private readonly __connection: Promise<IDBDatabase>;
private __connection: IDBDatabase = null;
protected readonly databaseName: string = 'DefaultDatabase';

@@ -39,2 +39,3 @@ protected readonly tables: string[] = ['DefaultTable'];

timestamps: classMeta.timestamps,
initData: classMeta.initialData,
primaryKey: {},

@@ -74,4 +75,6 @@ indexes: {},

this.databaseVersion = this.config.version;
}
this.__connection = new Promise((resolve, reject) => {
public connect(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
if (!window || !('indexedDB' in window) || !('open' in window.indexedDB)) {

@@ -84,10 +87,10 @@ return reject('Unsupported environment');

request.onsuccess = () => {
const __connection = request.result;
__connection.onversionchange = () => {
this.__connection = request.result;
this.__connection.onversionchange = () => {
console.info(`[${this.databaseName}]: Database version changed.`);
console.info(`[${this.databaseName}]: Connection closed.`);
__connection.close();
this.__connection.close();
};
return resolve(__connection);
return resolve(this.__connection);
};

@@ -186,2 +189,4 @@

public useModel<CollectionType>(target: string | ((new () => CollectionType) & Optional<TimeStampsType>)) {
if (this.connection === null) throw new Error('Database is not connected. Did you call .connect()?');
const tableName = { value: '' };

@@ -198,7 +203,8 @@ if (typeof target === 'string') tableName.value = target;

if (typeof target === 'string')
return new Model<CollectionType & Optional<TimeStampsType>>(this.__connection, table);
if (typeof target === 'string') {
return new Model<CollectionType & Optional<TimeStampsType>>(this.connection, table);
}
return new Model(this.__connection, table);
return new Model(this.connection, table, target);
}
}

@@ -6,2 +6,3 @@ import 'reflect-metadata';

timestamps: boolean;
initialData: Record<string, IDBValidKey | IDBKeyRange>[];
};

@@ -41,2 +42,3 @@ type IndexedPropertyType = Partial<{

timestamps: false,
initialData: [],
};

@@ -126,1 +128,9 @@ const assignOptions: TableDecoratorOptions = {

};
export const getPrimaryKey = (target: Function) => {
const properties = getPropertyMetadata(target);
const propertyEntries = Object.entries(properties);
for (const [propertyName, property] of propertyEntries) {
if (property.primaryKey) return propertyName;
}
};
export { Database } from './Database';
export { default as Model } from './Model';
export * from './Decorators';

@@ -5,5 +5,11 @@ import ArraySorter from './array-sorter';

import { OptionsType, OptionsWhereAsObject, TableType, TimeStampsType } from './types';
import { ClassConstructor, plainToInstance } from 'class-transformer';
import { getPrimaryKey } from './Decorators';
export default class Model<DataType extends Optional<TimeStampsType>> {
constructor(private readonly connection: Promise<IDBDatabase>, private readonly table: TableType) {}
constructor(
private readonly db: IDBDatabase,
private readonly table: TableType,
private readonly tableClass: Function = null,
) {}

@@ -24,10 +30,20 @@ /**

};
this.connection.then((db) => {
const request = db
.transaction(this.table.name, 'readwrite')
.objectStore(this.table.name)
.add(verifiedInsertData);
request.onsuccess = () => resolve(data);
request.onerror = () => reject(request.error || 'Unable to add data. Check the unique values');
});
const primary: { key: string } = { key: null };
try {
primary.key = getPrimaryKey(this.tableClass);
} catch (e) {
// No primary key found
}
const request = this.db
.transaction(this.table.name, 'readwrite')
.objectStore(this.table.name)
.add(verifiedInsertData);
request.onsuccess = () =>
resolve(
this.resolveValue({
...data,
...(primary.key && { [primary.key]: request.result }),
}) as Partial<DataType>,
);
request.onerror = () => reject(request.error || 'Unable to add data. Check the unique values');
} catch (e) {

@@ -44,9 +60,7 @@ return reject(e);

return new Promise((resolve, reject) => {
this.connection.then((db) => {
const transaction = db.transaction(this.table.name, 'readonly');
const objectStore = transaction.objectStore(this.table.name);
const request = objectStore.get(pKey);
request.onerror = () => reject(request.error || 'Unable to retrieve data from the model');
request.onsuccess = () => resolve(request.result);
});
const transaction = this.db.transaction(this.table.name, 'readonly');
const objectStore = transaction.objectStore(this.table.name);
const request: IDBRequest<DataType> = objectStore.get(pKey);
request.onerror = () => reject(request.error || 'Unable to retrieve data from the model');
request.onsuccess = () => resolve(this.resolveValue(request.result) as DataType);
});

@@ -60,9 +74,7 @@ }

return new Promise((resolve, reject) => {
this.connection.then((db) => {
const transaction = db.transaction(this.table.name, 'readonly');
const objectStore = transaction.objectStore(this.table.name);
const request = objectStore.index(indexName).get(value);
request.onerror = () => reject(request.error || `Unable to retrieve data from the model by ${indexName}`);
request.onsuccess = () => resolve(request.result);
});
const transaction = this.db.transaction(this.table.name, 'readonly');
const objectStore = transaction.objectStore(this.table.name);
const request: IDBRequest<DataType> = objectStore.index(indexName).get(value);
request.onerror = () => reject(request.error || `Unable to retrieve data from the model by ${indexName}`);
request.onsuccess = () => resolve(this.resolveValue(request.result) as DataType);
});

@@ -76,8 +88,6 @@ }

return new Promise((resolve, reject) => {
this.connection.then((db) => {
const objectStore = db.transaction(this.table.name, 'readonly').objectStore(this.table.name);
const request = objectStore.getAll();
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error || "Can't get data from database");
});
const objectStore = this.db.transaction(this.table.name, 'readonly').objectStore(this.table.name);
const request: IDBRequest<DataType[]> = objectStore.getAll();
request.onsuccess = () => resolve(this.resolveValue(request.result) as DataType[]);
request.onerror = () => reject(request.error || "Can't get data from database");
});

@@ -88,8 +98,6 @@ }

return new Promise((resolve, reject) => {
this.connection.then((db) => {
const objectStore = db.transaction(this.table.name, 'readonly').objectStore(this.table.name);
const request = objectStore.openCursor();
request.onsuccess = () => resolve(request);
request.onerror = () => reject(request.error || "Can't get data from database");
});
const objectStore = this.db.transaction(this.table.name, 'readonly').objectStore(this.table.name);
const request = objectStore.openCursor();
request.onsuccess = () => resolve(request);
request.onerror = () => reject(request.error || "Can't get data from database");
});

@@ -146,12 +154,23 @@ }

return new Promise((resolve, reject) => {
this.connection.then((db) => {
this.selectByPk(pKey).then((fetchedData) => {
const transaction = db.transaction(this.table.name, 'readwrite');
const store = transaction.objectStore(this.table.name);
const data = Object.assign(fetchedData, dataToUpdate);
if (this.table.timestamps) data.createdAt = Date.now();
const save = store.put(data);
save.onsuccess = () => resolve(data);
save.onerror = () => reject(save.error || "Couldn't update data");
});
this.selectByPk(pKey).then((fetchedData) => {
const transaction = this.db.transaction(this.table.name, 'readwrite');
const store = transaction.objectStore(this.table.name);
const data = Object.assign(fetchedData, dataToUpdate);
const primary: { key: string } = { key: null };
try {
primary.key = getPrimaryKey(this.tableClass);
} catch (e) {
// No primary key found
}
if (this.table.timestamps) data.createdAt = Date.now();
const save = store.put(data);
save.onsuccess = () => {
resolve(
this.resolveValue({
...data,
...(primary.key && { [primary.key]: save.result }),
}) as DataType,
);
};
save.onerror = () => reject(save.error || "Couldn't update data");
});

@@ -166,10 +185,19 @@ });

return new Promise((resolve, reject) => {
this.connection.then((db) => {
const transaction = db.transaction(this.table.name, 'readwrite');
const request = transaction.objectStore(this.table.name).delete(pKey);
request.onsuccess = () => resolve(pKey);
request.onerror = () => reject(request.error || "Couldn't remove an item");
});
const transaction = this.db.transaction(this.table.name, 'readwrite');
const request = transaction.objectStore(this.table.name).delete(pKey);
request.onsuccess = () => resolve(pKey);
request.onerror = () => reject(request.error || "Couldn't remove an item");
});
}
private resolveValue(value: Partial<DataType> | Partial<DataType>[]): Partial<DataType> | Partial<DataType>[] {
if (this.tableClass) {
if (Array.isArray(value)) {
return value.map((item) => plainToInstance(<ClassConstructor<DataType>>this.tableClass, item));
}
return plainToInstance(<ClassConstructor<DataType>>this.tableClass, value);
}
return value;
}
}

@@ -5,5 +5,4 @@ import { Database, Indexed, PrimaryKey, Table } from '../src';

beforeAll(() => jest.clearAllMocks());
afterEach(async () => {
jest.clearAllTimers();
});
afterEach(() => jest.clearAllTimers());
it('should throw config error "Config has to be an Object"', (done) => {

@@ -16,2 +15,30 @@ expect(() => {

it('should throw when "verify" method is lacking primary key value in insert data', function () {
try {
Database.verify(
{
username: 'test',
password: 'test',
},
[
{
name: 'users',
primaryKey: {
name: 'id',
autoIncrement: false,
unique: true,
},
indexes: {
username: { unique: true, multiEntry: false },
password: { unique: false, multiEntry: false },
},
},
],
);
} catch (e) {
expect(e).toBeInstanceOf(Error);
expect(e.message).toBe('Either include primary key as well or set {autoincrement: true}.');
}
});
it('should throw config validation errors', (done) => {

@@ -18,0 +45,0 @@ expect(() => {

@@ -1,5 +0,6 @@

import { Table, Indexed, Database, PrimaryKey, getClassMetadata, getPropertyMetadata } from '../src';
import { getClassMetadata, getPrimaryKey, getPropertyMetadata, Indexed, PrimaryKey, Table } from '../src';
test('[@Table] decorator metadata with defaults', () => {
function Test() {}
Table()(Test);

@@ -10,2 +11,3 @@ // or it can be class but for property metadata it has to be an instance

name: 'Test',
initialData: [],
timestamps: false,

@@ -17,5 +19,8 @@ });

Table({ name: 'My-Name' })(Test);
function Test() {}
expect(getClassMetadata(Test)).toEqual({
name: 'My-Name',
initialData: [],
timestamps: false,

@@ -27,5 +32,8 @@ });

Table({ name: 'My-Name', timestamps: true })(Test);
function Test() {}
expect(getClassMetadata(Test)).toEqual({
name: 'My-Name',
initialData: [],
timestamps: true,

@@ -37,2 +45,3 @@ });

class Test {}
const propertyName = 'propertyName';

@@ -52,2 +61,3 @@ Indexed()(new Test(), propertyName);

class Test {}
const propertyName = 'propertyName';

@@ -67,2 +77,3 @@ Indexed({ unique: true })(new Test(), propertyName);

class Test {}
const propertyName = 'propertyName';

@@ -80,4 +91,14 @@ Indexed({ unique: true, multiEntry: false })(new Test(), propertyName);

test('[@getPrimaryKey] decorator', () => {
class Test {}
const propertyName = 'myPrimaryKey';
PrimaryKey()(new Test(), propertyName);
const primaryKeyPropName = getPrimaryKey(Test);
expect(primaryKeyPropName).toBe(propertyName);
});
test('[@PrimaryKey] decorator metadata with defaults', () => {
class Test {}
const propertyName = 'propertyName';

@@ -97,2 +118,3 @@ PrimaryKey()(new Test(), propertyName);

class Test {}
const propertyName = 'propertyName';

@@ -112,2 +134,3 @@ PrimaryKey({ unique: false })(new Test(), propertyName);

class Test {}
const propertyName = 'propertyName';

@@ -127,2 +150,3 @@ PrimaryKey({ unique: false, autoIncrement: false })(new Test(), propertyName);

class Users {}
Table()(Users);

@@ -135,2 +159,3 @@ PrimaryKey()(new Users(), 'id');

timestamps: false,
initialData: [],
});

@@ -161,2 +186,3 @@ expect(getPropertyMetadata(Users)).toEqual({

class Users {}
Table({ name: '__Table__', timestamps: true })(Users);

@@ -169,2 +195,3 @@ PrimaryKey({ autoIncrement: false, unique: true })(new Users(), 'id');

timestamps: true,
initialData: [],
});

@@ -195,2 +222,3 @@ expect(getPropertyMetadata(Users)).toEqual({

class Users {}
Table({ name: '__Table__', timestamps: true })(Users);

@@ -210,2 +238,3 @@ Table({ name: 'Actual_Name', timestamps: false })(Users);

timestamps: false,
initialData: [],
});

@@ -212,0 +241,0 @@ expect(getPropertyMetadata(Users)).toEqual({

import { Database } from '../src';
function* id() {
for (let i = 0; i < 128; i++) yield String(i).padStart(2, '0');
}
describe('IndexedDB', () => {
const ref = { i: 1 };
beforeAll(() => jest.clearAllMocks());
beforeEach(() => {
ref.i++;
jest.clearAllMocks();
});
afterEach(async () => {
jest.clearAllTimers();
});
beforeEach(() => jest.clearAllMocks());

@@ -18,6 +15,6 @@ it('should be defined', () => {

it('should create store and verify methods', () => {
it('should create store and verify methods', async () => {
const db = new Database({
version: 1,
name: `Test-db-0${ref.i}`,
name: `Test-db${id().next().value}`,
tables: [

@@ -42,2 +39,3 @@ {

});
await db.connect();
const table = db.useModel('users');

@@ -59,3 +57,3 @@ expect(table.insert).toBeDefined();

version: 1,
name: `Test-db-0${ref.i}`,
name: `Test-db${id().next().value}`,
tables: [

@@ -77,9 +75,11 @@ {

});
const data = { username: 'michael', password: 'passwd' };
const table = db.useModel('users');
table.insert(data).then((inserted) => {
expect(inserted).toEqual(data);
table.selectAll().then((all) => {
expect(all).toEqual(expect.arrayContaining(initData.concat(data)));
done();
db.connect().then(() => {
const data = { username: 'michael', password: 'passwd' };
const table = db.useModel('users');
table.insert(data).then((inserted) => {
// expect(inserted).toEqual(data);
table.selectAll().then((all) => {
expect(all).toEqual(expect.arrayContaining(initData.concat(data)));
done();
});
});

@@ -92,3 +92,3 @@ });

version: 1,
name: `Test-db-0${ref.i}`,
name: `Test-db${id().next().value}`,
tables: [

@@ -113,6 +113,8 @@ {

});
const model = db.useModel('users');
model.selectByPk('admin').then((selected) => {
expect(selected).toEqual({ username: 'admin', password: 'admin123' });
done();
db.connect().then(() => {
const model = db.useModel('users');
model.selectByPk('admin').then((selected) => {
expect(selected).toEqual({ username: 'admin', password: 'admin123' });
done();
});
});

@@ -124,3 +126,3 @@ });

version: 1,
name: `Test-db-0${ref.i}`,
name: `Test-db${id().next().value}`,
tables: [

@@ -145,2 +147,3 @@ {

});
await db.connect();
const _data = await db.useModel('users').selectAll();

@@ -150,6 +153,6 @@ expect(_data).not.toBeNull();

it('should verify .selectByIndex', () => {
it('should verify .selectByIndex', async () => {
const db = new Database({
version: 1,
name: `Test-db-0${ref.i}`,
name: `Test-db${id().next().value}`,
tables: [

@@ -174,2 +177,3 @@ {

});
await db.connect();
const model = db.useModel('users');

@@ -184,3 +188,3 @@ model.selectByIndex('username', 'admin').then((data) => {

version: 1,
name: `Test-db-0${ref.i}`,
name: `Test-db${id().next().value}`,
tables: [

@@ -205,2 +209,3 @@ {

});
await db.connect();
const model = db.useModel('users');

@@ -270,3 +275,3 @@ expect(

version: 1,
name: `Test-db-0${ref.i}`,
name: `Test-db${id().next().value}`,
tables: [

@@ -291,2 +296,3 @@ {

});
await db.connect();
const model = db.useModel('users');

@@ -306,3 +312,3 @@ const update = await model.updateByPk('admin', {

version: 1,
name: `Test-db-0${ref.i}`,
name: `Test-db${id().next().value}`,
tables: [

@@ -327,2 +333,3 @@ {

});
await db.connect();
const model = db.useModel('users');

@@ -337,3 +344,3 @@ const deleted = await model.deleteByPk('admin');

version: 1,
name: `Test-db-0${ref.i}`,
name: `Test-db${id().next().value}`,
tables: [

@@ -363,34 +370,2 @@ {

it('should throw Unsupported environment', () => {
jest.spyOn(window.indexedDB, 'open').mockImplementation(() => {
throw new Error('Unsupported environment');
});
new Database({
version: 1,
name: `Test-db-0${ref.i}`,
tables: [
{
name: 'users',
primaryKey: {
name: 'username',
autoIncrement: false,
unique: true,
},
initData: [
{ username: 'n1md7', password: 'passwd' },
{ username: 'admin', password: 'admin123' },
],
indexes: {
username: { unique: true, multiEntry: false },
password: { unique: false, multiEntry: false },
},
},
],
}).connection.catch((err) => {
expect(err).toBeInstanceOf(Error);
expect(err.message).toBe('Unsupported environment');
});
});
it('should throw Config has to be an Object', () => {

@@ -397,0 +372,0 @@ jest.spyOn(window.indexedDB, 'open').mockImplementation(() => {

@@ -26,5 +26,7 @@ import Model from '../src/Model';

});
const model = new Model(database.connection, null);
model.insert({}).catch((error) => {
expect(error.message).toBe('Tables should not be empty/undefined');
database.connect().then(() => {
const model = new Model(database.connection, null);
model.insert({}).catch((error) => {
expect(error.message).toBe('Tables should not be empty/undefined');
});
});

@@ -55,48 +57,11 @@ });

const model = new Model(database.connection, users);
model
.insert({
username: 'nimda',
})
.catch((error) => {
expect(error.message).toBe('Either include primary key as well or set {autoincrement: true}.');
});
});
it('should throw an error on transaction insert', function () {
const connectionMock = jest.fn().mockResolvedValue({
transaction: () => ({
objectStore: () => ({
add: () => ({
onsuccess: () => {},
onerror: () => {},
}),
}),
}),
database.connect().then(() => {
model
.insert({
username: 'nimda',
})
.catch((error) => {
expect(error.message).toBe('Either include primary key as well or set {autoincrement: true}.');
});
});
jest.spyOn(Database.prototype, 'connection', 'get').mockImplementation(connectionMock);
const users = {
name: 'users',
primaryKey: {
name: 'id',
autoIncrement: true,
unique: true,
},
indexes: {
username: {
unique: false,
multiEntry: true,
},
},
timestamps: true,
};
const database = new Database({
version: 1,
name: 'Todo-list',
tables: [users],
});
const model = new Model(database.connection, users);
model.insert({ username: 'nimda' }).then(() => {
expect(connectionMock).toHaveBeenCalledTimes(1);
});
});

@@ -107,14 +72,2 @@ });

it('should resolve cursor value', function () {
const connectionMock = jest.fn().mockResolvedValue({
transaction: () => ({
objectStore: () => ({
openCursor: () => ({
onsuccess: () => {},
onerror: () => {},
}),
}),
}),
});
jest.spyOn(Database.prototype, 'connection', 'get').mockImplementation(connectionMock);
const users = {

@@ -133,3 +86,2 @@ name: 'users',

},
timestamps: true,
};

@@ -141,7 +93,11 @@ const database = new Database({

});
const model = new Model(database.connection, users);
model.openCursor().then(() => {
expect(connectionMock).toHaveBeenCalledTimes(1);
database.connect().then(() => {
const model = new Model(database.connection, users);
model.insert({ username: 'nimda' }).then(() => {
model.openCursor().then((data) => {
expect(data).toBeDefined();
});
});
});
});
});

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

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