From 9db23d54f7183ac0563b541391b9e5cab8810e8d Mon Sep 17 00:00:00 2001 From: artus9033 Date: Fri, 24 Jul 2020 09:54:30 +0200 Subject: [PATCH] Initial commit; added types; added compilation scripts --- .gitignore | 2 + .prettierrc.json | 6 + LICENSE | 5 + README.md | 318 ++++++++++++++++++++++++++++++++++++++++++++++ package-lock.json | 95 ++++++++++++++ package.json | 26 ++++ src/collection.ts | 141 ++++++++++++++++++++ src/index.ts | 85 +++++++++++++ src/util.ts | 170 +++++++++++++++++++++++++ tsconfig.json | 14 ++ 10 files changed, 862 insertions(+) create mode 100644 .gitignore create mode 100644 .prettierrc.json create mode 100644 LICENSE create mode 100644 README.md create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 src/collection.ts create mode 100644 src/index.ts create mode 100644 src/util.ts create mode 100644 tsconfig.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..db4c6d9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +dist +node_modules \ No newline at end of file diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 0000000..0c34c10 --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,6 @@ +{ + "printWidth": 100, + "useTabs": true, + "semi": true, + "tabWidth": 4 +} diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..7c9ed9f --- /dev/null +++ b/LICENSE @@ -0,0 +1,5 @@ +Original project code base +Copyright (c) 2014 Arvind Ravulavaru. Licensed under the MIT license. + +TypeScript port & modifications to the code made +Copyright (c) 2020 artus9033. Licensed under the MIT license. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..ef2d53f --- /dev/null +++ b/README.md @@ -0,0 +1,318 @@ +# diskDB + +A Lightweight Disk based JSON Database with a MongoDB like API for Node, written in TypeScript. + +## Contents + +- [diskDB](#diskdb) + - [Contents](#contents) + - [Getting Started](#getting-started) + - [Documentation](#documentation) + - [Connect to DB](#connect-to-db) + - [Load Collections](#load-collections) + - [Load Multiple Collections](#load-multiple-collections) + - [Write/Save to Collection](#writesave-to-collection) + - [Read from Collection](#read-from-collection) + - [db.collectionName.find()](#dbcollectionnamefind) + - [db.collectionName.findOne(query)](#dbcollectionnamefindonequery) + - [Update Collection](#update-collection) + - [Remove Collection](#remove-collection) + - [Count](#count) + +## Getting Started +Install the module locally : +```bash +$ npm install tsdiskdb +``` + +```js +var db = require('tsdiskdb'); +db = db.connect('/path/to/db-folder', ['collection-name']); +// you can access the traditional JSON DB methods here +``` + +## Documentation +### Connect to DB +```js +db.connect(pathToFolder, ['filename']); +``` +Filename will be the name of the JSON file. You can omit the extension, tsdiskDB will take care of it for you. + +```js +var db = require('tsdiskdb'); +db = db.connect('/examples/db', ['articles']); +// or simply +db.connect('/examples/db', ['articles']); +``` + +This will check for a directory at given path, if it does not exits, tsdiskDB will throw an error and exit. + +If the directory exists but the file/collection does not exist, tsdiskDB will create it for you. + +**Note** : If you have manually created a JSON file, please make sure it contains a valid JSON array, otherwise tsdiskDB +will return an empty array. + +```js +[] +``` +Else it will throw an error like + +```bash +undefined:0 + +^ +SyntaxError: Unexpected end of input +``` +--- +### Load Collections +Alternatively you can also load collections like + +```js +var db = require('tsdiskdb'); +// this +db = db.connect('/examples/db'); +db.loadCollections(['articles']); +//or +db.connect('/examples/db'); +db.loadCollections(['articles']); +//or +db.connect('/examples/db') + .loadCollections(['articles']); +//or +db.connect('/examples/db', ['articles']); +``` +#### Load Multiple Collections + +```js +var db = require('tsdiskdb'); +db.connect('/examples/db', ['articles','comments','users']); +``` +--- +### Write/Save to Collection +```js +db.collectionName.save(object); +``` +Once you have loaded a collection, you can access the collection's methods using the dot notation like + +```js +db.[collectionName].[methodname] +``` +To save the data, you can use +```js +var db = require('tsdiskdb'); +db.connect('db', ['articles']); +var article = { + title : "tsdiskDB rocks", + published : "today", + rating : "5 stars" +} +db.articles.save(article); +// or +db.articles.save([article]); +``` +The saved data will be +```js +[ + { + "title": "tsdiskDB rocks", + "published": "today", + "rating": "5 stars", + "_id": "0f6047c6c69149f0be0c8f5943be91be" + } +] +``` +You can also save multiple objects at once like + +```js +var db = require('tsdiskdb'); +db.connect('db', ['articles']); +var article1 = { + title : 'tsdiskDB rocks', + published : 'today', + rating : '5 stars' +} + +var article2 = { + title : 'tsdiskDB rocks', + published : 'yesterday', + rating : '5 stars' +} + +var article3 = { + title : 'tsdiskDB rocks', + published : 'today', + rating : '4 stars' +} +db.articles.save([article1, article2, article3]); +``` +And this will return the inserted objects + +```js +[ { title: 'tsdiskDB rocks', + published: 'today', + rating: '4 stars', + _id: 'b1cdbb3525b84e8c822fc78896d0ca7b' }, + { title: 'tsdiskDB rocks', + published: 'yesterday', + rating: '5 stars', + _id: '42997c62e1714e9f9d88bf3b87901f3b' }, + { title: 'tsdiskDB rocks', + published: 'today', + rating: '5 stars', + _id: '4ca1c1597ddc4020bc41b4418e7a568e' } ] +``` +--- +### Read from Collection +There are 2 methods available for reading the JSON collection +* db.collectionName.find(query) +* db.collectionName.findOne(query) + + +#### db.collectionName.find() +```js +var db = require('tsdiskdb'); +db.connect('/examples/db', ['articles']); +db.articles.find(); +``` +This will return all the records +```js +[{ + title: 'tsdiskDB rocks', + published: 'today', + rating: '5 stars', + _id: '0f6047c6c69149f0be0c8f5943be91be' +}] +``` +You can also query with a criteria like +```js +var db = require('tsdiskdb'); +db.connect('/examples/db', ['articles']); +db.articles.find({rating : "5 stars"}); +``` +This will return all the articles which have a rating of 5. + +Find can take multiple criteria +```js +var db = require('tsdiskdb'); +db.connect('/examples/db', ['articles']); +db.articles.find({rating : "5 stars", published: "yesterday"}); +``` +This will return all the articles with a rating of 5, published yesterday. + +Nested JSON : + +```js +var articleComments = { + title: 'tsdiskDB rocks', + published: '2 days ago', + comments: [{ + name: 'a user', + comment: 'this is cool', + rating: 2 + }, { + name: 'b user', + comment: 'this is ratchet', + rating: 3 + }, { + name: 'c user', + comment: 'this is awesome', + rating: 2 + }] +} +``` +```js +var savedArticle = db.articles.save([articleComments); +foundArticles = db.articles.find({rating : 2}); +``` +Since tsdiskDB is mostly for light weight data storage, avoid nested structures and huge datasets. + +#### db.collectionName.findOne(query) +```js +var db = require('tsdiskdb'); +db.connect('/examples/db', ['articles']); +db.articles.findOne(); +``` + +If you do not pass a query, tsdiskDB will return the first article in the collection. If you pass a query, it will return first article in the filtered data. + +```js +var db = require('tsdiskdb'); +db.connect('/examples/db', ['articles']); +db.articles.findOne({_id: '0f6047c6c69149f0be0c8f5943be91be'}); +``` +--- +### Update Collection +```js +db.collectionName.update(query, data, options); +``` + +You can also update one or many objects in the collection +```js +options = { + multi: false, // update multiple - default false + upsert: false // if object is not found, add it (update-insert) - default false +} +``` +Usage +```js +var db = require('tsdiskdb'); +db.connect('/examples/db', ['articles']); + +var query = { + title : 'tsdiskDB rocks' +}; + +var dataToBeUpdate = { + title : 'tsdiskDB rocks again!', +}; + +var options = { + multi: false, + upsert: false +}; + +var updated = db.articles.update(query, dataToBeUpdate, options); +console.log(updated); // { updated: 1, inserted: 0 } +``` +--- +### Remove Collection +```js +db.collectionName.remove(query, multi); +``` +You can remove the entire collection (including the file) or you can remove the matched objects by passing in a query. When you pass a query, you can either delete all the matched objects or only the first one by passing `multi` as `false`. The default value of `multi` is `true`. + +```js +var db = require('tsdiskdb'); +db.connect('/examples/db', ['articles']); +db.articles.remove({rating : "5 stars"}); +``` +```js +var db = require('tsdiskdb'); +db.connect('/examples/db', ['articles']); +db.articles.remove({rating : "5 stars"}, true); // remove all matched. Default - multi = true +``` + +```js +var db = require('tsdiskdb'); +db.connect('/examples/db', ['articles']); +db.articles.remove({rating : "5 stars"}, false); // remove only the first match +``` +Using remove without any params will delete the file and will remove the db instance. +```js +var db = require('tsdiskdb'); +db.connect('/examples/db', ['articles']); +db.articles.remove(); +``` +After the above operation `db.articles` is `undefined`. + +--- +### Count +```js +db.collectionName.count(); +``` +Will return the count of objects in the Collection +```js +var db = require('tsdiskdb'); +db.connect('/examples/db', ['articles']); +db.articles.count(); // will give the count +``` \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..e3aaa8b --- /dev/null +++ b/package-lock.json @@ -0,0 +1,95 @@ +{ + "name": "tsdiskdb", + "version": "1.0.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "@types/color-name": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@types/color-name/-/color-name-1.1.1.tgz", + "integrity": "sha512-rr+OQyAjxze7GgWrSaJwydHStIhHq2lvY3BOC2Mj7KnzI7XK0Uw1TOOdI9lDoajEbSWLiYgoo4f1R51erQfhPQ==" + }, + "@types/lodash": { + "version": "4.14.158", + "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.14.158.tgz", + "integrity": "sha512-InCEXJNTv/59yO4VSfuvNrZHt7eeNtWQEgnieIA+mIC+MOWM9arOWG2eQ8Vhk6NbOre6/BidiXhkZYeDY9U35w==", + "dev": true + }, + "@types/node": { + "version": "14.0.25", + "resolved": "https://registry.npmjs.org/@types/node/-/node-14.0.25.tgz", + "integrity": "sha512-okMqUHqrMlGOxfDZliX1yFX5MV6qcd5PpRz96XYtjkM0Ws/hwg23FMUqt6pETrVRZS+EKUB5HY19mmo54EuQbA==", + "dev": true + }, + "@types/uuid": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-8.0.0.tgz", + "integrity": "sha512-xSQfNcvOiE5f9dyd4Kzxbof1aTrLobL278pGLKOZI6esGfZ7ts9Ka16CzIN6Y8hFHE1C7jIBZokULhK1bOgjRw==", + "dev": true + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==" + }, + "lodash": { + "version": "4.17.19", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.19.tgz", + "integrity": "sha512-JNvd8XER9GQX0v2qJgsaN/mzFCNA5BRe/j8JN9d+tWyGLSodKQHKFicdwNYzWwI3wjRnaKPsGj1XkBjx/F96DQ==" + }, + "merge": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/merge/-/merge-1.2.1.tgz", + "integrity": "sha512-VjFo4P5Whtj4vsLzsYBu5ayHhoHJ0UqNm7ibvShmbmoz7tGi0vXaoJbGdB+GmDMLUdg8DpQXEIeVDAe8MaABvQ==" + }, + "supports-color": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", + "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", + "requires": { + "has-flag": "^4.0.0" + } + }, + "typescript": { + "version": "3.9.7", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.9.7.tgz", + "integrity": "sha512-BLbiRkiBzAwsjut4x/dsibSTB6yWpwT5qWmC2OfuCg3GgVQCSgMs4vEctYPhsaGtd0AeuuHMkjZ2h2WG8MSzRw==" + }, + "uuid": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.2.0.tgz", + "integrity": "sha512-CYpGiFTUrmI6OBMkAdjSDM0k5h8SkkiTP4WAjQgDgNB1S3Ou9VBEvr6q0Kv2H1mMk7IWfxYGpMH5sd5AvcIV2Q==" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..0b32b6f --- /dev/null +++ b/package.json @@ -0,0 +1,26 @@ +{ + "name": "tsdiskdb", + "version": "1.0.1", + "description": "TypeScript disk-based JSON database for storing small structures with a Mongo-like interface", + "main": "dist/index.js", + "scripts": { + "build": "tsc", + "dev": "tsc --watch", + "postinstall": "npm run build" + }, + "author": "artus9033", + "homepage": "github.com/artus9033/tsdiskdb", + "license": "MIT", + "dependencies": { + "chalk": "^4.1.0", + "lodash": "^4.17.19", + "merge": "^1.2.1", + "typescript": "^3.9.7", + "uuid": "^8.2.0" + }, + "devDependencies": { + "@types/lodash": "^4.14.158", + "@types/node": "^14.0.25", + "@types/uuid": "^8.0.0" + } +} diff --git a/src/collection.ts b/src/collection.ts new file mode 100644 index 0000000..22088cc --- /dev/null +++ b/src/collection.ts @@ -0,0 +1,141 @@ +import path from "path"; + +import { isArray } from "lodash"; +import uuid from "uuid"; + +import util, { CollectionType, ModelTypeBase, QueryType } from "./util"; +import DiskDB from "."; + +export default class Collection { + private _f: string; + + constructor(private db: DiskDB, private collectionName: string) { + this._f = path.join(this.db._db.path, this.collectionName + ".json"); + } + + find(query?: QueryType) { + var collection = JSON.parse(util.readFromFile(this._f)); + + if (!query || Object.keys(query).length === 0) { + return collection; + } else { + var searcher = new util.ObjectSearcher(); + return searcher.findAllInObject(collection, query, true); + } + } + + findOne(query?: QueryType) { + var collection = JSON.parse(util.readFromFile(this._f)); + + if (!query) { + return collection[0]; + } else { + var searcher = new util.ObjectSearcher(); + return searcher.findAllInObject(collection, query, false)[0]; + } + } + + save(data: Omit): ModelType; + save(data: Omit[]): ModelType[]; + save(data: Omit | Omit[]): ModelType | ModelType[] { + var collection = JSON.parse(util.readFromFile(this._f)) as CollectionType; + + if (isArray(data)) { + /* + if (data.length === 1) { + if (isArray(data[0]) && data[0].length > 0) { + data = data[0]; + } + }*/ + + var retCollection = []; + + for (var i = data.length - 1; i >= 0; i--) { + let d = { + ...data[i], + _id: uuid.v4().replace(/-/g, ""), + } as ModelType; + collection.push(d); + retCollection.push(d); + } + + util.writeToFile(this._f, collection); + + return retCollection; + } + + let newData = { + ...data, + _id: uuid.v4().replace(/-/g, ""), + } as ModelType; + collection.push(newData); + util.writeToFile(this._f, collection); + + return newData; + } + + update( + query: QueryType, + data: ModelType, + options?: { + multi?: boolean; + upsert?: boolean; + } + ) { + var ret: { + updated: number; + inserted: number; + } = { updated: 0, inserted: 0 }, + collection = JSON.parse(util.readFromFile(this._f)) as CollectionType; // update + + var records = util.finder(collection, query, true); + + if (records.length) { + if (options && options.multi) { + collection = util.updateFiltered(collection, query, data, true); + ret.updated = records.length; + ret.inserted = 0; + } else { + collection = util.updateFiltered(collection, query, data, false); + ret.updated = 1; + ret.inserted = 0; + } + } else { + if (options && options.upsert) { + data._id = uuid.v4().replace(/-/g, ""); + collection.push(data); + ret.updated = 0; + ret.inserted = 1; + } else { + ret.updated = 0; + ret.inserted = 0; + } + } + + util.writeToFile(this._f, collection); + + return ret; + } + + remove(query?: QueryType, multi?: boolean) { + if (query) { + var collection = JSON.parse(util.readFromFile(this._f)); + if (typeof multi === "undefined") { + multi = true; + } + collection = util.removeFiltered(collection, query, multi); + + util.writeToFile(this._f, collection); + } else { + util.removeFile(this._f); + + delete this.db[this.collectionName]; + } + + return true; + } + + count() { + return (JSON.parse(util.readFromFile(this._f)) as CollectionType).length; + } +} diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..61166c1 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,85 @@ +import path from "path"; + +import { red as e, green as s } from "chalk"; + +import Collection from "./collection"; +import util, { ModelTypeBase } from "./util"; + +type ValuesOf = T[number]; + +class DiskDB< + CollectionTypes extends { + [key: string]: ModelTypeBase; + } +> { + public _db = { + path: "", + }; + + collections: { [T in keyof CollectionTypes]: Collection } = {} as any; + + public connect(path: string, collections: Array) { + if (util.isValidPath(path)) { + this._db.path = path; + + console.log(s("Successfully connected to : " + path)); + + if (collections) { + this.loadCollections(collections as string[]); + } + } else { + console.log( + e( + "The DB Path [" + + path + + "] does not seem to be valid. Recheck the path and try again" + ) + ); + + return false; + } + return this; + } + + public loadCollections(collections: Array) { + if (!this._db) { + console.log( + e( + "Initialize the DB before you add collections. Use : ", + "db.connect('path-to-db');" + ) + ); + return false; + } + + if (typeof collections === "object" && collections.length) { + for (var i = 0; i < collections.length; i++) { + var p = path.join( + this._db.path, + ((collections[i] as string).indexOf(".json") >= 0 + ? collections[i] + : collections[i]) + ".json" + ); + + if (!util.isValidPath(p)) { + util.writeToFile(p); + } + + var _c = (collections[i] as string).replace(".json", ""); + this.collections[collections[i]] = new Collection(this, _c); + } + } else { + console.log( + e( + "Invalid Collections Array.", + "Expected Format : ", + "['collection1','collection2','collection3']" + ) + ); + } + + return this; + } +} + +export default DiskDB; diff --git a/src/util.ts b/src/util.ts new file mode 100644 index 0000000..935d57f --- /dev/null +++ b/src/util.ts @@ -0,0 +1,170 @@ +var fs = require("fs"); +var merge = require("merge"); + +export type ModelTypeBase = { _id: string }; +export type CollectionType = Array; +export type QueryType = Partial | undefined | null; + +export class util { + static isValidPath(path: string) { + return fs.existsSync(path); + } + + static writeToFile(outputFilename: string, content?: CollectionType) { + if (!content) { + content = []; + } + fs.writeFileSync(outputFilename, JSON.stringify(content, null, 0)); + } + + static readFromFile(file: string) { + return fs.readFileSync(file, "utf-8"); + } + + static removeFile(file: string) { + return fs.unlinkSync(file); + } + + static updateFiltered( + collection: CollectionType, + query: QueryType = {}, + data: Object, + multi?: boolean + ) { + // break 2 loops at once - multi : false + loop: for (var i = collection.length - 1; i >= 0; i--) { + var c = collection[i]; + + for (var p in query) { + if (p in c && c[p] == query[p]) { + collection[i] = merge(c, data); + if (!multi) { + break loop; + } + } + } + } + + return collection; + } + + static removeFiltered( + collection: CollectionType, + query: QueryType = {}, + multi?: boolean + ) { + // break 2 loops at once - multi : false + loop: for (var i = collection.length - 1; i >= 0; i--) { + var c = collection[i]; + for (var p in query) { + if (p in c && c[p] == query[p]) { + collection.splice(i, 1); + if (!multi) { + break loop; + } + } + } + } + return collection; + } + + static finder( + collection: CollectionType, + query: QueryType = {}, + multi?: boolean + ) { + var retCollection = []; + + loop: for (var i = collection.length - 1; i >= 0; i--) { + var c = collection[i]; + for (var p in query) { + if (p in c && c[p] == query[p]) { + retCollection.push(collection[i]); + if (!multi) { + break loop; + } + } + } + } + + return retCollection; + } + + /** recursive finder **/ + static ObjectSearcher = class { + results = []; + objects = []; + resultIDS = {}; + + findAllInObject(object: Object, valueOBj: Object, isMulti?: boolean) { + for (var objKey in object) { + this.performSearch(object[objKey], valueOBj, object[objKey]); + if (!isMulti && this.results.length == 1) { + return this.results; + } + } + + while (this.objects.length !== 0) { + var objRef = this.objects.pop(); + this.performSearch(objRef["_obj"], valueOBj, objRef["parent"]); + if (!isMulti && this.results.length == 1) { + return this.results; + } + } + + return this.results; + } + + performSearch(object: Object, valueOBj: Object, opt_parentObj?: Object) { + for (var criteria in valueOBj) { + var query = {}; + query[criteria] = valueOBj[criteria]; + this.searchObject(object, query, opt_parentObj); + } + + for (var i = 0; i < this.results.length; i++) { + var result = this.results[i]; + for (var field in valueOBj) { + if (result[field] !== undefined) { + if (result[field] !== valueOBj[field]) { + this.results.splice(i, 1); + } + } + } + } + } + + searchObject = function (object: Object, valueOBj: Object, opt_parentObj?: Object) { + for (var objKey in object) { + if (typeof object[objKey] != "object") { + if (valueOBj[objKey] == object[objKey]) { + if (opt_parentObj !== undefined) { + if (this.resultIDS[opt_parentObj["_id"]] === undefined) { + this.results.push(opt_parentObj); + this.resultIDS[opt_parentObj["_id"]] = ""; + } + } else { + if (this.resultIDS[object["_id"]] === undefined) { + this.results.push(object); + this.resultIDS[object["_id"]] = ""; + } + } + } + } else { + var obj = object; + if (opt_parentObj !== undefined) { + obj = opt_parentObj; + } + var objRef = { + parent: obj, + _obj: object[objKey], + }; + + this.objects.push(objRef); + } + } + }; + }; +} + +export default util; diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..f9e46af --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "module": "commonjs", + "esModuleInterop": true, + "allowSyntheticDefaultImports": true, + "target": "es6", + "noImplicitAny": false, + "moduleResolution": "node", + "sourceMap": true, + "outDir": "dist", + "rootDir": "src", + "declaration": true + } +}