'How to retrieve an http request headers item from a symbol map?

I am trying to retrieve a particular request header from an apolloserver request (i.e. the request object from a GraphQLRequestContext), inside a a plugin.

logging the headers object logs out as:

Headers {
  [Symbol(map)]: [Object: null prototype] {
    'content-type': [ 'application/json' ],
    user: [
      '{...(redacted)...}'
    ],
    'x-header-foo': [ '234' ],
    accept: [ '*/*' ],
    'content-length': [ '256' ],
    'user-agent': [ 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)' ],
    'accept-encoding': [ 'gzip,deflate' ],
    connection: [ 'close' ],
    host: [ 'localhost:3000' ]
  }
}

but headers['x-header-foo'] yields undefined. How do I get the header value? I have not used symbols much so far.



Solution 1:[1]

As you said rightly, Headers are Symbols and not Objects, so to get value, you use the get method

Read more about Symbols here Symbol is a built-in object whose constructor returns a symbol primitive — also called a Symbol value or just a Symbol — that's guaranteed to be unique.

Headers are Symbols and not Objects, so to get value, you use the get method

const host = req.headers.get("host"); // stackoverflow.com

If you wish to destructure using Symbols:

let symbol = Symbol()
let obj = { [symbol] : 'value'}
let { [symbol]: alias } = obj

console.log(alias)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ChukwuEmeka