Are there any TypeScript decorators available to build XML better with a typescript? #692
Replies: 4 comments
-
Library supports modifying prefix for attributes and their group and other kind of tags. |
Beta Was this translation helpful? Give feedback.
-
So far I created this kind of approach: import { test } from 'node:test'
import * as assert from 'node:assert'
function namespace<T extends Record<string, any>>(object: T, ns: string): Record<string, any> {
const result: Record<string, any> = {}
for (const [key, value] of Object.entries(object)) {
const namespacedKey = `${ns}:${key}`
result[namespacedKey] = value
}
return result
}
function attr<T extends Record<string, any>>(object: T): Record<string, any> {
const result: Record<string, any> = {}
for (const [key, value] of Object.entries(object)) {
const attrKey = `@_${key}`
result[attrKey] = value
}
return result
}
const ns1 = <T extends Record<string, any>>(object: T) => namespace(object, 'ns1')
const ns2 = <T extends Record<string, any>>(object: T) => namespace(object, 'ns2')
test('namespaced attributes', async (t) => {
await t.test('handles namespaced attributes through composition', () => {
const input = {
root: {
...ns1({
item: {
...attr({ id: '1' }),
...attr(ns1({ type: 'test' })),
...attr(ns2({ lang: 'en' })),
'#text': 'content'
}
})
}
}
const expected = {
root: {
'ns1:item': {
'@_id': '1',
'@_ns1:type': 'test',
'@_ns2:lang': 'en',
'#text': 'content'
}
}
}
const result = input
assert.deepStrictEqual(result, expected)
})
}) |
Beta Was this translation helpful? Give feedback.
-
So I decided to publish my helpers as a package: https://www.npmjs.com/package/fxmlp to be able to use it in another project |
Beta Was this translation helpful? Give feedback.
-
Honestly, speaking I couldn't understand your concern and purpose of creating a wrapper just to make a few properties to default. However, its your choice. This library is made to provide core functionality so people can use it in their projects. Good luck |
Beta Was this translation helpful? Give feedback.
-
Hi!
I'm just thinking loud - it's just the open question for the discussion about the format chosen to attract attributes.
So Currently we have a following format:
translates into
It's totally fine if we want to parse XML and work with it, however it represents certain problems with using such objects in typescript.
I have been thinking of some possible ways may be to avoid using @ and : symbols in a property names and use some helper functions/decorators to work with just regular types and interfaces?
I've been experiementing but didn't find yet a good way to construct XML without creating types specially dedicated to this format..
Beta Was this translation helpful? Give feedback.
All reactions