Skip to content

Commit

Permalink
fix: validate perspective config (#252)
Browse files Browse the repository at this point in the history
  • Loading branch information
stipsan authored Jul 7, 2023
1 parent bf9f9b9 commit d6e0630
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {generateHelpUrl} from './generateHelpUrl'
import type {ClientConfig, InitializedClientConfig} from './types'
import type {ClientConfig, ClientPerspective, InitializedClientConfig} from './types'
import * as validate from './validators'
import * as warnings from './warnings'

Expand Down Expand Up @@ -27,6 +27,19 @@ export const validateApiVersion = function validateApiVersion(apiVersion: string
}
}

export const validateApiPerspective = function validateApiPerspective(perspective: string) {
switch (perspective as ClientPerspective) {
case 'previewDrafts':
case 'published':
case 'raw':
return
default:
throw new TypeError(
'Invalid API perspective string, expected `published`, `previewDrafts` or `raw`'
)
}
}

export const initConfig = (
config: Partial<ClientConfig>,
prevConfig: Partial<ClientConfig>
Expand All @@ -48,6 +61,10 @@ export const initConfig = (
throw new Error('Configuration must contain `projectId`')
}

if (typeof newConfig.perspective === 'string') {
validateApiPerspective(newConfig.perspective)
}

if (
'encodeSourceMapAtPath' in newConfig ||
'encodeSourceMap' in newConfig ||
Expand Down
16 changes: 16 additions & 0 deletions test/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,22 @@ describe('client', async () => {
expect(() => createClient({projectId: 'abc123', logger: console})).toThrow(/logger/)
})

test('throws on invalid perspective', () => {
expect(() => createClient({projectId: 'abc123', perspective: 'published'})).not.toThrow(
/Invalid API perspective/
)
expect(() => createClient({projectId: 'abc123', perspective: 'previewDrafts'})).not.toThrow(
/Invalid API perspective/
)
expect(() => createClient({projectId: 'abc123', perspective: 'raw'})).not.toThrow(
/Invalid API perspective/
)
// @ts-expect-error -- we want to test that it throws an error
expect(() => createClient({projectId: 'abc123', perspective: 'preview drafts'})).toThrow(
/Invalid API perspective/
)
})

test('throws on invalid project ids', () => {
expect(() => createClient({projectId: '*foo*'})).toThrow(/projectId.*?can only contain/i)
})
Expand Down

0 comments on commit d6e0630

Please sign in to comment.