smartjson/ts/index.ts

78 lines
1.7 KiB
TypeScript
Raw Normal View History

import * as plugins from './smartjson.plugins';
2020-10-05 11:22:16 +00:00
/**
* allows you to parse a json
*/
export const parse = plugins.bufferJson.parse;
2020-10-05 11:22:16 +00:00
/**
*
* @param objArg
* @param optionsArg
*/
export const stringify = (objArg: any, optionsArg: plugins.IStableJsonTypes['Options'] = {}) => {
const bufferedJson = plugins.bufferJson.stringify(objArg);
objArg = JSON.parse(bufferedJson);
return plugins.stableJson(objArg, optionsArg);
};
export class Smartjson {
2020-10-05 11:13:17 +00:00
/**
* enfolds data from an object
*/
public static enfoldFromObject(objectArg) {
const newInstance = new this();
for (const keyName in objectArg) {
if (newInstance.saveableProperties.indexOf(keyName) !== -1) {
newInstance[keyName] = objectArg[keyName];
}
}
return newInstance;
}
2020-10-05 11:22:16 +00:00
/**
* enfold from json
*/
public static enfoldFromJson(jsonArg: string) {
const objectFromJson = parse(jsonArg);
return this.enfoldFromObject(objectFromJson);
}
// ========
// INSTANCE
// ========
2017-02-27 13:05:03 +00:00
2019-08-09 08:55:17 +00:00
public saveableProperties: string[];
2017-02-27 13:05:03 +00:00
/**
* folds a class into an object
*/
2019-08-09 08:55:17 +00:00
public foldToObject() {
const newFoldedObject: { [key: string]: any } = {};
for (const keyName of this.saveableProperties) {
2019-07-04 15:03:15 +00:00
newFoldedObject[keyName] = plugins.lodashCloneDeep(this[keyName]);
2017-02-27 13:05:03 +00:00
}
2018-07-23 22:38:54 +00:00
return newFoldedObject;
2017-02-27 13:05:03 +00:00
}
2020-10-05 11:22:16 +00:00
/**
* folds a class into an object
*/
public foldToJson() {
const foldedObject = this.foldToObject();
return stringify(foldedObject, {});
}
2017-02-27 13:05:03 +00:00
}
/**
* Decorator that marks a property as foldable
*/
export let foldDec = () => {
return (target: any, key: string) => {
2018-07-23 22:38:54 +00:00
if (!target.saveableProperties) {
target.saveableProperties = [];
}
target.saveableProperties.push(key);
};
};