Skip to content

Commit

Permalink
proxy added (#46)
Browse files Browse the repository at this point in the history
  • Loading branch information
beyzaerkan committed Jul 21, 2022
1 parent 0a8a4d2 commit 59e2c48
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions lib/ModelInstance.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import Model from './Model';
import { safeWrite } from './Utilities';
import { safeWrite, getKeyValue } from './Utilities';

export interface DataInfo {
redisKey: String,
Expand All @@ -9,6 +9,7 @@ interface ModelFields {
_model: Model;
_previousDataValues: any | Object;
_dataInfo: DataInfo;
_changedValues: any | Object;
}

/**
Expand Down Expand Up @@ -36,10 +37,20 @@ class ModelInstance {
_model: model,
_previousDataValues: data,
_dataInfo: dataInfo,
_changedValues: {},
};
Object.entries(data).forEach(([key, defaultValue]) => {
this[key] = defaultValue;
});
const handler = {
set: (target: Object, key: string, value: any)=>{
this._Model._changedValues[`${key}`] = getKeyValue(key)(target);
target[key as keyof Object] = value;
return true;
}
}
let proxy: any = new Proxy(this, handler);
return proxy;
}

/**
Expand All @@ -48,7 +59,12 @@ class ModelInstance {
public async save(): Promise<void> {
const { _Model, ...data } = this;
const { redisClient, flexSchema, schema } = _Model._model;
await safeWrite(data, _Model._dataInfo.redisKey, redisClient, schema, flexSchema);
const keys = Object.keys(_Model._changedValues);
const tempData: Object = {};
keys.forEach((key) => {
tempData[key as keyof Object] = data[key];
});
await safeWrite(tempData, _Model._dataInfo.redisKey, redisClient, schema, flexSchema);
}

/**
Expand Down

0 comments on commit 59e2c48

Please sign in to comment.