Skip to content

Commit

Permalink
Merge pull request #4 from neg4n/obj-traverse-recode
Browse files Browse the repository at this point in the history
Recode the object traverse and improve tests
  • Loading branch information
neg4n authored Feb 8, 2024
2 parents 4b9cf41 + fe811a6 commit cd285b6
Show file tree
Hide file tree
Showing 5 changed files with 393 additions and 135 deletions.
8 changes: 2 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "obj-serialize",
"version": "2.0.0",
"version": "2.1.0",
"description": "Simple utility to serialize objects to be passed around to another context. Useful in Next.js Pages Router projects.",
"author": {
"name": "Igor Klepacki",
Expand Down Expand Up @@ -52,18 +52,14 @@
"devDependencies": {
"@jest/globals": "^29.7.0",
"@jest/types": "^29.6.3",
"@types/flat": "^5.0.2",
"@types/node": "^18.7.18",
"jest": "^29.7.0",
"next": "^14.0.4",
"prettier": "^2.7.1",
"rimraf": "^3.0.2",
"ts-jest": "^29.1.1",
"tsup": "^8.0.1",
"type-fest": "^4.10.2",
"typescript": "^4.8.3"
},
"dependencies": {
"flattie": "^1.1.0",
"nestie": "^1.0.3"
}
}
33 changes: 8 additions & 25 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

85 changes: 50 additions & 35 deletions src/serialize.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
import { flattie } from 'flattie'
import { nestie } from 'nestie'

export const SkipSerialization = Symbol(
'ba1894562a5b3e00de68679b5e01fed0de0a0aac6da459729c2f4d665d928ccc',
)
Expand All @@ -9,47 +6,65 @@ type SerializationRules = <T>(
unserializedValue: T,
) => string | number | boolean | null | undefined | typeof SkipSerialization

export function serialize<R>(data: Record<string, unknown>, rules: SerializationRules) {
if (hasCircularReferences(data)) {
throw new Error('Neither Next.js nor obj-serialize supports circular references.')
}
function detectCircularReferences(
object: unknown,
seenObjects = new Set<unknown>(),
): boolean {
if (object !== null && typeof object === 'object') {
if (seenObjects.has(object)) return true

return nestie(
Object.entries(flattie(data) as Record<string, unknown>).reduce(
(newData, [key, value]) => {
let oldValue = value
const serialized = rules(value)

if (typeof serialized === typeof SkipSerialization) {
newData[key] = oldValue
} else if (serialized !== oldValue) {
newData[key] = serialized
}

return newData
},
{} as Record<string, unknown>,
),
) as Record<string, R>
seenObjects.add(object)
for (const key of Object.keys(object as object)) {
if (
detectCircularReferences((object as { [key: string]: unknown })[key], seenObjects)
)
return true
}

seenObjects.delete(object)
}
return false
}

function hasCircularReferences(object: unknown): boolean {
const seenObjects = new Set<unknown>()
return detectCircularReferences(object)
}

const detect = (object: unknown): boolean => {
if (object !== null && typeof object === 'object') {
if (seenObjects.has(object)) return true
function isPlainObject(obj: unknown): obj is Record<string, unknown> {
return Object.prototype.toString.call(obj) === '[object Object]'
}

seenObjects.add(object)
function processValue(value: unknown, rules: SerializationRules): unknown {
if (Array.isArray(value)) {
return value
.map((item) => processValue(item, rules))
.filter((item) => item !== SkipSerialization)
} else if (typeof value === 'object' && value !== null && isPlainObject(value)) {
const processedObject = Object.fromEntries(
Object.entries(value)
.map(([key, val]) => [key, processValue(val, rules)])
.filter(([, val]) => val !== SkipSerialization),
)

for (const key of Object.keys(object as object))
if (detect((object as { [key: string]: unknown })[key])) return true
if (Object.keys(processedObject).length === 0 && !rules(value))
return SkipSerialization

seenObjects.delete(object)
}
return processedObject
} else {
const serialized = rules(value)
if (serialized === SkipSerialization) return value

return false
return serialized
}
}

export function serialize<V>(data: unknown, rules: SerializationRules) {
if (hasCircularReferences(data)) {
throw new Error('Neither Next.js nor obj-serialize supports circular references.')
}

return detect(object)
const result = processValue(data, rules)
return result === SkipSerialization
? ({} as Record<string, V>)
: (result as Record<string, V>)
}
Loading

0 comments on commit cd285b6

Please sign in to comment.