ketting
Version:
Opinionated HATEOAS / Rest client.
66 lines • 2.05 kB
JavaScript
import { resolve } from './uri.js';
export function parseHtml(contextUri, body) {
const parser = new DOMParser();
const doc = parser.parseFromString(body, 'text/html');
return {
forms: formFromTags(contextUri, doc.getElementsByTagName('form')),
links: [
...linkFromTags(contextUri, doc.getElementsByTagName('link')),
...linkFromTags(contextUri, doc.getElementsByTagName('a'))
]
};
}
function linkFromTags(contextUri, elements) {
const result = [];
for (const node of elements) {
const rels = node.getAttribute('rel');
const href = node.getAttribute('href');
const type = node.getAttribute('type') || undefined;
if (!rels || !href) {
continue;
}
for (const rel of rels.split(' ')) {
const link = {
rel: rel,
context: contextUri,
href: href,
};
if (type)
link.type = type;
result.push(link);
}
}
return result;
}
function formFromTags(contextUri, elements) {
const result = [];
for (const node of elements) {
const rels = node.getAttribute('rel');
const action = node.getAttribute('action') || '';
const enctype = node.getAttribute('enctype') || 'application/x-www-form-urlencoded';
const id = node.getAttribute('id');
const method = node.getAttribute('method') || 'GET';
if (!rels) {
result.push({
rel: null,
action: resolve(contextUri, action),
enctype,
id,
method
});
continue;
}
for (const rel of rels.split(' ')) {
const form = {
rel,
action: resolve(contextUri, action),
enctype,
id,
method
};
result.push(form);
}
}
return result;
}
//# sourceMappingURL=html.web.js.map