Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
@skava/graphql / src / deps / setCookiesOnResponse.ts
Size: Mime:
import { isObj, isArray, EMPTY_OBJ } from 'exotic'
import { Request as ExpressRequest, Response as ExpressResponse } from 'express'
import { Context } from '../typings'
import tough, { Cookie } from 'tough-cookie'

/* Cookies suck :( */

const hasResponseCookies = (response: Response) => {
  return isObj(response.headers) && isArray(response.headers._headers['set-cookie'])
  // return isArray(response.headers.get('set-cookie'))
}

const parseCookie = (cookie: string): Cookie.Properties => {
  return (cookie && Cookie.parse(cookie, { loose: true }).toJSON()) || EMPTY_OBJ
}

const decodeCookieValue = (cookieVal: string): string => {
  const first = decodeURIComponent(cookieVal)
  return decodeURIComponent(first)
}

/* Because Invalid API cookies breaks things*/
const toCookies = (response: Response): string[] => {
  // ._headers is hidden from types, .get returns just 1
  const headers = (response.headers as any)._headers
  if (hasResponseCookies(response)) {
    return headers['set-cookie']
  } else {
    return [headers['set-cookie']]
  }
}

const setCookiesOnResponse = (response: Response, context: Context): void => {
  toCookies(response)
    .filter(cookie => {
      const parsed = parseCookie(cookie)
      return parsed.value !== undefined
    })
    .forEach(cookie => {
      // @todo typing here
      const { key, value, maxAge, path } = parseCookie(cookie)
      const fixedValue = decodeCookieValue(value)

      console.log({ key, value, maxAge, path, fixedValue })

      context.res.cookie(key, fixedValue, {
        // domain: parsed.domain,
        maxAge: maxAge * 1000,
        path,
        encode: String,
      })
    })

  // example to send it back
  // const serializedCookies = cookies.map(cookie => {
  //   const mostlyFixed = cookie
  //     .replace('Domain=skavaone.com;', '')
  //     .replace(';Secure', ';')
  //     .replace('Max-Age=3600;', 'Max-Age=3600000;')
  //   const withoutExpires = mostlyFixed.split('Expires=').shift()
  //   return withoutExpires
  // })
  // context.res.header('_Cookies', serializedCookies.join('|||'))
}

export { setCookiesOnResponse, hasResponseCookies }
export default setCookiesOnResponse