Skip to content

Commit

Permalink
feat: add tests and better typechecking
Browse files Browse the repository at this point in the history
good idea to make sure these are actually ServiceDIDs since that's what the types want
  • Loading branch information
travis committed Aug 11, 2023
1 parent 30d2e5a commit f1a846b
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 2 deletions.
10 changes: 8 additions & 2 deletions upload-api/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,19 @@ export function getServiceSigner(config) {
}

/**
* Given a string, parse into provider service DIDs.
* Given a string, parse into provider ServiceDIDs.
*
* @param {string} providersEnvVar
* @returns {import('@web3-storage/upload-api').ServiceDID[]}
*/
export function parseProviders(providersEnvVar) {
return /** @type {import('@web3-storage/upload-api').ServiceDID[]} */(
providersEnvVar.split(',').map(s => s.trim())
providersEnvVar.split(',').map(s => {
const did = DID.parse(s.trim()).did()
if (!did.startsWith('did:web:')) {
throw new Error(`Invalid ServiceDID - ServiceDID must be a did:web: ${did}`)
}
return did
})
)
}
45 changes: 45 additions & 0 deletions upload-api/test/config.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,48 @@ test('getServiceSigner errors if config.UPLOAD_API_DID is provided but not a DID
})
}, { message: /^Invalid DID/ })
})

test('parseProviders parses one DID', async (t) => {
t.deepEqual(
configModule.parseProviders('did:web:example.com'),
['did:web:example.com']
)
})

test('parseProviders parses more than one DID', async (t) => {
t.deepEqual(
configModule.parseProviders('did:web:example.com,did:web:two.example.com'),
['did:web:example.com', 'did:web:two.example.com']
)

t.deepEqual(
configModule.parseProviders('did:web:example.com,did:web:two.example.com,did:web:three.example.com'),
['did:web:example.com', 'did:web:two.example.com', 'did:web:three.example.com']
)
})

test('parseProviders trims space around dids', async (t) => {
t.deepEqual(
configModule.parseProviders(' did:web:example.com, did:web:two.example.com '),
['did:web:example.com', 'did:web:two.example.com']
)
})

test('parseProviders throws an exception if a non-DID is provided', async (t) => {
t.throws(
() => configModule.parseProviders('http://example.com'),
{ message: /^Invalid DID/}
)
})

test('parseProviders throws an exception if a non-ServiceDID is provided', async (t) => {
t.throws(
() => configModule.parseProviders('did:mailto:abc123'),
{ message: /^Invalid ServiceDID/}
)

t.throws(
() => configModule.parseProviders('did:key:z6Mkfy8k2JJUdNWCJtvzYrko5QRc7GXP6pksKDG19gxYzyi4'),
{ message: /^Invalid ServiceDID/}
)
})

0 comments on commit f1a846b

Please sign in to comment.