UNPKG

@shopify/react-network

Version:

A collection of components that allow you to set common HTTP headers from within your React application

92 lines (87 loc) 2.71 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var network = require('@shopify/network'); var ServerCookieManager = require('./ServerCookieManager.js'); const EFFECT_ID = Symbol('network'); class NetworkManager { constructor({ headers, cookies } = {}) { this.effect = { id: EFFECT_ID, afterEachPass: () => { return this.redirectUrl == null; }, betweenEachPass: () => { this.reset(); } }; this.statusCodes = []; this.csp = new Map(); this.headers = new Map(); this.requestHeaders = normalizeHeaders(headers); this.cookies = new ServerCookieManager.ServerCookieManager(cookies); } reset() { this.statusCodes = []; this.csp.clear(); this.headers.clear(); this.cookies.clear(); this.redirectUrl = undefined; } getHeader(header) { return this.requestHeaders[header.toLowerCase()]; } setHeader(header, value) { this.headers.set(header, value); } redirectTo(url, status = network.StatusCode.Found) { this.addStatusCode(status); this.redirectUrl = url; } addStatusCode(statusCode) { this.statusCodes.push(statusCode); } addCspDirective(directive, value) { const normalizedValue = typeof value === 'string' ? [value] : value; const currentValue = this.csp.get(directive) || []; const normalizedCurrentValue = Array.isArray(currentValue) ? currentValue : [String(currentValue)]; const newValue = Array.isArray(normalizedValue) ? [...normalizedCurrentValue, ...normalizedValue] : normalizedValue; this.csp.set(directive, newValue); } extract() { const csp = this.csp.size === 0 ? undefined : [...this.csp].map(([key, value]) => { let printedValue; if (typeof value === 'boolean') { printedValue = ''; } else if (typeof value === 'string') { printedValue = value; } else { printedValue = value.join(' '); } return `${key}${printedValue ? ' ' : ''}${printedValue}`; }).join('; '); const headers = new Map(this.headers); if (csp) { headers.set(network.Header.ContentSecurityPolicy, csp); } return { status: this.statusCodes.length > 0 ? this.statusCodes.reduce((large, code) => Math.max(large, code), 0) : undefined, headers, cookies: this.cookies.getCookies(), redirectUrl: this.redirectUrl }; } } function normalizeHeaders(headers) { if (!headers) { return {}; } return Object.entries(headers).reduce((accumulator, [key, value]) => { accumulator[key.toLowerCase()] = value; return accumulator; }, {}); } exports.EFFECT_ID = EFFECT_ID; exports.NetworkManager = NetworkManager;