Last active
May 21, 2021 14:32
-
-
Save grtjn/0caa73d041cb30d12ca3022b11443beb to your computer and use it in GitHub Desktop.
Fluent interface for MarkLogic NodeBuilder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
// Fluent interface functions | |
function document(root) { | |
return function(b) { | |
return (b || new NodeBuilder()).addDocument(root); | |
} | |
} | |
function element(name, contents) { | |
return function(b) { | |
return (b || new NodeBuilder()).addElement(name, cb => { | |
if (!Array.isArray(contents)) { | |
contents = [contents]; | |
} | |
return contents.reduce((cb, child) => child(cb), cb); | |
}); | |
}; | |
} | |
function attribute(name, contents) { | |
return function(b) { | |
return (b || new NodeBuilder()).addAttribute(name, '' + contents); | |
}; | |
} | |
function text(contents) { | |
return function(b) { | |
return (b || new NodeBuilder()).addText(contents); | |
} | |
} | |
// Straight-forward method looks like this: | |
var b = new NodeBuilder(); | |
b.startDocument(); | |
b.startElement('names'); | |
b.startElement('name'); | |
b.addAttribute('id', '123'); | |
b.addText('John'); | |
b.endElement(); | |
b.startElement('name'); | |
b.addAttribute('id', '234'); | |
b.addText('Patrick'); | |
b.endElement(); | |
b.startElement('name'); | |
b.addAttribute('id', '345'); | |
b.addText('Chris'); | |
b.endElement(); | |
b.endElement(); | |
b.endDocument(); | |
b.toNode(); | |
// Original NodeBuilder combined with arrow-notation | |
new NodeBuilder() | |
.addDocument(b => { | |
b.addElement('names', b => { | |
b.addElement('name', b => { | |
b.addAttribute('id', '123') | |
.addText('John'); | |
}) | |
.addElement('name', b => { | |
b.addAttribute('id', '234') | |
.addText('Patrick'); | |
}) | |
.addElement('name', b => { | |
b.addAttribute('id', '345') | |
.addText('Chris'); | |
}); | |
}); | |
}) | |
.toNode(); | |
// Fluent-notation approach: | |
document( | |
element('names', [ | |
element('name', [ | |
attribute('id', 123), | |
text('John') | |
]), | |
element('name', [ | |
attribute('id', 234), | |
text('Patrick') | |
]), | |
element('name', [ | |
attribute('id', 345), | |
text('Chris') | |
]) | |
]) | |
)().toNode(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yeah, you cannot insert attributes with xmlns prefix, those are reserved. addElement, and addAttribute allow a optional 3rd param that can be exposed on the fluent methods as well with only minor changes. You end up with something like: