Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Recode the object traverse and improve tests #4

Merged
merged 2 commits into from
Feb 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@
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))

Check warning on line 49 in src/serialize.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🌿 Branch is not covered

Warning! Not covered branch
return SkipSerialization

Check warning on line 50 in src/serialize.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🌿 Branch is not covered

Warning! Not covered branch

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>)

Check warning on line 68 in src/serialize.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🌿 Branch is not covered

Warning! Not covered branch
: (result as Record<string, V>)
}
Loading
Loading