Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions src/utils/http.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { describe, it, expect, vi, afterEach } from 'vitest'
import { createValidateStatusCode, HttpError, Response } from '.'

const makeResponse = (statusCode: number, body = '{"sys":{"type":"Error"}}') =>
({ statusCode, body }) as Response

describe('createValidateStatusCode', () => {
afterEach(() => {
vi.restoreAllMocks()
})

it('returns the response when status code is allowed', () => {
const validate = createValidateStatusCode([200, 201])
const response = makeResponse(201)
expect(validate(response)).toBe(response)
})

it('throws HttpError when status code is not allowed', () => {
const validate = createValidateStatusCode([201])
const response = makeResponse(404, '{"sys":{"type":"Error","id":"NotFound"}}')
expect(() => validate(response)).toThrow(HttpError)
})

it('does not write to stdout when throwing', () => {
const consoleSpy = vi.spyOn(console, 'log')
const validate = createValidateStatusCode([201])
try {
validate(makeResponse(404))
} catch {
// expected
}
expect(consoleSpy).not.toHaveBeenCalled()
})
})
5 changes: 4 additions & 1 deletion src/utils/http.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import got, { ExtendOptions, Got, HTTPError, Response as GotResponse } from 'got'
import { createLogger } from './logger'

const log = createLogger({ namespace: 'utils/http' })

const config = {
prefixUrl: process.env.BASE_URL || 'https://api.contentful.com',
Expand All @@ -11,7 +14,7 @@ export const createHttpClient = (configOverride: ExtendOptions = {}) => {

export const createValidateStatusCode = (allowedStatusCodes: number[]) => (response: Response) => {
if (!allowedStatusCodes.includes(response.statusCode)) {
console.log(response.body)
Comment thread
juanibiapina-ctfl marked this conversation as resolved.
log(`unexpected status code %d: %s`, response.statusCode, response.body)
throw new HTTPError(response)
}
return response
Expand Down