import { R } from '../libs'; import { GraphqlOperation, GraphqlMiddlewareHandler, GraphqlHeaderRequest, GraphqlHeaderValue, IGraphqlInitOptions, GraphqlHeadersFactory, } from '../types'; export function headersMiddleware( headers?: IGraphqlInitOptions['headers'], ): GraphqlMiddlewareHandler { return (req, next) => { // Calculate the headers. // NB: Override the middleware headers with any headers passed // explitictly from the calling query/mutation context. const context = req.getContext(); let obj = {}; obj = headers ? toHeadersObject(req, headers) : {}; obj = context.headers ? { ...obj, ...context.headers } : obj; // Append the headers to the context. req.setContext({ headers: { ...(req.getContext().headers || {}), ...obj, }, }); // Finish up. return next ? next(req) : null; }; } function toHeadersObject( req: GraphqlOperation, headers: IGraphqlInitOptions['headers'], ) { const asKeyValuePairs = (headers: IGraphqlInitOptions['headers']) => { const getValue = (value: GraphqlHeaderValue) => { return R.is(Function, value) ? (value as GraphqlHeaderRequest)(req) : (value as string); }; const headerObject = (R.is(Function, headers) ? (headers as GraphqlHeadersFactory)() : headers) || {}; return Object.keys(headerObject).map(key => ({ key, value: getValue(headerObject[key]), })); }; return asKeyValuePairs(headers).reduce((result, header) => { result[header.key] = header.value; return result; }, {}); }