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

xpress-mongo

Package Overview
Dependencies
Maintainers
1
Versions
149
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

xpress-mongo - npm Package Compare versions

Comparing version 0.0.48 to 0.0.49

38

fn/inbuilt.ts

@@ -1,2 +0,3 @@

import {FunctionReturnsBoolean, SchemaPropertiesType, ValidatorType} from "../src/CustomTypes";
import {FunctionReturnsBoolean, SchemaPropertiesType, StringToAnyObject, ValidatorType} from "../src/CustomTypes";
import XMongoModel from "../src/XMongoModel";

@@ -61,2 +62,37 @@ /**

return true;
}
export async function RunOnEvent(event: string, modelInstance: XMongoModel, changes: string[] = []): Promise<any> {
const Model = (modelInstance.constructor as typeof XMongoModel);
if (!Model.events) return false;
let events = Model.events;
if (!events[event]) return false;
events = events[event];
if (event === 'watch' && !changes.length) return false
if (typeof events === "function") {
await events(modelInstance);
} else if (typeof events === "object") {
const fields = Object.keys(events)
for (const field of fields) {
if (event === 'watch') {
if (changes.includes(field)) {
Promise.all([
events[field](modelInstance)
]).catch(console.error);
}
} else {
const newFieldValue = await events[field](modelInstance);
if (newFieldValue !== undefined) {
modelInstance.set(field, newFieldValue);
}
}
}
}
return false
}

@@ -47,2 +47,18 @@ import {MongoClient, MongoClientOptions} from "mongodb";

/**
* Adds an event to set a fields Timestamp to current date on update.
* Remove if not in use.
*/
function RefreshDateOnUpdate(Model: typeof XMongoModel, field: string, ifHasChanges: boolean = true) {
if (ifHasChanges) {
Model.on(`update.${field}`, (model) => {
if (Object.keys(model.changes()).length) {
return new Date()
}
});
} else {
Model.on(`update.${field}`, () => new Date());
}
}
export {

@@ -67,3 +83,4 @@ // Export is schemaBuilder

// Others
parseServerUrl
parseServerUrl,
RefreshDateOnUpdate
};
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.runAndValidation = exports.runOrValidation = exports.defaultValue = void 0;
exports.RunOnEvent = exports.runAndValidation = exports.runOrValidation = exports.defaultValue = void 0;
/**

@@ -64,1 +73,37 @@ * Get Default value.

exports.runAndValidation = runAndValidation;
function RunOnEvent(event, modelInstance, changes = []) {
return __awaiter(this, void 0, void 0, function* () {
const Model = modelInstance.constructor;
if (!Model.events)
return false;
let events = Model.events;
if (!events[event])
return false;
events = events[event];
if (event === 'watch' && !changes.length)
return false;
if (typeof events === "function") {
yield events(modelInstance);
}
else if (typeof events === "object") {
const fields = Object.keys(events);
for (const field of fields) {
if (event === 'watch') {
if (changes.includes(field)) {
Promise.all([
events[field](modelInstance)
]).catch(console.error);
}
}
else {
const newFieldValue = yield events[field](modelInstance);
if (newFieldValue !== undefined) {
modelInstance.set(field, newFieldValue);
}
}
}
}
return false;
});
}
exports.RunOnEvent = RunOnEvent;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseServerUrl = exports.omitIdAndPick = exports.omitIdAnd = exports.pickKeys = exports.omitKeys = exports.XMongoDataType = exports.XMongoModel = exports.Client = exports.is = void 0;
exports.RefreshDateOnUpdate = exports.parseServerUrl = exports.omitIdAndPick = exports.omitIdAnd = exports.pickKeys = exports.omitKeys = exports.XMongoDataType = exports.XMongoModel = exports.Client = exports.is = void 0;
const mongodb_1 = require("mongodb");

@@ -54,1 +54,18 @@ const XMongoSchemaBuilder_1 = require("./src/XMongoSchemaBuilder");

exports.parseServerUrl = parseServerUrl;
/**
* Adds an event to set a fields Timestamp to current date on update.
* Remove if not in use.
*/
function RefreshDateOnUpdate(Model, field, ifHasChanges = true) {
if (ifHasChanges) {
Model.on(`update.${field}`, (model) => {
if (Object.keys(model.changes()).length) {
return new Date();
}
});
}
else {
Model.on(`update.${field}`, () => new Date());
}
}
exports.RefreshDateOnUpdate = RefreshDateOnUpdate;

@@ -83,2 +83,9 @@ "use strict";

});
/**
* Set Model Schema if exists
*/
const thisClass = this.constructor;
if (thisClass.schema) {
this.useSchema(thisClass.schema);
}
}

@@ -150,2 +157,9 @@ /**

/**
* Check if field exists in data
* @param key
*/
has(key) {
return _.has(this.data, key);
}
/**
* Push element to model

@@ -284,9 +298,2 @@ * @param key

useSchema(schema) {
// Redefine schema
Object.defineProperty(this, 'schema', {
value: {},
writable: true,
enumerable: false,
configurable: true,
});
// Try to find schema from .schemaStore if string

@@ -425,7 +432,9 @@ if (typeof schema === "string") {

save(options = {}, create = false) {
return new Promise((resolve, reject) => {
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
const id = this.id();
if (id) {
yield inbuilt_1.RunOnEvent('update', this);
let $set = this.changes();
if (!Object.keys($set).length)
let $setKeys = Object.keys($set);
if (!$setKeys.length)
return resolve(false);

@@ -439,5 +448,14 @@ // Try to validate changes

}
return this.constructor.native().updateOne({ _id: this.id() }, { $set }, options, (error, res) => error ? reject(error) : resolve(res.connection));
return this.constructor.native().updateOne({ _id: this.id() }, { $set }, options, (error, res) => {
if (error) {
return reject(error);
}
else {
inbuilt_1.RunOnEvent('watch', this, $setKeys);
resolve(res.connection);
}
});
}
else {
yield inbuilt_1.RunOnEvent('create', this);
// Try to validate new data.

@@ -459,3 +477,3 @@ try {

}
});
}));
}

@@ -624,3 +642,5 @@ /**

if (_id) {
this.emptyData();
// Run on delete Events on background
inbuilt_1.RunOnEvent("delete", this).catch(console.error);
// Delete Document
return this.constructor.native().deleteOne({ _id });

@@ -1035,4 +1055,30 @@ }

}
/**
* Register Events for create, update and delete
* @param event
* @param functionOrFunctions
*/
static on(event, functionOrFunctions) {
if (!this.events)
this.events = {};
if (event === "delete" && typeof functionOrFunctions !== "function") {
throw Error("on('delete') event must be type of Function.");
}
if (event === "watch" && typeof functionOrFunctions !== "object") {
throw Error("on('watch') event must be type of Object.");
}
_.set(this.events, event, functionOrFunctions);
}
}
/**
* Model Schema
* @private
* @type {{}}
*/
XMongoModel.schema = {};
/**
* Model Events
*/
XMongoModel.events = {};
/**
* Defined relationships

@@ -1039,0 +1085,0 @@ * @type {{}}

2

package.json
{
"name": "xpress-mongo",
"version": "0.0.48",
"version": "0.0.49",
"description": "Light Weight ODM for mongoDb",

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

@@ -19,3 +19,3 @@ import ObjectCollection = require('object-collection');

import {diff} from 'deep-object-diff';
import {defaultValue, runOrValidation, runAndValidation} from '../fn/inbuilt';
import {defaultValue, runOrValidation, runAndValidation, RunOnEvent} from '../fn/inbuilt';
import {PaginationData, SchemaPropertiesType, StringToAnyObject} from "./CustomTypes";

@@ -62,2 +62,14 @@

/**
* Model Schema
* @private
* @type {{}}
*/
public static schema: StringToAnyObject = {};
/**
* Model Events
*/
public static events: StringToAnyObject = {};
/**
* Model Schema Store

@@ -105,2 +117,3 @@ * @private

this.emptyData();
Object.defineProperty(this, 'schema', {

@@ -130,2 +143,11 @@ value: {},

})
/**
* Set Model Schema if exists
*/
const thisClass = (this.constructor as typeof XMongoModel);
if (thisClass.schema) {
this.useSchema(thisClass.schema);
}
}

@@ -201,3 +223,11 @@

/**
* Check if field exists in data
* @param key
*/
has(key: string): boolean {
return _.has(this.data, key)
}
/**

@@ -356,10 +386,2 @@ * Push element to model

// Redefine schema
Object.defineProperty(this, 'schema', {
value: {},
writable: true,
enumerable: false,
configurable: true,
});
// Try to find schema from .schemaStore if string

@@ -521,10 +543,12 @@ if (typeof schema === "string") {

save(options: UpdateOneOptions | CollectionInsertOneOptions = {}, create = false): Promise<boolean | UpdateWriteOpResult | InsertOneWriteOpResult<any>> {
return new Promise((resolve, reject) => {
return new Promise(async (resolve, reject) => {
const id = this.id();
if (id) {
await RunOnEvent('update', this);
let $set = this.changes();
let $setKeys = Object.keys($set);
if (!$setKeys.length) return resolve(false);
if (!Object.keys($set).length) return resolve(false);
// Try to validate changes

@@ -541,4 +565,12 @@ try {

<UpdateOneOptions>options,
(error, res) => error ? reject(error) : resolve(res.connection))
(error, res) => {
if (error) {
return reject(error)
} else {
RunOnEvent('watch', this, $setKeys);
resolve(res.connection)
}
})
} else {
await RunOnEvent('create', this);
// Try to validate new data.

@@ -761,3 +793,6 @@ try {

if (_id) {
this.emptyData();
// Run on delete Events on background
RunOnEvent("delete", this).catch(console.error);
// Delete Document
return (<typeof XMongoModel>this.constructor).native().deleteOne({_id})

@@ -1205,5 +1240,29 @@ } else {

/**
* Register Events for create, update and delete
* @param event
* @param functionOrFunctions
*/
static on(
event: "create" | "update" | "delete" | "create.fieldName" | "update.fieldName" | "watch.fieldName" | string,
functionOrFunctions: onEvent
) {
if (!this.events) this.events = {};
if (event === "delete" && typeof functionOrFunctions !== "function") {
throw Error("on('delete') event must be type of Function.")
}
if (event === "watch" && typeof functionOrFunctions !== "object") {
throw Error("on('watch') event must be type of Object.")
}
_.set(this.events, event, functionOrFunctions);
}
}
type FunctionWithModelInstance = (modelInstance: XMongoModel) => (void | any);
type onEvent = FunctionWithModelInstance | { [key: string]: FunctionWithModelInstance };
export = XMongoModel;

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

const {is, ModelDataType} = require('../');
const {is, RefreshDateOnUpdate} = require('../');
const Database = global['Database'];

@@ -45,10 +45,5 @@

class Users extends Database.model("users") {
constructor() {
super();
this.useSchema(GuestSchema);
}
static schema = GuestSchema;
static append = ['fullName'];

@@ -70,2 +65,5 @@

RefreshDateOnUpdate(Users, 'updated_at')
/**

@@ -72,0 +70,0 @@ * @type {typeof Users | typeof XMongoModel}

@@ -7,23 +7,27 @@ const connection = require('./connection');

/*const user = await Users.findById('5e5acba088ebeef8a715ca43', {
projection: {_id: 0}
// 5f8bb34c17793a7bb278d24f
const user = await Users.findById('5e5acba088ebeef8a715ca43', {
// projection: {_id: 0}
});
console.log(user);*/
await user.update({
// created_at: new Date()
});
console.log(user);
/**
* Async Space
*/
const guest = new Users().set({
type: 'guest',
first_name: 'Hello',
last_name: 'World',
guestId: '678',
updated_at: 'Fri, 03 Apr 2020 00:00:00 GMT'
});
// const guest = new Users().set({
// type: 'guest',
// first_name: 'Hello',
// last_name: 'World',
// guestId: '678',
// updated_at: 'Fri, 03 Apr 2020 00:00:00 GMT'
// });
//
// console.log(guest);
// console.log(guest.data);
console.log(guest.validate());
/**

@@ -30,0 +34,0 @@ * End Async Space

import { FunctionReturnsBoolean, SchemaPropertiesType, ValidatorType } from "../src/CustomTypes";
import XMongoModel from "../src/XMongoModel";
/**

@@ -32,1 +33,2 @@ * Get Default value.

export declare function runAndValidation(value: any, validators: ValidatorType[] | FunctionReturnsBoolean[]): boolean;
export declare function RunOnEvent(event: string, modelInstance: XMongoModel, changes?: string[]): Promise<any>;

@@ -25,2 +25,7 @@ import { MongoClient, MongoClientOptions } from "mongodb";

}): string;
export { is, Client, XMongoModel, XMongoDataType, XMongoSchemaBuilder, omitKeys, pickKeys, omitIdAnd, omitIdAndPick, parseServerUrl };
/**
* Adds an event to set a fields Timestamp to current date on update.
* Remove if not in use.
*/
declare function RefreshDateOnUpdate(Model: typeof XMongoModel, field: string, ifHasChanges?: boolean): void;
export { is, Client, XMongoModel, XMongoDataType, XMongoSchemaBuilder, omitKeys, pickKeys, omitIdAnd, omitIdAndPick, parseServerUrl, RefreshDateOnUpdate };

@@ -34,2 +34,12 @@ import ObjectCollection = require('object-collection');

/**
* Model Schema
* @private
* @type {{}}
*/
static schema: StringToAnyObject;
/**
* Model Events
*/
static events: StringToAnyObject;
/**
* Model Schema Store

@@ -100,2 +110,7 @@ * @private

/**
* Check if field exists in data
* @param key
*/
has(key: string): boolean;
/**
* Push element to model

@@ -374,3 +389,13 @@ * @param key

static toArray(query: FunctionWithRawArgument): Promise<any[]>;
/**
* Register Events for create, update and delete
* @param event
* @param functionOrFunctions
*/
static on(event: "create" | "update" | "delete" | "create.fieldName" | "update.fieldName" | "watch.fieldName" | string, functionOrFunctions: onEvent): void;
}
declare type FunctionWithModelInstance = (modelInstance: XMongoModel) => (void | any);
declare type onEvent = FunctionWithModelInstance | {
[key: string]: FunctionWithModelInstance;
};
export = XMongoModel;
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