ven.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. 'use strict';
  2. const {
  3. serialize: serializeCreatePartyRegistration,
  4. } = require('../xml/create-party-registration');
  5. const {
  6. parse: parseCreatedPartyRegistration,
  7. } = require('../xml/created-party-registration');
  8. const axios = require('axios');
  9. const { escape } = require('querystring');
  10. class Ven {
  11. constructor(
  12. endpoint,
  13. clientCertPem,
  14. commonName,
  15. venId,
  16. venName,
  17. registrationId,
  18. ) {
  19. if (!endpoint.endsWith('/')) endpoint += '/';
  20. this.endpoint = endpoint;
  21. this.clientCertHeader = escape(clientCertPem);
  22. this.venId = venId;
  23. this.registrationId = registrationId;
  24. this.venName = venName;
  25. this.commonName = commonName;
  26. }
  27. async register() {
  28. const message = {
  29. requestId: '2233',
  30. registrationId: this.registrationId,
  31. venId: this.venId,
  32. oadrProfileName: '2.0b',
  33. oadrTransportName: 'simplehttp',
  34. oadrReportOnly: false,
  35. oadrXmlSignature: false,
  36. oadrVenName: this.venName,
  37. oadrHttpPullModel: true,
  38. };
  39. const xml = serializeCreatePartyRegistration(message);
  40. const config = {
  41. headers: {
  42. 'Content-Type': 'application/xml',
  43. // these next 2 headers are provided manually for now, simulating what nginx is doing.
  44. SSL_CLIENT_S_DN_CN: this.commonName || 'no_client_cert',
  45. SSL_CLIENT_CERTIFICATE: this.clientCertHeader,
  46. },
  47. };
  48. // axios will automatically reject HTTP response codes outside the 200-299 range
  49. const httpResponse = await axios.post(
  50. `${this.endpoint}OpenADR2/Simple/2.0b/EiRegisterParty`,
  51. xml,
  52. config,
  53. );
  54. const registrationResponse = await parseCreatedPartyRegistration(
  55. httpResponse.data,
  56. );
  57. // but OpenADR provides its own response code in the XML envelope, we need to check that
  58. if (
  59. registrationResponse.responseCode < 200 ||
  60. registrationResponse.responseCode >= 300
  61. ) {
  62. throw new Error(
  63. 'Error during registration. ResponseCode=' +
  64. registrationResponse.responseCode +
  65. ', ResponseDescription=' +
  66. registrationResponse.responseDescription,
  67. );
  68. }
  69. // track registrationId for subsequent requests
  70. this.registrationId = registrationResponse.registrationId;
  71. return registrationResponse;
  72. }
  73. }
  74. module.exports = {
  75. Ven,
  76. };