Skip to content

Commit cd272ad

Browse files
committed
restructure into a class
1 parent fbc00db commit cd272ad

10 files changed

+441
-456
lines changed

README.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,10 @@ npm install @cityssm/green-button-subscriber
3434
⭐ All output is parsed and returned as a fully typed object. ⭐
3535

3636
```javascript
37-
import * as greenButtonSubscriber from '@cityssm/green-button-subscriber'
37+
import { GreenButtonSubscriber } from '@cityssm/green-button-subscriber'
3838

3939
// Pass the base URL, client ID, client secret, etc.
40-
greenButtonSubscriber.setConfiguration(config)
40+
const greenButtonSubscriber = new GreenButtonSubscriber(config)
4141

4242
// Get the authorizations
4343
const greenButtonJson = await greenButtonSubscriber.getAuthorizations()

index.d.ts

+28-37
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,35 @@
11
import { type types as greenButtonTypes } from '@cityssm/green-button-parser';
22
import type { DateTimeFilters } from './types.js';
3-
export interface Configuration {
3+
export interface GreenButtonSubscriberConfiguration {
44
baseUrl: `${string}/`;
55
clientId?: string;
66
clientSecret?: string;
77
accessToken?: string;
88
}
9-
export declare function setConfiguration(configuration: Configuration): void;
10-
export declare function setUtilityApiConfiguration(apiToken: string, baseUrl?: `${string}/`): void;
11-
export declare function getEndpoint(endpoint: string, getParameters?: Record<string, string>): Promise<string | undefined>;
12-
export declare function getGreenButtonEndpoint(greenButtonEndpoint: `/${string}`, getParameters?: Record<string, string>): Promise<greenButtonTypes.GreenButtonJson | undefined>;
13-
export declare function getAuthorizations(): Promise<greenButtonTypes.GreenButtonJson | undefined>;
14-
export declare function getAuthorization(authorizationId: string): Promise<greenButtonTypes.GreenButtonJson | undefined>;
15-
export declare function getUsagePoints(authorizationId: string): Promise<greenButtonTypes.GreenButtonJson | undefined>;
16-
export declare function getMeterReadings(authorizationId: string, meterId: string): Promise<greenButtonTypes.GreenButtonJson | undefined>;
17-
export declare function getIntervalBlocks(authorizationId: string, meterId: string, readingId: string): Promise<greenButtonTypes.GreenButtonJson | undefined>;
18-
export declare function getUsageSummaries(authorizationId: string, meterId: string): Promise<greenButtonTypes.GreenButtonJson | undefined>;
19-
export declare function getElectricPowerQualitySummaries(authorizationId: string, meterId: string): Promise<greenButtonTypes.GreenButtonJson | undefined>;
20-
export declare function getCustomers(authorizationId: string): Promise<greenButtonTypes.GreenButtonJson | undefined>;
21-
export declare function getCustomerAccounts(authorizationId: string, customerId: string): Promise<greenButtonTypes.GreenButtonJson | undefined>;
22-
export declare function getCustomerAgreements(authorizationId: string, customerId: string, customerAccountId: string): Promise<greenButtonTypes.GreenButtonJson | undefined>;
23-
export declare function getBatchSubscriptionsByAuthorization(authorizationId: string, dateTimeFilters?: DateTimeFilters): Promise<greenButtonTypes.GreenButtonJson | undefined>;
24-
export declare function getBatchSubscriptionsByMeter(authorizationId: string, meterId: string, dateTimeFilters?: DateTimeFilters): Promise<greenButtonTypes.GreenButtonJson | undefined>;
25-
declare const _default: {
26-
setConfiguration: typeof setConfiguration;
27-
setUtilityApiConfiguration: typeof setUtilityApiConfiguration;
28-
getEndpoint: typeof getEndpoint;
29-
getGreenButtonEndpoint: typeof getGreenButtonEndpoint;
30-
getAuthorizations: typeof getAuthorizations;
31-
getAuthorization: typeof getAuthorization;
32-
getUsagePoints: typeof getUsagePoints;
33-
getMeterReadings: typeof getMeterReadings;
34-
getIntervalBlocks: typeof getIntervalBlocks;
35-
getUsageSummaries: typeof getUsageSummaries;
36-
getElectricPowerQualitySummaries: typeof getElectricPowerQualitySummaries;
37-
getCustomers: typeof getCustomers;
38-
getCustomerAccounts: typeof getCustomerAccounts;
39-
getCustomerAgreements: typeof getCustomerAgreements;
40-
getBatchSubscriptionsByAuthorization: typeof getBatchSubscriptionsByAuthorization;
41-
getBatchSubscriptionsByMeter: typeof getBatchSubscriptionsByMeter;
42-
};
43-
export default _default;
44-
export type * as types from '@cityssm/green-button-parser/types/entryTypes.js';
9+
export declare class GreenButtonSubscriber {
10+
_configuration: GreenButtonSubscriberConfiguration;
11+
_token: {
12+
access_token: string;
13+
expires_in: number;
14+
};
15+
constructor(configuration?: GreenButtonSubscriberConfiguration);
16+
setConfiguration(configuration: GreenButtonSubscriberConfiguration): void;
17+
setUtilityApiConfiguration(apiToken: string, baseUrl?: `${string}/`): void;
18+
getAccessToken(): Promise<void>;
19+
getEndpoint(endpoint: string, getParameters?: Record<string, string>): Promise<string | undefined>;
20+
getGreenButtonEndpoint(greenButtonEndpoint: `/${string}`, getParameters?: Record<string, string>): Promise<greenButtonTypes.GreenButtonJson | undefined>;
21+
getAuthorizations(): Promise<greenButtonTypes.GreenButtonJson | undefined>;
22+
getAuthorization(authorizationId: string): Promise<greenButtonTypes.GreenButtonJson | undefined>;
23+
getUsagePoints(authorizationId: string): Promise<greenButtonTypes.GreenButtonJson | undefined>;
24+
getMeterReadings(authorizationId: string, meterId: string): Promise<greenButtonTypes.GreenButtonJson | undefined>;
25+
getIntervalBlocks(authorizationId: string, meterId: string, readingId: string): Promise<greenButtonTypes.GreenButtonJson | undefined>;
26+
getUsageSummaries(authorizationId: string, meterId: string): Promise<greenButtonTypes.GreenButtonJson | undefined>;
27+
getElectricPowerQualitySummaries(authorizationId: string, meterId: string): Promise<greenButtonTypes.GreenButtonJson | undefined>;
28+
getCustomers(authorizationId: string): Promise<greenButtonTypes.GreenButtonJson | undefined>;
29+
getCustomerAccounts(authorizationId: string, customerId: string): Promise<greenButtonTypes.GreenButtonJson | undefined>;
30+
getCustomerAgreements(authorizationId: string, customerId: string, customerAccountId: string): Promise<greenButtonTypes.GreenButtonJson | undefined>;
31+
getBatchSubscriptionsByAuthorization(authorizationId: string, dateTimeFilters?: DateTimeFilters): Promise<greenButtonTypes.GreenButtonJson | undefined>;
32+
getBatchSubscriptionsByMeter(authorizationId: string, meterId: string, dateTimeFilters?: DateTimeFilters): Promise<greenButtonTypes.GreenButtonJson | undefined>;
33+
}
34+
export type { types } from '@cityssm/green-button-parser';
35+
export { helpers } from '@cityssm/green-button-parser';

index.js

+111-120
Original file line numberDiff line numberDiff line change
@@ -3,129 +3,120 @@ import axios from 'axios';
33
import Debug from 'debug';
44
import { formatDateTimeFiltersParameters } from './utilities.js';
55
const debug = Debug('green-button-subscriber');
6-
let _configuration;
7-
let _token;
8-
export function setConfiguration(configuration) {
9-
_configuration = configuration;
10-
}
11-
export function setUtilityApiConfiguration(apiToken, baseUrl = 'https://utilityapi.com/') {
12-
setConfiguration({
13-
baseUrl,
14-
accessToken: apiToken
15-
});
16-
}
17-
async function getAccessToken() {
18-
if (_configuration.accessToken !== undefined) {
19-
_token = {
20-
access_token: _configuration.accessToken,
21-
expires_in: Number.POSITIVE_INFINITY
22-
};
23-
return;
24-
}
25-
try {
26-
const authorizeUrl = `${_configuration.baseUrl}oauth/authorize`;
27-
debug(`Authorize URL: ${authorizeUrl}`);
28-
const response = await axios.post(authorizeUrl, {
29-
response_type: 'code',
30-
grant_type: 'client_credentials',
31-
client_id: _configuration.clientId,
32-
client_secret: _configuration.clientSecret
33-
}, {
34-
headers: {
35-
Referer: _configuration.baseUrl
36-
}
6+
export class GreenButtonSubscriber {
7+
_configuration;
8+
_token;
9+
constructor(configuration) {
10+
if (configuration !== undefined) {
11+
this.setConfiguration(configuration);
12+
}
13+
}
14+
setConfiguration(configuration) {
15+
this._configuration = configuration;
16+
}
17+
setUtilityApiConfiguration(apiToken, baseUrl = 'https://utilityapi.com/') {
18+
this.setConfiguration({
19+
baseUrl,
20+
accessToken: apiToken
3721
});
38-
_token = response.data;
39-
debug('Access token obtained successfully.');
40-
debug('Access Token:', _token.access_token);
4122
}
42-
catch (error) {
43-
debug('Error getting access token:', error.response.data);
23+
async getAccessToken() {
24+
if (this._configuration.accessToken !== undefined) {
25+
this._token = {
26+
access_token: this._configuration.accessToken,
27+
expires_in: Number.POSITIVE_INFINITY
28+
};
29+
return;
30+
}
31+
try {
32+
const authorizeUrl = `${this._configuration.baseUrl}oauth/authorize`;
33+
debug(`Authorize URL: ${authorizeUrl}`);
34+
const response = await axios.post(authorizeUrl, {
35+
response_type: 'code',
36+
grant_type: 'client_credentials',
37+
client_id: this._configuration.clientId,
38+
client_secret: this._configuration.clientSecret
39+
}, {
40+
headers: {
41+
Referer: this._configuration.baseUrl
42+
}
43+
});
44+
this._token = response.data;
45+
debug('Access token obtained successfully.');
46+
debug('Access Token:', this._token.access_token);
47+
}
48+
catch (error) {
49+
debug('Error getting access token:', error.response.data);
50+
}
4451
}
45-
}
46-
export async function getEndpoint(endpoint, getParameters = {}) {
47-
if (_token === undefined || Date.now() >= _token.expires_in * 1000) {
48-
debug('Token expired.');
49-
await getAccessToken();
50-
}
51-
const headers = {
52-
Authorization: `Bearer ${_token.access_token}`
53-
};
54-
const apiEndpoint = _configuration.baseUrl + endpoint;
55-
debug(`End Point: ${apiEndpoint}`);
56-
const requestOptions = {
57-
headers
58-
};
59-
if (getParameters !== undefined && Object.keys(getParameters).length > 0) {
60-
requestOptions.params = getParameters;
61-
}
62-
try {
63-
const response = await axios.get(apiEndpoint, requestOptions);
64-
return response.data;
65-
}
66-
catch (error) {
67-
debug('Error accessing API endpoint:', error.response.data);
68-
}
69-
return undefined;
70-
}
71-
export async function getGreenButtonEndpoint(greenButtonEndpoint, getParameters) {
72-
const greenButtonXml = await getEndpoint(`DataCustodian/espi/1_1/resource${greenButtonEndpoint}`, getParameters);
73-
if (greenButtonXml === undefined) {
52+
async getEndpoint(endpoint, getParameters = {}) {
53+
if (this._token === undefined ||
54+
Date.now() >= this._token.expires_in * 1000) {
55+
debug('Token expired.');
56+
await this.getAccessToken();
57+
}
58+
const headers = {
59+
Authorization: `Bearer ${this._token.access_token}`
60+
};
61+
const apiEndpoint = this._configuration.baseUrl + endpoint;
62+
debug(`End Point: ${apiEndpoint}`);
63+
const requestOptions = {
64+
headers
65+
};
66+
if (getParameters !== undefined && Object.keys(getParameters).length > 0) {
67+
requestOptions.params = getParameters;
68+
}
69+
try {
70+
const response = await axios.get(apiEndpoint, requestOptions);
71+
return response.data;
72+
}
73+
catch (error) {
74+
debug('Error accessing API endpoint:', error.response.data);
75+
}
7476
return undefined;
7577
}
76-
return await atomToGreenButtonJson(greenButtonXml);
77-
}
78-
export async function getAuthorizations() {
79-
return await getGreenButtonEndpoint('/Authorization');
80-
}
81-
export async function getAuthorization(authorizationId) {
82-
return await getGreenButtonEndpoint(`/Authorization/${authorizationId}`);
83-
}
84-
export async function getUsagePoints(authorizationId) {
85-
return await getGreenButtonEndpoint(`/Subscription/${authorizationId}/UsagePoint`);
86-
}
87-
export async function getMeterReadings(authorizationId, meterId) {
88-
return await getGreenButtonEndpoint(`/Subscription/${authorizationId}/UsagePoint/${meterId}/MeterReading`);
89-
}
90-
export async function getIntervalBlocks(authorizationId, meterId, readingId) {
91-
return await getGreenButtonEndpoint(`/Subscription/${authorizationId}/UsagePoint/${meterId}/MeterReading/${readingId}/IntervalBlock`);
92-
}
93-
export async function getUsageSummaries(authorizationId, meterId) {
94-
return await getGreenButtonEndpoint(`/Subscription/${authorizationId}/UsagePoint/${meterId}/UsageSummary`);
95-
}
96-
export async function getElectricPowerQualitySummaries(authorizationId, meterId) {
97-
return await getGreenButtonEndpoint(`/Subscription/${authorizationId}/UsagePoint/${meterId}/ElectricPowerQualitySummary`);
98-
}
99-
export async function getCustomers(authorizationId) {
100-
return await getGreenButtonEndpoint(`/RetailCustomer/${authorizationId}/Customer`);
101-
}
102-
export async function getCustomerAccounts(authorizationId, customerId) {
103-
return await getGreenButtonEndpoint(`/RetailCustomer/${authorizationId}/Customer/${customerId}/CustomerAccount`);
104-
}
105-
export async function getCustomerAgreements(authorizationId, customerId, customerAccountId) {
106-
return await getGreenButtonEndpoint(`/RetailCustomer/${authorizationId}/Customer/${customerId}/CustomerAccount/${customerAccountId}/CustomerAgreement`);
107-
}
108-
export async function getBatchSubscriptionsByAuthorization(authorizationId, dateTimeFilters) {
109-
return await getGreenButtonEndpoint(`/Batch/Subscription/${authorizationId}`, formatDateTimeFiltersParameters(dateTimeFilters));
110-
}
111-
export async function getBatchSubscriptionsByMeter(authorizationId, meterId, dateTimeFilters) {
112-
return await getGreenButtonEndpoint(`/Batch/Subscription/${authorizationId}/UsagePoint/${meterId}`, formatDateTimeFiltersParameters(dateTimeFilters));
78+
async getGreenButtonEndpoint(greenButtonEndpoint, getParameters) {
79+
const greenButtonXml = await this.getEndpoint(`DataCustodian/espi/1_1/resource${greenButtonEndpoint}`, getParameters);
80+
if (greenButtonXml === undefined) {
81+
return undefined;
82+
}
83+
return await atomToGreenButtonJson(greenButtonXml);
84+
}
85+
async getAuthorizations() {
86+
return await this.getGreenButtonEndpoint('/Authorization');
87+
}
88+
async getAuthorization(authorizationId) {
89+
return await this.getGreenButtonEndpoint(`/Authorization/${authorizationId}`);
90+
}
91+
async getUsagePoints(authorizationId) {
92+
return await this.getGreenButtonEndpoint(`/Subscription/${authorizationId}/UsagePoint`);
93+
}
94+
async getMeterReadings(authorizationId, meterId) {
95+
return await this.getGreenButtonEndpoint(`/Subscription/${authorizationId}/UsagePoint/${meterId}/MeterReading`);
96+
}
97+
async getIntervalBlocks(authorizationId, meterId, readingId) {
98+
return await this.getGreenButtonEndpoint(`/Subscription/${authorizationId}/UsagePoint/${meterId}/MeterReading/${readingId}/IntervalBlock`);
99+
}
100+
async getUsageSummaries(authorizationId, meterId) {
101+
return await this.getGreenButtonEndpoint(`/Subscription/${authorizationId}/UsagePoint/${meterId}/UsageSummary`);
102+
}
103+
async getElectricPowerQualitySummaries(authorizationId, meterId) {
104+
return await this.getGreenButtonEndpoint(`/Subscription/${authorizationId}/UsagePoint/${meterId}/ElectricPowerQualitySummary`);
105+
}
106+
async getCustomers(authorizationId) {
107+
return await this.getGreenButtonEndpoint(`/RetailCustomer/${authorizationId}/Customer`);
108+
}
109+
async getCustomerAccounts(authorizationId, customerId) {
110+
return await this.getGreenButtonEndpoint(`/RetailCustomer/${authorizationId}/Customer/${customerId}/CustomerAccount`);
111+
}
112+
async getCustomerAgreements(authorizationId, customerId, customerAccountId) {
113+
return await this.getGreenButtonEndpoint(`/RetailCustomer/${authorizationId}/Customer/${customerId}/CustomerAccount/${customerAccountId}/CustomerAgreement`);
114+
}
115+
async getBatchSubscriptionsByAuthorization(authorizationId, dateTimeFilters) {
116+
return await this.getGreenButtonEndpoint(`/Batch/Subscription/${authorizationId}`, formatDateTimeFiltersParameters(dateTimeFilters));
117+
}
118+
async getBatchSubscriptionsByMeter(authorizationId, meterId, dateTimeFilters) {
119+
return await this.getGreenButtonEndpoint(`/Batch/Subscription/${authorizationId}/UsagePoint/${meterId}`, formatDateTimeFiltersParameters(dateTimeFilters));
120+
}
113121
}
114-
export default {
115-
setConfiguration,
116-
setUtilityApiConfiguration,
117-
getEndpoint,
118-
getGreenButtonEndpoint,
119-
getAuthorizations,
120-
getAuthorization,
121-
getUsagePoints,
122-
getMeterReadings,
123-
getIntervalBlocks,
124-
getUsageSummaries,
125-
getElectricPowerQualitySummaries,
126-
getCustomers,
127-
getCustomerAccounts,
128-
getCustomerAgreements,
129-
getBatchSubscriptionsByAuthorization,
130-
getBatchSubscriptionsByMeter
131-
};
122+
export { helpers } from '@cityssm/green-button-parser';

0 commit comments

Comments
 (0)