Skip to content

Commit

Permalink
fix(lossless-parser): correctly parse number array
Browse files Browse the repository at this point in the history
fixes #258
  • Loading branch information
jwulf committed Sep 24, 2024
1 parent 2408267 commit 0e1ae3d
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 5 deletions.
19 changes: 14 additions & 5 deletions src/__tests__/lib/LosslessJsonParser.unit.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
BigIntValue,
ChildDto,
createDtoInstance,
Int64String,
LosslessDto,
losslessParse,
Expand Down Expand Up @@ -387,14 +388,22 @@ test('LosslessJsonParser will throw if given stringified JSON with an unsafe int

test('It rejects Date, Map, and Set types', () => {
class Dto extends LosslessDto {
date!: Date
name!: string
date?: Date
name?: string
map?: Map<string, string>
set?: Set<string>
}
const date = new Date()
const dto = new Dto({ date, name: 'me' })
const dto = createDtoInstance(Dto, { date, name: 'me' })
expect(() => losslessStringify(dto)).toThrow('Date')
const mapDto = new Dto({ map: new Map() })
const mapDto = createDtoInstance(Dto, { map: new Map() })
expect(() => losslessStringify(mapDto)).toThrow('Map')
const setDto = new Dto({ set: new Set() })
const setDto = createDtoInstance(Dto, { set: new Set<string>() })
expect(() => losslessStringify(setDto)).toThrow('Set')
})

test('It correctly handles a number array in a subkey', () => {
const json = `{"message":"Hello from automation","userId":null,"sendTo":[12022907,12022896,12022831]}`
const res = losslessParse(json)
expect(res.sendTo[0]).toBe(12022907)
})
4 changes: 4 additions & 0 deletions src/lib/CreateDtoInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
*
* This provides a type-safe method to create a DTO instance from a plain object.
*
* Node 22's experimental strip types does not play well with the previous "via the constructor" method.
*
* See: https://gist.github.com/jwulf/6e7b093b5b7b3e12c7b76f55b9e4be84
*
* @param dtoClass
* @param dtoData
* @returns
Expand Down
3 changes: 3 additions & 0 deletions src/lib/LosslessJsonParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,9 @@ function convertLosslessNumbersToNumberOrThrow<T>(obj: any): T {
if (!obj) {
return obj
}
if (obj instanceof LosslessNumber) {
return toSafeNumberOrThrow(obj.toString()) as T
}
let currentKey = ''
try {
Object.keys(obj).forEach((key) => {
Expand Down

0 comments on commit 0e1ae3d

Please sign in to comment.