Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

lowkie

Package Overview
Dependencies
Maintainers
2
Versions
23
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

lowkie - npm Package Compare versions

Comparing version 0.4.0 to 0.5.0

11

lib/model.js

@@ -23,4 +23,12 @@ 'use strict';

this.dbs[dbconnectionname].addCollection(modelName, collectionOptions);
let populate = function (refs, query) {
return Schema.populate(modelProxy, refs, query);
};
let modelHandler = {
/*get: function (target, name) {return target[ name ];},*/
// get: function (target, name) {
// if (typeof target[name] === 'function') {
// }
// return target[name];
// }
};

@@ -32,2 +40,3 @@ modelProxy.insert = new Proxy(modelProxy.insert, {

});
modelProxy.populate = populate;
let newModelProxy = new Proxy(modelProxy, modelHandler);

@@ -34,0 +43,0 @@ this.models[modelName] = newModelProxy;

145

lib/schema.js
'use strict';
const flatten = require('flat');
const ObjectId = require('./object_id');
const pluralize = require('pluralize');
var isExternalRef = function (key) {
let properties = key.split('.');
return (properties[properties.length - 1] === 'ref');
};
var isTypeDef = function (key) {
let properties = key.split('.');
return (properties[properties.length - 1] === 'type');
};
var isDefaultDef = function (key) {
let properties = key.split('.');
return (properties[properties.length - 1] === 'default');
};
/**

@@ -10,6 +27,19 @@ * proxy for creating new loki documents

class lowkieSchema {
constructor(scheme, lowkieSingleton, db = 'default') {
constructor (scheme, lowkieSingleton, db = 'default') {
this.scheme = scheme;
this.flattenedScheme = flatten(scheme);
this.validNames = Object.keys(scheme).concat(['_id', ]);
let flatKeys = Object.keys(this.flattenedScheme);
this.default_defs = flatKeys.filter(isDefaultDef);
this.external_refs = flatKeys.filter(isExternalRef);
this.type_defs = flatKeys.filter(isTypeDef);
this.validNames = Object.keys(this.flattenedScheme).reduce((result, key) => {
let properties = key.split('.');
let parentKey = properties.slice(0, properties.length - 1).join('.');
if (this.default_defs.indexOf(key) === -1 && this.external_refs.indexOf(key) === -1 && this.type_defs.indexOf(key) === -1) {
result.push(key);
} else if (result.indexOf(parentKey) === -1) {
result.push(parentKey);
}
return result;
}, []).concat(['_id']);
this.lowkie = lowkieSingleton;

@@ -21,60 +51,48 @@ this.createDoc = this.createDocument.bind(this);

}
return this;
}
/**
* returns validated document for lokijs
*
* @param {any} doc
* @returns object
*
* @memberOf lowkieSchema
*/
createDocument(doc) {
let defaultDoc = Object.keys(this.scheme).reduce((result, key)=>{
if(typeof this.scheme==='object' && this.scheme[key] && this.scheme[key].default){
if(this.scheme[key].default===Date.now){
result[key] = new Date();
} else{
result[key] = typeof this.scheme[key].default ==='function' ? this.scheme[key].default.call() : this.scheme[key].default;
validateDocument (_document) {
_document = flatten(_document);
return this.validNames.reduce((result, key) => {
if (_document[key]) {
let validType = this.flattenedScheme[`${ key }.type`] || this.flattenedScheme[key];
if (typeof _document[key] === 'string' && (validType === String || validType === ObjectId)) {
result[key] = _document[key].toString();
} else if (validType === Boolean) {
result[key] = (_document[key]) ? true : false;
} else if (validType === Number) {
result[key] = Number(_document[key]);
} else if (typeof _document[key] === 'object' && (validType === Array || validType === Object)) {
result[key] = _document[key];
}
} else if (this.default_defs.indexOf(`${ key }.default`) !== -1 && !_document[key]) {
if (this.flattenedScheme[`${ key }.default`] === Date.now) result[key] = new Date();
else result[key] = this.flattenedScheme[`${ key }.default`];
}
return result;
}, {});
let newDoc = Object.assign({}, defaultDoc, {
}, { _id: _document._id });
}
/**
* returns validated document for lokijs
*
* @param {any} doc
* @returns object
*
* @memberOf lowkieSchema
*/
createDocument (doc) {
let newDoc = Object.assign({
_id: ObjectId.createId(),
}, doc);
let validDoc = this.validNames.reduce((result, key) => {
// if (this.lowkie.config.strictSchemas) {
// if (typeof newDoc[ key ] === 'string' && (this.scheme[ key ] !== String || (this.scheme[key].type !== String))) {
// throw new Error(`${key} (${newDoc[ key ] } - ${typeof newDoc[ key ]}) must be a valid String`);
// }
// }
if (newDoc[key]) {
if (typeof newDoc[key] === 'string' && this.scheme[key] === String) {
result[key] = newDoc[key].toString();
} else if (this.scheme[key] === Boolean) {
result[key] = (newDoc[key]) ? true : false;
} else if (this.scheme[key] === Number) {
result[key] = Number(newDoc[key]);
} else if (typeof newDoc[key] === 'object') {
result[key] = newDoc[key];
} else {
result[key] = newDoc[key];
}
}
return result;
}, {});
return validDoc;
return this.validateDocument(newDoc);
}
/**
* overwrites the default insert method
*
* @param {any} options
* @returns Promise
*
* @memberOf lowkieSchema
*/
insert(options = {}) {
/**
* overwrites the default insert method
*
* @param {any} options
* @returns Promise
*
* @memberOf lowkieSchema
*/
insert (options = {}) {
let lokiCollectionInsert = options.target;

@@ -100,2 +118,25 @@ let lowkieInstance = options.thisArg;

}
populate (model, refs = '', query = {}) {
let _refs = (Array.isArray(refs)) ? refs : refs.split(' ');
_refs = _refs.map(ref => {
if (ref && typeof ref === 'object') return ref;
return { path: ref };
});
let collections = this.lowkie.dbs[this.dbconnection].collections;
let flattened = this.flattenedScheme;
let _documents = model.chain().find(query);
return _documents.data().reduce((result, doc) => {
let flattenedDoc = flatten(doc);
_refs.forEach(ref => {
let name = pluralize(flattened[`${ ref.path }.ref`]);
let toPopulate = collections.filter(collection => collection.name === name)[0];
let _id = flattenedDoc[ref.path];
if (_id) {
let childDocument = toPopulate.chain().find({ _id }).data()[0];
flattenedDoc[ref.path] = childDocument || null;
}
});
return result.concat(flatten.unflatten(flattenedDoc));
}, []);
}
}

@@ -102,0 +143,0 @@

{
"name": "lowkie",
"version": "0.4.0",
"version": "0.5.0",
"license": "MIT",

@@ -5,0 +5,0 @@ "main": "index.js",

@@ -1,1 +0,1 @@

{"filename":"/Users/yawetse/Developer/github/typesettin/lowkie/example/sampledb.json","collections":[{"name":"kittens","data":[],"idIndex":[201,217,218],"binaryIndices":{},"constraints":null,"uniqueNames":[],"transforms":{},"objType":"kittens","dirty":true,"cachedIndex":null,"cachedBinaryIndex":null,"cachedData":null,"adaptiveBinaryIndices":true,"transactional":false,"cloneObjects":false,"cloneMethod":"parse-stringify","asyncListeners":false,"disableChangesApi":true,"autoupdate":false,"ttl":null,"maxId":218,"DynamicViews":[],"events":{"insert":[null],"update":[null],"pre-insert":[],"pre-update":[],"close":[],"flushbuffer":[],"error":[],"delete":[null],"warning":[null]},"changes":[]}],"databaseVersion":1.1,"engineVersion":1.1,"autosave":false,"autosaveInterval":5000,"autosaveHandle":null,"throttledSaves":true,"options":{"serializationMethod":"normal","destructureDelimiter":"$<\n"},"persistenceMethod":"fs","persistenceAdapter":null,"verbose":false,"events":{"init":[null],"loaded":[],"flushChanges":[],"close":[],"changes":[],"warning":[]},"ENV":"NODEJS"}
{"filename":"/Users/janbialostok/Developer/github/periodic/lowkie/test/mock/sampledb.json","collections":[],"databaseVersion":1.1,"engineVersion":1.1,"autosave":false,"autosaveInterval":5000,"autosaveHandle":null,"throttledSaves":true,"options":{"serializationMethod":"normal","destructureDelimiter":"$<\n"},"persistenceMethod":"fs","persistenceAdapter":null,"verbose":false,"events":{"init":[null],"loaded":[],"flushChanges":[],"close":[],"changes":[],"warning":[]},"ENV":"NODEJS"}

@@ -9,6 +9,6 @@ 'use strict';

const testSchemaDBPath = path.join(__dirname, '../mock/schematestdb.json');
let lowkie = require('../../index');
let lowkieSchema = require('../../lib/schema');
const lowkie = require('../../index');
const lowkieSchema = require('../../lib/schema');
const removeTestDB = require('../util/removeTestDB');
let testUserSchemaScheme = {
const testUserSchemaScheme = {
name: String,

@@ -23,5 +23,11 @@ email: String,

},
account: {
ref: 'testaccount',
type: lowkieSchema.Types.ObjectId
}
};
let testUserSchema;
let testUserModel;
let testAccountSchema;
let testAccountModel;

@@ -37,2 +43,4 @@ describe('Schema', function () {

testUserModel = lowkie.model('testuser', testUserSchema);
testAccountSchema = lowkie.Schema({ name: String });
testAccountModel = lowkie.model('testaccount', testAccountSchema);
// console.log({testUserSchema})

@@ -63,3 +71,3 @@ done();

expect(testUserSchema.createDoc({})._id).to.be.an('string');
expect(Object.keys(testUserSchema.createDoc({})).length).to.eql(1);
expect(Object.keys(testUserSchema.createDoc({})).length).to.eql(2);
});

@@ -97,2 +105,34 @@ it('should allow for custom Ids', () => {

});
it('Should define default schema props', () => {
let newUser = testUserSchema.createDoc({
name: 'testuser',
email: 'user@domain.tld',
active: true,
age: 18,
invalidprop: 'whatever',
});
expect(newUser.profile).to.equal('no profile');
});
it('Should allow the definition of a populated field', (done) => {
return testAccountModel.insert({
name: 'Some Random Name'
})
.then(account => {
expect(account[0]._id).to.be.ok;
return testUserModel.insert({
name: 'testuser',
email: 'user@domain.tld',
active: true,
age: 18,
account: account[0]._id
});
})
.then(newUser => {
let result = testUserModel.populate('account', { _id: newUser[0]._id })[0];
expect(result.account).to.have.property('name');
expect(result.account.name).to.equal('Some Random Name');
done();
})
.catch(done);
});
describe('#insert', () => {

@@ -99,0 +139,0 @@ it('should return a promise', () => {

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc