Skip to content

Commit

Permalink
Handling case where options.headers is of type window.Headers
Browse files Browse the repository at this point in the history
  • Loading branch information
megoth committed Nov 12, 2018
1 parent ee07382 commit 3a5d62b
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 4 deletions.
25 changes: 25 additions & 0 deletions src/__test__/fetch-util.spec.js
@@ -0,0 +1,25 @@
// @flow
/* eslint-env jest */
/* global Headers */

import { copyHeaders } from '../fetch-util'

describe('copyHeaders', () => {
it('returns an object', () => expect(copyHeaders({})).toEqual({}))
it('returns a copy of whatever is passed in as first param', () =>
expect(copyHeaders({ foo: 42 })).toEqual({ foo: 42 }))
it('handles option.headers as object', () =>
expect(copyHeaders({ foo: 42 }, { headers: { bar: 1337 } })).toEqual({
foo: 42,
bar: 1337
}))
xit('handles options.headers as Headers', () => {
// Enable this when there is support for window.Headers
const headers = new Headers()
headers.append('bar', '1337')
expect(copyHeaders({ foo: '42' }, { headers })).toEqual({
foo: '42',
bar: '1337'
})
})
})
17 changes: 17 additions & 0 deletions src/fetch-util.js
@@ -0,0 +1,17 @@
export function copyHeaders(newHeaders, oldOptions = {}) {
return {
...normalizeHeaders(oldOptions.headers),
...normalizeHeaders(newHeaders)
}
}

function normalizeHeaders(headers = {}) {
if (!headers.forEach) {
return headers
}
const newHeaders = {}
headers.forEach((value, key) => {
newHeaders[key] = value
})
return newHeaders
}
11 changes: 7 additions & 4 deletions src/webid-oidc.js
Expand Up @@ -9,6 +9,7 @@ import { currentUrl, navigateTo, toUrlString } from './url-util'
import type { webIdOidcSession } from './session'
import type { AsyncStorage } from './storage'
import { defaultStorage, getData, updateStorage } from './storage'
import { copyHeaders } from './fetch-util'

export async function login(
idp: string,
Expand Down Expand Up @@ -191,10 +192,12 @@ export async function fetchWithCredentials(
const authenticatedOptions = {
...options,
credentials: 'include',
headers: {
...(options && options.headers ? options.headers : {}),
authorization: `Bearer ${popToken}`
}
headers: copyHeaders(
{
authorization: `Bearer ${popToken}`
},
options
)
}
return fetch(input, authenticatedOptions)
}

0 comments on commit 3a5d62b

Please sign in to comment.