config.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. const extend = require('./util/extend');
  2. const EndpointAddress = {
  3. production: 'api.push.apple.com',
  4. development: 'api.sandbox.push.apple.com',
  5. };
  6. module.exports = function (dependencies) {
  7. const logger = dependencies.logger;
  8. const prepareCertificate = dependencies.prepareCertificate;
  9. const prepareToken = dependencies.prepareToken;
  10. const prepareCA = dependencies.prepareCA;
  11. function config(options) {
  12. const config = {
  13. token: null,
  14. cert: 'cert.pem',
  15. key: 'key.pem',
  16. ca: null,
  17. pfx: null,
  18. passphrase: null,
  19. production: process.env.NODE_ENV === 'production',
  20. address: null,
  21. port: 443,
  22. proxy: null,
  23. rejectUnauthorized: true,
  24. connectionRetryLimit: 10,
  25. heartBeat: 60000,
  26. requestTimeout: 5000,
  27. };
  28. validateOptions(options);
  29. extend(config, options);
  30. configureAddress(config);
  31. if (config.token) {
  32. delete config.cert;
  33. delete config.key;
  34. delete config.pfx;
  35. extend(config, { token: prepareToken(config.token) });
  36. } else {
  37. if (config.pfx || config.pfxData) {
  38. config.cert = options.cert;
  39. config.key = options.key;
  40. }
  41. extend(config, prepareCertificate(config));
  42. }
  43. extend(config, prepareCA(config));
  44. return config;
  45. }
  46. function validateOptions(options) {
  47. for (const key in options) {
  48. if (options[key] === null || options[key] === undefined) {
  49. logger(
  50. 'Option [' + key + '] is ' + options[key] + '. This may cause unexpected behaviour.'
  51. );
  52. }
  53. }
  54. if (options) {
  55. if (options.passphrase && typeof options.passphrase !== 'string') {
  56. throw new Error('Passphrase must be a string');
  57. }
  58. if (options.token) {
  59. validateToken(options.token);
  60. }
  61. }
  62. }
  63. return config;
  64. };
  65. function validateToken(token) {
  66. if (!token.keyId) {
  67. throw new Error('token.keyId is missing');
  68. } else if (typeof token.keyId !== 'string') {
  69. throw new Error('token.keyId must be a string');
  70. }
  71. if (!token.teamId) {
  72. throw new Error('token.teamId is missing');
  73. } else if (typeof token.teamId !== 'string') {
  74. throw new Error('token.teamId must be a string');
  75. }
  76. }
  77. function configureAddress(options) {
  78. if (!options.address) {
  79. if (options.production) {
  80. options.address = EndpointAddress.production;
  81. } else {
  82. options.address = EndpointAddress.development;
  83. }
  84. } else {
  85. if (options.address === EndpointAddress.production) {
  86. options.production = true;
  87. } else {
  88. options.production = false;
  89. }
  90. }
  91. }