Skip to content

Instantly share code, notes, and snippets.

@emmanuelnk
Last active August 14, 2019 03:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emmanuelnk/5c5517d6e1fe6bd8eff4acc9d3b43f21 to your computer and use it in GitHub Desktop.
Save emmanuelnk/5c5517d6e1fe6bd8eff4acc9d3b43f21 to your computer and use it in GitHub Desktop.
Recursively update all timestamps in a document to current timestamps based on when the document/fixture was created (Moment.js, Node.js)
// great for fixtures used in tests that need to stay up to date
// needs moment.js
const moment = require('moment')
const updateTimestamps = (entity, baseTimestamp, path = '', tsFields) => {
// usage: recusrively updates all Timestamps in a json fixture for tests
const nowTs = moment().clone().startOf('hour')
const diff = Math.abs(nowTs.diff(baseTimestamp, 'hours'))
if (entity && entity.constructor === Array)
entity = entity.map((item, idx) =>
updateTimestamps(item, baseTimestamp, `${path}[${idx}]`)
)
if (entity && entity.constructor === Object) {
const keys = Object.keys(entity)
for (const key of keys)
if (tsFields.includes(key)) {
entity[key] = moment(entity[key]).clone().add(
diff,
'hours'
).toDate()
// console.log(`${path}${ path ? '.' : '' }${key}`, entity[key])
} else if (entity[key] && entity[key].constructor === Object)
entity[key] = updateTimestamps(
entity[key],
baseTimestamp,
`${path}${key}`
)
else if (entity[key] && entity[key].constructor === Array)
entity[key] = entity[key].map((item, idx) =>
updateTimestamps(item, baseTimestamp, `${path}${key}[${idx}]`)
)
}
return entity
}
// results should be a json object or array for which every timestamp defined in ts fields will be updated recursively
let results = []
// usage: recusrively updates all Timestamps in a json fixture for tests
const updatedEntity = updateTimestamps(results, moment().startOf('hour').toISOString(),'',[
'ts',
'updatedAt',
'createdAt'
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment