Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- // returns updated object but also saves audit to db
- fooWithAuditSavedToDbAfterExec({ x: 8 }, 'restuta')
- */
- /* goals:
- We want to abstract audit records collection from "foo" function. We don't want it to know
- anything about audit log, it should just be able to call "applyUpdatesWithAudit" anytime it wants and
- later we would like to collect all audit logs and save to db.
- "updateWithAuditLog" is a function that updates an object and returns updated object and
- corresponding audit record.
- Generic definition:
- Design a pattern that allows "foo" function to be agnostic of the update fuction passed to it,
- it should know or deal with any audt logs collection and saving them to db.
- Specific definition:
- 1) Design a funciton that has signature similar to "updateWithAuditLog" but returns updates only
- (and not the audit log record)
- see: "applyUpdatesWithAudit" as an example of such a function
- 2) Create new function based on "foo" that is able to collect audit records and save them to db
- 3) We should save audit records to db all at once after all updates are done.
- 4) Solution should be generic enough so we can "attach" it to any function that expects
- "audit producing function".
- */
- const foo = applyUpdatesWithAudit => (obj, userName) => {
- let updatedObj = applyUpdatesWithAudit(obj, { y: 1 }, userName);
- updatedObj = applyUpdatesWithAudit(updatedObj, { z: 2 }, userName)
- updatedObj = applyUpdatesWithAudit(updatedObj, { x: 3 }, userName)
- return {
- updatedObj,
- };
- };
- const updateWithAuditLog = (orignalObj, updates, userName) => {
- const updatedObj = {
- ...orignalObj,
- ...updates,
- };
- const auditRecord = `${userName} updated "${Object.keys(updates).join(',')}".`;
- return {
- updatedObj,
- auditRecord,
- };
- };
- const saveAuditRecordsToDb = auditRecords => console.log(`Saved ${auditRecords.length} to db`);
- // implementation stub
- const applyUpdatesWithAudit = (...args) => updateWithAuditLog(...args).updatedObj;
- updateWithAuditLog({ x: 8 }, { a: 9, x: 9 }, 'anton'); //?
- foo(applyUpdatesWithAudit)({ x: 8 }, 'restuta'); //?
- const createAuditLogCollector = auditLogProducingFunc => func => {/* your implementation */ }
- const saveAuditLog = saveAuditToDbFunc => () => { /* your implementation */ }
- const saveAuditLogAfterExecution = saveAuditLog(saveAuditRecordsToDb)
- const withAuditLogCollector = createAuditLogCollector(updateWithAuditLog)
- const fooWithAudit = withAuditLogCollector(foo)
- const fooWithAuditSavedToDbAfterExec = saveAuditLogAfterExecution(fooWithAudit)
- const R = require('ramda')
- const fooWithAuditSavedToDbAfterExec2 = R.pipe(
- withAuditLogCollector,
- saveAuditLogAfterExecution
- )
Add Comment
Please, Sign In to add comment