feat(core): functions to (de-)serialize TL JSON
This commit is contained in:
parent
b157b52ff6
commit
90e1e018f5
2 changed files with 58 additions and 0 deletions
|
@ -5,6 +5,7 @@ export * from './types'
|
|||
|
||||
export * from './utils/crypto'
|
||||
export * from './utils/peer-utils'
|
||||
export * from './utils/tl-json'
|
||||
|
||||
export { BinaryReader } from './utils/binary/binary-reader'
|
||||
export { BinaryWriter } from './utils/binary/binary-writer'
|
||||
|
|
57
packages/core/src/utils/tl-json.ts
Normal file
57
packages/core/src/utils/tl-json.ts
Normal file
|
@ -0,0 +1,57 @@
|
|||
import { tl } from '@mtcute/tl'
|
||||
|
||||
/**
|
||||
* Convert a JS object to TL JSON
|
||||
*
|
||||
* @param obj Object to be converted
|
||||
*/
|
||||
export function jsonToTlJson(obj: any): tl.TypeJSONValue {
|
||||
if (obj === null || obj === undefined) return { _: 'jsonNull' }
|
||||
if (typeof obj === 'boolean') return { _: 'jsonBool', value: obj }
|
||||
if (typeof obj === 'number') return { _: 'jsonNumber', value: obj }
|
||||
if (typeof obj === 'string') return { _: 'jsonString', value: obj }
|
||||
if (Array.isArray(obj))
|
||||
return { _: 'jsonArray', value: obj.map(jsonToTlJson) }
|
||||
|
||||
if (typeof obj !== 'object')
|
||||
throw new Error(`Unsupported type: ${typeof obj}`)
|
||||
|
||||
const items: tl.TypeJSONObjectValue[] = []
|
||||
|
||||
Object.entries(obj).forEach(([key, value]) => {
|
||||
items.push({
|
||||
_: 'jsonObjectValue',
|
||||
key,
|
||||
value: jsonToTlJson(value),
|
||||
})
|
||||
})
|
||||
|
||||
return {
|
||||
_: 'jsonObject',
|
||||
value: items,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert TL JSON object to plain JS object
|
||||
*
|
||||
* @param obj TL JSON object to convert
|
||||
*/
|
||||
export function tlJsonToJson(obj: tl.TypeJSONValue): any {
|
||||
if (obj._ === 'jsonNull') return null
|
||||
if (
|
||||
obj._ === 'jsonBool' ||
|
||||
obj._ === 'jsonNumber' ||
|
||||
obj._ === 'jsonString'
|
||||
)
|
||||
return obj.value
|
||||
if (obj._ === 'jsonArray') return obj.value.map(tlJsonToJson)
|
||||
|
||||
const ret: any = {}
|
||||
|
||||
obj.value.forEach((item) => {
|
||||
ret[item.key] = tlJsonToJson(item.value)
|
||||
})
|
||||
|
||||
return ret
|
||||
}
|
Loading…
Reference in a new issue