Skip to content
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
25 changes: 25 additions & 0 deletions packages/clients/src/scw/__tests__/custom-marshalling.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@ import {
marshalScwFile,
marshalTimeSeries,
marshalTimeSeriesPoint,
unmarshalDecimal,
unmarshalMoney,
unmarshalScwFile,
unmarshalServiceInfo,
unmarshalTimeSeries,
unmarshalTimeSeriesPoint,
} from '../custom-marshalling'
import { Decimal } from '../custom-types'

describe('unmarshalMoney', () => {
it('returns the proper object', () => {
Expand Down Expand Up @@ -123,6 +125,29 @@ describe('unmarshalTimeSeries', () => {
})
})

describe('unmarshalDecimal', () => {
it('returns the proper object', () => {
const decimal = unmarshalDecimal({
value: '0.01',
})
expect(decimal).toBeInstanceOf(Decimal)
expect(decimal?.toString()).toStrictEqual('0.01')
})

it('throws for invalid input', () => {
expect(unmarshalDecimal(null)).toBeNull()
expect(() => {
unmarshalDecimal({})
}).toThrow()
expect(() => {
unmarshalDecimal({ value: null })
}).toThrow()
expect(() => {
unmarshalDecimal({ value: 0.02 })
}).toThrow()
})
})

describe('marshalScwFile', () => {
it('returns a the proper object', () =>
expect(
Expand Down
25 changes: 21 additions & 4 deletions packages/clients/src/scw/custom-marshalling.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,13 +115,28 @@ export const unmarshalTimeSeries = (data: unknown) => {
* @internal
*/
export const unmarshalDecimal = (data: unknown) => {
if (!(typeof data === 'string')) {
if (!(typeof data === 'object')) {
throw new TypeError(
`Unmarshalling the type 'Decimal' failed as data isn't a string.`,
`Unmarshalling the type 'Decimal' failed as data isn't an object.`,
)
}
if (data === null) {
return null
}

if (!('value' in data)) {
throw new TypeError(
`Unmarshalling the type 'Decimal' failed as data object does not have a 'value' key.`,
)
}

return new Decimal(data)
if (!(typeof data.value === 'string')) {
throw new TypeError(
`Unmarshalling the type 'Decimal' failed as 'value' is not a string.`,
)
}

return new Decimal(data.value)
}

/**
Expand Down Expand Up @@ -189,4 +204,6 @@ export const marshalTimeSeries = (
*
* @internal
*/
export const marshalDecimal = (obj: Decimal): string => obj.toString()
export const marshalDecimal = (obj: Decimal): { value: string } => ({
value: obj.toString(),
})
2 changes: 2 additions & 0 deletions packages/clients/src/scw/custom-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,4 +79,6 @@ export class Decimal {
}

public toString = (): string => this.str

public marshal = (): object => ({ value: this.str })
}
Loading