A simple entity diff generator.
generates a list of changes made to the entity.
All you need are two objects, one with the entity before the changes and the other with it after the changes.
npm:
npm install entity-diffyarn:
yarn add entity-diffimport{Audit}from"entity-diff";constaudit=newAudit();constbefore={name: "Mason",age: 20};constafter={name: "Mason Floyd",age: 20};constresult=audit.diff(before,after);// result:// [// {// key: "name",// from: "Mason",// to: "Mason Floyd"// }// ]It is possible to change some information in the final result of the diffs using parameters.
It is possible to ignore some keys of the objects audited through a list.
import{Audit}from"entity-diff";constbefore={name: "Mason",age: 20};constafter={name: "Mason Floyd",// this change will be ignoredage: 25};constignore=["name"];constaudit=newAudit({ ignore });constresult=audit.diff(before,after);// result:// [// {// key: "age",// from: 20,// to: 25// }// ]Changing the name that appears in the key in the result
import{Audit}from"entity-diff";constbefore={name: "Mason",age: 20};constafter={name: "Mason Floyd",age: 25};constoptions=[{key: "name",title: "Person name"}];constaudit=newAudit({ options });constresult=audit.diff(before,after);// result:// [// {// key: "Person name", // title defined in options// from: "Mason",// to: "Mason Floyd"// }// ]It can be done through a function defined in options
import{format}from'date-fns'import{Audit}from"entity-diff";constbefore={name: "Mason",age: 20};constafter={name: "Mason Floyd",age: 20,updatedAt: "2020-09-08T18:04:56.627Z"};constoptions=[{key: "updatedAt",customFormatter: date=>format(newDate(date),"MM/dd/yyyy")}];constaudit=newAudit({ options });constresult=audit.diff(before,after);// result:// [// {// key: "updatedAt",// from: null,// to: "09/08/2020"// }// ]when working with arrays, diffs are generated only when there is some value in "arrayOptions".
The "key" property represents the key used to find the entities within the other array. it is optional, but by default entity-diff looks for the "id" key.
import{Audit}from"entity-diff";constbefore={name: "Mason",age: 20,roles: [{id: 1,name: "ADM"},{id: 2,name: "USER"}]};constafter={name: "Mason",age: 20,roles: [{id: 1,name: "SUPER_USER"},{id: 3,name: "TEC"}]};constoptions=[{key: "roles",arrayOptions: {name: "name"}}];constaudit=newAudit({ options });constresult=audit.diff(before,after);// resut:// [// {// "key": "roles",// "type": "ARRAY",// "details": [// {// "key": "ADM",// "type": "MODIFIED",// "details": [// {// "key": "name",// "from": "ADM",// "to": "SUPER_USER"// }// ]// },// {// "key": "TEC",// "type": "NEW",// "details": [// {// "key": "id",// "from": null,// "to": 3// },// {// "key": "name",// "from": null,// "to": "TEC"// }// ]// },// {// "key": "USER",// "type": "REMOVED",// "details": [// {// "key": "id",// "from": 2,// "to": null// },// {// "key": "name",// "from": "USER",// "to": null// }// ]// }// ]// }// ]