Skip to content

Commit 7736741

Browse files
committed
Add fromObject static method
1 parent c3640bd commit 7736741

File tree

3 files changed

+46
-2
lines changed

3 files changed

+46
-2
lines changed

index.js

+30-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ class Attribute {
2828
if (options.type && typeof (options.type) !== 'string') {
2929
throw TypeError('options.type must be a string')
3030
}
31-
this.#type = options.type || ''
31+
this.type = options.type || ''
3232

3333
const values = options.values || options.vals || []
3434
if (options.vals) {
@@ -261,6 +261,35 @@ class Attribute {
261261
return result
262262
}
263263

264+
/**
265+
* Given an object of attribute types mapping to attribute values, construct
266+
* a set of Attributes.
267+
*
268+
* @param {object} obj Each key is an attribute type, and each value is an
269+
* attribute value or set of values.
270+
*
271+
* @returns {Attribute[]}
272+
*
273+
* @throws If an attribute cannot be constructed correctly.
274+
*/
275+
static fromObject (obj) {
276+
const attributes = []
277+
for (const [key, value] of Object.entries(obj)) {
278+
if (Array.isArray(value) === true) {
279+
attributes.push(new Attribute({
280+
type: key,
281+
values: value
282+
}))
283+
} else {
284+
attributes.push(new Attribute({
285+
type: key,
286+
values: [value]
287+
}))
288+
}
289+
}
290+
return attributes
291+
}
292+
264293
/**
265294
* Determine if an object represents an {@link Attribute}.
266295
*

index.test.js

+15
Original file line numberDiff line numberDiff line change
@@ -301,6 +301,21 @@ tap.test('#fromBer', t => {
301301
t.end()
302302
})
303303

304+
tap.test('#fromObject', t => {
305+
t.test('handles basic object', async t => {
306+
const attrs = Attribute.fromObject({
307+
foo: ['foo'],
308+
bar: 'bar',
309+
'baz;binary': Buffer.from([0x00])
310+
})
311+
for (const attr of attrs) {
312+
t.equal(Object.prototype.toString.call(attr), '[object LdapAttribute]')
313+
}
314+
})
315+
316+
t.end()
317+
})
318+
304319
tap.test('#isAttribute', t => {
305320
t.test('rejects non-object', async t => {
306321
t.equal(Attribute.isAttribute(42), false)

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
"name": "@ldapjs/attribute",
88
"homepage": "https://github.com/ldapjs/attribute",
99
"description": "API for handling LDAP entry attributes",
10-
"version": "1.0.0-rc.4",
10+
"version": "1.0.0-rc.5",
1111
"license": "MIT",
1212
"repository": {
1313
"type": "git",

0 commit comments

Comments
 (0)