Skip to content

Commit

Permalink
feat: add a function to verify and return Abilities.
Browse files Browse the repository at this point in the history
Given a list of strings representing capability names (Abilities), verify that all the strings are valid Abilities and return Abilities[].

Abilities[] is still just a list of strings, but this helps us play nice with Typescript.

Inspired by #1250
  • Loading branch information
travis committed Jan 8, 2024
1 parent 80037f9 commit 1274e71
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
22 changes: 22 additions & 0 deletions packages/w3up-client/src/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
import {
Store as StoreCapabilities,
Upload as UploadCapabilities,
abilitiesAsStrings,
} from '@web3-storage/capabilities'
import { CAR } from '@ucanto/transport'
import { Base } from './base.js'
Expand Down Expand Up @@ -54,6 +55,27 @@ export class Client extends Base {
this.coupon = new CouponAPI(agentData, options)
}

/**
* Verify and return Abilities.
*
* Given a list of strings representing capability names (Abilities),
* verify that all the strings are valid Abilities and return Abilities[].
*
* Abilities[] is still just a list of strings, but this helps us play
* nice with Typescript.
*
* @param {string[]} abilities
* @returns {import('@web3-storage/access').Abilities[]}
*/
static abilities(abilities) {
for (const ability of abilities) {
if (!abilitiesAsStrings.includes(/** @type {import('@web3-storage/access').Abilities} */(ability))) {
throw new Error(`${ability} is not a supported capability`)
}
}
return /** @type {import('@web3-storage/access').Abilities[]} */(abilities)
}

did() {
return this._agent.did()
}
Expand Down
13 changes: 13 additions & 0 deletions packages/w3up-client/test/client.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -480,4 +480,17 @@ describe('Client', () => {
assert.equal(typeof client.capability.upload.remove, 'function')
})
})

describe('abilities', () => {
it('should return the passed argument if all abilities are valid', async () => {
const abilities = ['store/add', 'upload/add']
assert.equal(Client.abilities(abilities), abilities)
})

it('should throw an error if one of the abilities is not supported', async () => {
assert.throws(() => {
Client.abilities(['foo/bar'])
})
})
})
})

0 comments on commit 1274e71

Please sign in to comment.