Skip to content

Instantly share code, notes, and snippets.

@FranCarstens
Created March 18, 2021 18:20
Show Gist options
  • Save FranCarstens/43cbc90adaf4d664ef6ff3feec3fd44a to your computer and use it in GitHub Desktop.
Save FranCarstens/43cbc90adaf4d664ef6ff3feec3fd44a to your computer and use it in GitHub Desktop.
A MirageJS serializer to convert all IDs to integers
// convert single string id to integer
const idToInt = id => Number(id)
// convert array of ids to integers
const idsToInt = ids => ids.map(id => idToInt(id))
// check if the data being passed is a collection or model
const isCollection = data => Array.isArray(data)
// check if data should be traversed
// should match the structure of a collection
// array containing objects
const shouldTraverse = entry =>
(Array.isArray(entry) && entry[0] instanceof Object) ||
(entry instanceof Object && entry[0] instanceof Object)
// check if the entry is an id
const isIdKey = key =>
!['createdById', 'lastUpdatedById'].includes(key) &&
(key === 'id' || key.slice(key.length - 2) === 'Id')
// check for serialized Ids
const isIdArray = (key, value) =>
key.slice(key.length - 3, key.length) === 'Ids' && Array.isArray(value)
// traverse the passed model and update Ids where required, keeping other entries as is
const traverseModel = model =>
Object.entries(model).reduce(
(a, c) =>
isIdKey(c[0])
// convert id to int
? { ...a, [c[0]]: idToInt(c[1]) }
// convert id array to int
: isIdArray(c[0], c[1])
? { ...a, [c[0]]: idsToInt(c[1]) }
// traverse nested entries
: shouldTraverse(c[1])
? { ...a, [c[0]]: serializeIds(c[1]) }
// keep regular entries
: { ...a, [c[0]]: c[1] },
{}
)
// start traversal of data
const serializeIds = data =>
isCollection(data)
? data.map(model => traverseModel(model))
: traverseModel(data)
export default serializeIds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment