determineApolloConfig.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { createHash } from '@apollo/utils.createhash';
  2. export function determineApolloConfig(input, logger) {
  3. const apolloConfig = {};
  4. const { APOLLO_KEY, APOLLO_GRAPH_REF, APOLLO_GRAPH_ID, APOLLO_GRAPH_VARIANT, } = process.env;
  5. if (input?.key) {
  6. apolloConfig.key = input.key.trim();
  7. }
  8. else if (APOLLO_KEY) {
  9. apolloConfig.key = APOLLO_KEY.trim();
  10. }
  11. if ((input?.key ?? APOLLO_KEY) !== apolloConfig.key) {
  12. logger.warn('The provided API key has unexpected leading or trailing whitespace. ' +
  13. 'Apollo Server will trim the key value before use.');
  14. }
  15. if (apolloConfig.key) {
  16. assertValidHeaderValue(apolloConfig.key);
  17. }
  18. if (apolloConfig.key) {
  19. apolloConfig.keyHash = createHash('sha512')
  20. .update(apolloConfig.key)
  21. .digest('hex');
  22. }
  23. if (input?.graphRef) {
  24. apolloConfig.graphRef = input.graphRef;
  25. }
  26. else if (APOLLO_GRAPH_REF) {
  27. apolloConfig.graphRef = APOLLO_GRAPH_REF;
  28. }
  29. const graphId = input?.graphId ?? APOLLO_GRAPH_ID;
  30. const graphVariant = input?.graphVariant ?? APOLLO_GRAPH_VARIANT;
  31. if (apolloConfig.graphRef) {
  32. if (graphId) {
  33. throw new Error('Cannot specify both graph ref and graph ID. Please use ' +
  34. '`apollo.graphRef` or `APOLLO_GRAPH_REF` without also setting the graph ID.');
  35. }
  36. if (graphVariant) {
  37. throw new Error('Cannot specify both graph ref and graph variant. Please use ' +
  38. '`apollo.graphRef` or `APOLLO_GRAPH_REF` without also setting the graph variant.');
  39. }
  40. }
  41. else if (graphId) {
  42. apolloConfig.graphRef = graphVariant
  43. ? `${graphId}@${graphVariant}`
  44. : graphId;
  45. }
  46. return apolloConfig;
  47. }
  48. function assertValidHeaderValue(value) {
  49. const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/g;
  50. if (invalidHeaderCharRegex.test(value)) {
  51. const invalidChars = value.match(invalidHeaderCharRegex);
  52. throw new Error(`The API key provided to Apollo Server contains characters which are invalid as HTTP header values. The following characters found in the key are invalid: ${invalidChars.join(', ')}. Valid header values may only contain ASCII visible characters. If you think there is an issue with your key, please contact Apollo support.`);
  53. }
  54. }
  55. //# sourceMappingURL=determineApolloConfig.js.map